Skip to main content

manabrew_engine/card/
valid_filter.rs

1//! Shared card/player filter matching used across triggers, static abilities,
2//! replacement effects, and combat. Consolidates 34 duplicate implementations.
3//!
4//! This module provides canonical implementations for matching cards and players
5//! against filter expressions like "Creature.YouCtrl" or "Opponent".
6//!
7//! **Filter Syntax:**
8//!
9//! Card filters are dot-separated: "Creature.YouCtrl.nonToken"
10//! - Comma separates OR conditions: "Creature,Artifact" matches either
11//! - Dot separates qualifiers: "Creature.YouCtrl" matches creatures you control
12//! - Plus separates compound conditions: "YouCtrl+kicked" matches both
13//!
14//! **Type parts:**
15//! - Card, Permanent, Creature, Land, Artifact, Enchantment, Planeswalker, Instant, Sorcery
16//! - Subtypes: "Zombie", "Wall", "Forest", etc.
17//!
18//! **Qualifiers:**
19//! - Controller: YouCtrl, OppCtrl, YouControl, OpponentCtrl
20//! - Self: Self, Other, StrictlyOther
21//! - Token: token, nonToken
22//! - Type negation: nonCreature, nonLand
23//! - State: tapped, untapped, kicked
24//! - Counters: counters_GE3_P1P1, counters_EQ1_Charge
25//! - CMC: cmcEQ1, cmcLE3, cmcGE5
26//! - Color: White, Blue, Black, Red, Green, Colorless, multicolor
27//! - Combat: DamagedBy
28//! - Attachment: EnchantedBy
29
30use forge_foundation::color::Color;
31use forge_foundation::mana::ManaAtom;
32use forge_foundation::ZoneType;
33
34use crate::card::Card;
35use crate::combat::{CombatState, DefenderId};
36use crate::core::HasSVars;
37use crate::game::GameState;
38use crate::ids::{CardId, PlayerId};
39use crate::parsing::compare::compare_expr;
40use crate::parsing::keys;
41use crate::parsing::{
42    cached_compiled_selector, CardColorSelector, CardIdentitySelector, CardSelectorType,
43    CardStateSelector, CardSupertypeSelector, CompiledSelector, ContextPredicate,
44    ControllerSelector, NumericSelectorProperty, ParsedParams, RelationPredicate, Selector,
45    SelectorCompareOperator, SelectorNumericOperand, SelectorPredicate, TargetRef,
46};
47use crate::spellability::SpellAbility;
48
49fn requirement_controller(game: &GameState, source: &Card) -> PlayerId {
50    let mut controller = source.controller;
51
52    // Java parity: during trigger resolution, use the resolving trigger's
53    // activating player rather than the host card's current controller.
54    if !game.stack.is_empty()
55        && game.stack.is_resolving()
56        && game.stack.cur_resolving_card() == Some(source.id)
57    {
58        if let Some(entry) = game.stack.peek() {
59            if entry.spell_ability.is_trigger {
60                controller = entry.spell_ability.activating_player;
61            }
62        }
63    }
64
65    controller
66}
67
68fn requirement_amount(
69    source: &Card,
70    svar_source: &dyn HasSVars,
71    expr: &str,
72    game: &GameState,
73) -> i32 {
74    let raw_value = svar_source
75        .get_svar(expr)
76        .or_else(|| source.get_s_var(expr))
77        .unwrap_or(expr)
78        .trim();
79
80    if let Ok(n) = raw_value.parse::<i32>() {
81        return n;
82    }
83    if let Some(stripped) = raw_value.strip_prefix('+') {
84        if let Ok(n) = stripped.parse::<i32>() {
85            return n;
86        }
87    }
88    if let Some(stripped) = raw_value.strip_prefix('-') {
89        return -requirement_amount(source, svar_source, stripped.trim(), game);
90    }
91
92    if raw_value.starts_with("Count$") {
93        return crate::svar::resolve_count_svar(raw_value, game, source.id, source.controller);
94    }
95
96    let sa = crate::spellability::SpellAbility::new_simple(
97        Some(source.id),
98        requirement_controller(game, source),
99        &format!("DB$ Internal | Amount$ {raw_value}"),
100    );
101    let resolved = crate::svar::resolve_numeric_value(game, &sa, raw_value, i32::MIN);
102    if resolved != i32::MIN {
103        return resolved;
104    }
105
106    0
107}
108
109fn compare_requirement_amount(
110    source: &Card,
111    svar_source: &dyn HasSVars,
112    compare: &str,
113    game: &GameState,
114    left: i32,
115) -> bool {
116    let operator = compare.get(..compare.len().min(2)).unwrap_or("GE");
117    let operand_expr = compare.get(compare.len().min(2)..).unwrap_or("1");
118    let operand = requirement_amount(source, svar_source, operand_expr, game);
119    compare_expr(left, &format!("{operator}{operand}"))
120}
121
122/// Typed requirement bag for Java `CardTraitBase.meetsCommonRequirements(params)`.
123///
124/// Only params consumed by that Java method belong here. This keeps the shared
125/// requirement gate reusable across trigger, spell ability, static ability, and
126/// replacement IRs without passing the full legacy `Params` map at runtime.
127#[derive(Debug, Clone, PartialEq, Eq, Default)]
128pub struct CardTraitRequirementsIr {
129    metalcraft: Option<String>,
130    delirium: Option<String>,
131    threshold: Option<String>,
132    hellbent: Option<String>,
133    bloodthirst: Option<String>,
134    fateful_hour: Option<String>,
135    monarch: Option<String>,
136    revolt: Option<String>,
137    desert: Option<String>,
138    blessing: Option<String>,
139    day_time: Option<String>,
140    adamant: Option<String>,
141    life_total: Option<String>,
142    life_amount: Option<String>,
143    is_present: Option<String>,
144    is_present_selector: Option<CompiledSelector>,
145    present_compare: Option<String>,
146    present_player: Option<String>,
147    present_zone: Option<String>,
148    present_defined: Option<String>,
149    is_present2: Option<String>,
150    is_present2_selector: Option<CompiledSelector>,
151    present_compare2: Option<String>,
152    present_player2: Option<String>,
153    present_zone2: Option<String>,
154    check_defined_player: Option<String>,
155    defined_player_compare: Option<String>,
156    check_svar: Option<String>,
157    svar_compare: Option<String>,
158    check_second_svar: Option<String>,
159    second_svar_compare: Option<String>,
160    mana_spent: Option<String>,
161    mana_not_spent: Option<String>,
162    werewolf_transform_condition: bool,
163    werewolf_untransform_condition: bool,
164    class_level: Option<String>,
165    condition: Option<String>,
166}
167
168impl CardTraitRequirementsIr {
169    pub fn from_key_values<'a, I>(
170        entries: I,
171        is_present_selector: Option<CompiledSelector>,
172        is_present2_selector: Option<CompiledSelector>,
173    ) -> Self
174    where
175        I: IntoIterator<Item = (&'a str, &'a str)>,
176    {
177        let mut ir = Self::default();
178        for (key, value) in entries {
179            ir.set(key, value);
180        }
181        ir.is_present_selector = is_present_selector;
182        ir.is_present2_selector = is_present2_selector;
183        ir
184    }
185
186    pub fn from_parsed(params: &ParsedParams<'_>) -> Self {
187        let mut ir = Self::from_key_values(
188            params
189                .entries()
190                .iter()
191                .map(|entry| (entry.key, entry.value)),
192            None,
193            None,
194        );
195        ir.is_present_selector = ir.is_present.as_deref().map(cached_compiled_selector);
196        ir.is_present2_selector = ir.is_present2.as_deref().map(cached_compiled_selector);
197        ir
198    }
199
200    pub fn is_empty(&self) -> bool {
201        self.metalcraft.is_none()
202            && self.delirium.is_none()
203            && self.threshold.is_none()
204            && self.hellbent.is_none()
205            && self.bloodthirst.is_none()
206            && self.fateful_hour.is_none()
207            && self.monarch.is_none()
208            && self.revolt.is_none()
209            && self.desert.is_none()
210            && self.blessing.is_none()
211            && self.day_time.is_none()
212            && self.adamant.is_none()
213            && self.life_total.is_none()
214            && self.is_present.is_none()
215            && self.is_present2.is_none()
216            && self.check_defined_player.is_none()
217            && self.check_svar.is_none()
218            && self.check_second_svar.is_none()
219            && self.mana_spent.is_none()
220            && self.mana_not_spent.is_none()
221            && !self.werewolf_transform_condition
222            && !self.werewolf_untransform_condition
223            && self.class_level.is_none()
224            && self.condition.is_none()
225    }
226
227    pub fn meets(&self, game: &GameState, source: &Card, svar_source: &dyn HasSVars) -> bool {
228        meets_card_trait_requirements(self, game, source, svar_source)
229    }
230
231    fn set(&mut self, key: &str, value: &str) {
232        match key {
233            "Metalcraft" => self.metalcraft = Some(value.to_string()),
234            "Delirium" => self.delirium = Some(value.to_string()),
235            "Threshold" => self.threshold = Some(value.to_string()),
236            "Hellbent" => self.hellbent = Some(value.to_string()),
237            "Bloodthirst" => self.bloodthirst = Some(value.to_string()),
238            "FatefulHour" => self.fateful_hour = Some(value.to_string()),
239            "Monarch" => self.monarch = Some(value.to_string()),
240            "Revolt" => self.revolt = Some(value.to_string()),
241            "Desert" => self.desert = Some(value.to_string()),
242            "Blessing" => self.blessing = Some(value.to_string()),
243            "DayTime" => self.day_time = Some(value.to_string()),
244            "Adamant" => self.adamant = Some(value.to_string()),
245            "LifeTotal" => self.life_total = Some(value.to_string()),
246            "LifeAmount" => self.life_amount = Some(value.to_string()),
247            keys::IS_PRESENT => self.is_present = Some(value.to_string()),
248            keys::PRESENT_COMPARE => self.present_compare = Some(value.to_string()),
249            keys::PRESENT_PLAYER => self.present_player = Some(value.to_string()),
250            keys::PRESENT_ZONE => self.present_zone = Some(value.to_string()),
251            "PresentDefined" => self.present_defined = Some(value.to_string()),
252            "IsPresent2" => self.is_present2 = Some(value.to_string()),
253            "PresentCompare2" => self.present_compare2 = Some(value.to_string()),
254            "PresentPlayer2" => self.present_player2 = Some(value.to_string()),
255            "PresentZone2" => self.present_zone2 = Some(value.to_string()),
256            "CheckDefinedPlayer" => self.check_defined_player = Some(value.to_string()),
257            "DefinedPlayerCompare" => self.defined_player_compare = Some(value.to_string()),
258            keys::CHECK_SVAR => self.check_svar = Some(value.to_string()),
259            keys::SVAR_COMPARE => self.svar_compare = Some(value.to_string()),
260            "CheckSecondSVar" => self.check_second_svar = Some(value.to_string()),
261            "SecondSVarCompare" => self.second_svar_compare = Some(value.to_string()),
262            "ManaSpent" => self.mana_spent = Some(value.to_string()),
263            "ManaNotSpent" => self.mana_not_spent = Some(value.to_string()),
264            "WerewolfTransformCondition" => self.werewolf_transform_condition = true,
265            "WerewolfUntransformCondition" => self.werewolf_untransform_condition = true,
266            "ClassLevel" => self.class_level = Some(value.to_string()),
267            keys::CONDITION => self.condition = Some(value.to_string()),
268            _ => {}
269        }
270    }
271}
272
273fn check_boolean_requirement(value: Option<&str>, actual: bool) -> bool {
274    value.is_none_or(|value| value.eq_ignore_ascii_case("True") == actual)
275}
276
277fn player_life_for_requirement(game: &GameState, source: &Card, who: &str) -> i32 {
278    let controller = requirement_controller(game, source);
279    match who {
280        "You" => game.player(controller).life,
281        "OpponentSmallest" => game
282            .alive_players()
283            .into_iter()
284            .filter(|&pid| pid != controller)
285            .map(|pid| game.player(pid).life)
286            .min()
287            .unwrap_or(1),
288        "OpponentGreatest" => game
289            .alive_players()
290            .into_iter()
291            .filter(|&pid| pid != controller)
292            .map(|pid| game.player(pid).life)
293            .max()
294            .unwrap_or(1),
295        "ActivePlayer" => game.player(game.active_player()).life,
296        _ => 1,
297    }
298}
299
300fn collect_present_cards(
301    game: &GameState,
302    source: &Card,
303    defined: Option<&str>,
304    present_player: &str,
305    present_zone: ZoneType,
306) -> Vec<CardId> {
307    if let Some(defined) = defined {
308        return crate::ability::ability_utils::get_defined_cards(
309            game,
310            Some(source.id),
311            defined,
312            Some(requirement_controller(game, source)),
313        );
314    }
315
316    let controller = requirement_controller(game, source);
317    let mut cards = Vec::new();
318
319    if present_player.eq_ignore_ascii_case("You") || present_player.eq_ignore_ascii_case("Any") {
320        cards.extend(game.cards_in_zone(present_zone, controller).iter().copied());
321    }
322    if present_player.eq_ignore_ascii_case("Opponent") || present_player.eq_ignore_ascii_case("Any")
323    {
324        for pid in game.alive_players() {
325            if pid != controller {
326                cards.extend(game.cards_in_zone(present_zone, pid).iter().copied());
327            }
328        }
329    }
330
331    cards
332}
333
334fn paying_color_count(paying_mana_to_cast: &[u16], color_mask: u16) -> usize {
335    paying_mana_to_cast
336        .iter()
337        .filter(|&&atom| atom == color_mask)
338        .count()
339}
340
341fn has_all_spent_colors(colors_spent_to_cast: u16, colors: u16) -> bool {
342    colors != 0 && (colors_spent_to_cast & colors) == colors
343}
344
345/// Check if a card matches a filter expression like "Creature.YouCtrl".
346/// Returns true if `valid` is empty or the card satisfies all parts.
347///
348/// # Examples
349///
350/// ```ignore
351/// // Matches any creature you control:
352/// matches_valid_card("Creature.YouCtrl", creature, source)
353///
354/// // Matches either creatures or artifacts:
355/// matches_valid_card("Creature,Artifact", card, source)
356///
357/// // Matches creatures you control that are tokens:
358/// matches_valid_card("Creature.YouCtrl.token", card, source)
359/// ```
360pub fn matches_valid_card(valid: &str, card: &Card, source: &Card) -> bool {
361    matches_valid_card_selector(&cached_compiled_selector(valid), card, source)
362}
363
364#[cfg(debug_assertions)]
365fn legacy_matches_valid_card(valid: &str, card: &Card, context: MatchContext<'_>) -> bool {
366    let valid = valid.trim();
367    if valid.is_empty() {
368        return true;
369    }
370
371    // Comma-separated = OR conditions.
372    // Each comma-delimited part is a separate filter; the card matches if ANY part matches.
373    // Parts may contain dots (e.g. "Card.Self,Elemental.Other+YouCtrl").
374    if valid.contains(',') {
375        return valid
376            .split(',')
377            .any(|part| matches_single_valid_card(part.trim(), card, context));
378    }
379
380    matches_single_valid_card(valid, card, context)
381}
382
383/// Convenience wrapper: None means "no filter" → always matches.
384pub fn matches_valid_card_opt(valid: Option<&str>, card: &Card, source: &Card) -> bool {
385    match valid {
386        None => true,
387        Some(v) => matches_valid_card(v, card, source),
388    }
389}
390
391/// Match a precompiled selector against a card without reparsing the
392/// comma/dot/plus selector structure.
393pub fn matches_valid_card_selector(
394    selector: &CompiledSelector,
395    card: &Card,
396    source: &Card,
397) -> bool {
398    matches_valid_card_selector_with_context(selector, card, MatchContext::from_source(source))
399}
400
401pub fn matches_valid_card_selector_in_game(
402    selector: &CompiledSelector,
403    card: &Card,
404    source: &Card,
405    game: &GameState,
406) -> bool {
407    matches_valid_card_selector_with_context(
408        selector,
409        card,
410        MatchContext::from_source(source).with_game(game),
411    )
412}
413
414#[derive(Debug, Clone, Copy)]
415pub struct MatchContext<'a> {
416    pub source_card: &'a Card,
417    pub source_controller: PlayerId,
418    pub targeted_cards: &'a [CardId],
419    pub targeted_players: &'a [PlayerId],
420    pub remembered_cards: &'a [CardId],
421    pub remembered_players: &'a [PlayerId],
422    pub trigger_remembered_cards: &'a [CardId],
423    pub triggering_card: Option<CardId>,
424    pub triggering_player: Option<PlayerId>,
425    pub combat: Option<&'a CombatState>,
426    pub game: Option<&'a GameState>,
427    pub spell_ability: Option<&'a SpellAbility>,
428}
429
430impl<'a> MatchContext<'a> {
431    pub fn from_source(source_card: &'a Card) -> Self {
432        Self {
433            source_card,
434            source_controller: source_card.controller,
435            targeted_cards: &[],
436            targeted_players: &[],
437            remembered_cards: &source_card.remembered_cards,
438            remembered_players: &source_card.remembered_players,
439            trigger_remembered_cards: &[],
440            triggering_card: None,
441            triggering_player: None,
442            combat: None,
443            game: None,
444            spell_ability: None,
445        }
446    }
447
448    pub fn with_game(mut self, game: &'a GameState) -> Self {
449        self.game = Some(game);
450        self
451    }
452
453    pub fn with_spell_ability(mut self, spell_ability: &'a SpellAbility) -> Self {
454        self.spell_ability = Some(spell_ability);
455        self
456    }
457
458    /// Override `source_controller` with an iterated player. Mirrors Java's
459    /// `CardLists.getValidCardCount(..., player, source, ctb)` signature
460    /// (`AbilityUtils.java:3380, 3389`), where `YouCtrl` resolves against the
461    /// iterated player rather than the source's controller — needed by
462    /// `PlayerCountOpponents$HighestValid X.YouCtrl` style SVars.
463    pub fn with_source_controller(mut self, player: PlayerId) -> Self {
464        self.source_controller = player;
465        self
466    }
467
468    pub fn with_combat(mut self, combat: &'a CombatState) -> Self {
469        self.combat = Some(combat);
470        self
471    }
472
473    pub fn with_targets(
474        mut self,
475        targeted_cards: &'a [CardId],
476        targeted_players: &'a [PlayerId],
477    ) -> Self {
478        self.targeted_cards = targeted_cards;
479        self.targeted_players = targeted_players;
480        self
481    }
482
483    pub fn with_triggering(
484        mut self,
485        triggering_card: Option<CardId>,
486        triggering_player: Option<PlayerId>,
487    ) -> Self {
488        self.triggering_card = triggering_card;
489        self.triggering_player = triggering_player;
490        self
491    }
492
493    pub fn with_trigger_remembered_cards(mut self, cards: &'a [CardId]) -> Self {
494        self.trigger_remembered_cards = cards;
495        self
496    }
497}
498
499/// Match a precompiled selector with explicit contextual state for predicates
500/// like `Attacking`, `TopLibrary`, and `ExiledWithSource`.
501pub fn matches_valid_card_selector_with_context(
502    selector: &CompiledSelector,
503    card: &Card,
504    context: MatchContext<'_>,
505) -> bool {
506    crate::perf::increment(crate::perf::Metric::SelectorMatches, 1);
507    let result = matches_card_selector_ir(&selector.ir, card, context);
508    #[cfg(debug_assertions)]
509    report_selector_drift(
510        "card",
511        result,
512        legacy_matches_valid_card(&selector.as_raw(), card, context),
513        &selector.as_raw(),
514    );
515    result
516}
517
518/// Known pre-existing compiled-vs-legacy divergences surface in normal games
519/// (e.g. `Creature.Artifact`, `Card.IsRemembered+YouOwn`), so the drift guard
520/// reports once per selector instead of panicking; set `FORGE_SELECTOR_ASSERT`
521/// to make it fatal while debugging a specific divergence.
522#[cfg(debug_assertions)]
523fn report_selector_drift(kind: &str, compiled: bool, legacy: bool, raw: &str) {
524    use std::collections::HashSet;
525    use std::sync::{Mutex, OnceLock};
526
527    if compiled == legacy {
528        return;
529    }
530    if std::env::var_os("FORGE_SELECTOR_ASSERT").is_some() {
531        panic!(
532            "compiled {kind} selector diverged from string matcher for {raw:?}: compiled={compiled} legacy={legacy}"
533        );
534    }
535    static REPORTED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
536    let mut reported = REPORTED
537        .get_or_init(|| Mutex::new(HashSet::new()))
538        .lock()
539        .unwrap();
540    if reported.insert(raw.to_string()) {
541        eprintln!("[selector-drift] {kind} selector {raw:?}: compiled={compiled} legacy={legacy}");
542    }
543}
544
545fn matches_card_selector_ir(selector: &Selector, card: &Card, context: MatchContext<'_>) -> bool {
546    match selector.alternatives.as_slice() {
547        [] => true,
548        [alternative] => matches_card_selector_alt(alternative, card, context),
549        alternatives => {
550            for alternative in alternatives {
551                if matches_card_selector_alt(alternative, card, context) {
552                    return true;
553                }
554            }
555            false
556        }
557    }
558}
559
560#[inline]
561fn matches_card_selector_alt(
562    alternative: &crate::parsing::SelectorAlt,
563    card: &Card,
564    context: MatchContext<'_>,
565) -> bool {
566    match alternative.predicates.as_slice() {
567        [] => true,
568        [predicate] => matches_card_predicate(predicate, card, context),
569        [first, second] => {
570            matches_card_predicate(first, card, context)
571                && matches_card_predicate(second, card, context)
572        }
573        predicates => {
574            for predicate in predicates {
575                if !matches_card_predicate(predicate, card, context) {
576                    return false;
577                }
578            }
579            true
580        }
581    }
582}
583
584#[inline(always)]
585fn matches_card_predicate(
586    predicate: &SelectorPredicate,
587    card: &Card,
588    context: MatchContext<'_>,
589) -> bool {
590    match predicate {
591        SelectorPredicate::Any => true,
592        SelectorPredicate::CardType(card_type) => matches_card_type_predicate(card_type, card),
593        SelectorPredicate::CardController(controller) => {
594            matches_card_controller(*controller, card.controller, context.source_controller)
595        }
596        SelectorPredicate::Tapped(tapped) => card.tapped == *tapped,
597        SelectorPredicate::Zone(zone) => card.zone == *zone,
598        SelectorPredicate::Token(token) => card.is_token == *token,
599        SelectorPredicate::Color(color) => matches_card_color(*color, card),
600        SelectorPredicate::Colorless => card.color.is_colorless(),
601        SelectorPredicate::CardOwner(controller) => {
602            matches_card_controller(*controller, card.owner, context.source_controller)
603        }
604        SelectorPredicate::StartedTurnTapped(tapped) => card.started_turn_tapped == *tapped,
605        SelectorPredicate::CameUnderControlSinceLastUpkeep => {
606            card.came_under_control_since_last_upkeep()
607        }
608        SelectorPredicate::Multicolor => card.color.is_multicolor(),
609        SelectorPredicate::Commander => card.is_commander,
610        SelectorPredicate::Legendary => card.type_line.is_legendary(),
611        SelectorPredicate::Kicked => card.kicked,
612        SelectorPredicate::CardSupertype(supertype) => {
613            matches_card_supertype_predicate(*supertype, card)
614        }
615        SelectorPredicate::CardIdentity(identity) => {
616            matches_card_identity(*identity, card, context)
617        }
618        SelectorPredicate::Player | SelectorPredicate::PlayerController(_) => false,
619        SelectorPredicate::RememberedCard => context.remembered_cards.contains(&card.id),
620        SelectorPredicate::TriggerRememberedCard => {
621            context.trigger_remembered_cards.contains(&card.id)
622        }
623        SelectorPredicate::EffectSource => context.source_card.effect_source == Some(card.id),
624        SelectorPredicate::SourceColor(color) => matches_card_color(*color, card),
625        SelectorPredicate::SourceColorless => card.color.is_colorless(),
626        SelectorPredicate::ChosenColorSource => matches_chosen_color_source(card, context),
627        SelectorPredicate::CardState(state) => matches_card_state(*state, card, context),
628        SelectorPredicate::Context(predicate) => {
629            matches_context_predicate(predicate, card, context)
630        }
631        SelectorPredicate::Relation(predicate) => {
632            matches_relation_predicate(predicate, card, context)
633        }
634        SelectorPredicate::DamagedBy => card
635            .damage_sources_this_turn
636            .contains(&context.source_card.id),
637        SelectorPredicate::AttachedBy => context.source_card.attached_to == Some(card.id),
638        SelectorPredicate::WasCast { by_you } => {
639            card.was_cast() && (!by_you || card.controller == context.source_controller)
640        }
641        SelectorPredicate::ChosenType => context
642            .source_card
643            .chosen_type
644            .as_ref()
645            .is_some_and(|ct| card.type_line.has_subtype(ct) || card.has_keyword("Changeling")),
646        SelectorPredicate::Keyword { name, present } => card.has_keyword(name) == *present,
647        SelectorPredicate::NumericComparison {
648            property,
649            operator,
650            value,
651        } => matches_numeric_comparison(*property, *operator, value, card, context),
652        SelectorPredicate::NumericParity { property, even } => {
653            resolve_numeric_property(*property, card, context)
654                .is_some_and(|actual| (actual % 2 == 0) == *even)
655        }
656        SelectorPredicate::CounterComparison {
657            operator,
658            value,
659            counter_type,
660        } => matches_counter_comparison(*operator, value, counter_type, card, context),
661        SelectorPredicate::Not(predicate) => !matches_card_predicate(predicate, card, context),
662        SelectorPredicate::Raw(raw) => matches_raw_card_predicate(raw, card, context),
663    }
664}
665
666#[inline]
667fn matches_chosen_color_source(card: &Card, context: MatchContext<'_>) -> bool {
668    context
669        .source_card
670        .chosen_colors
671        .iter()
672        .filter_map(|color| color_from_name_no_alloc(color))
673        .any(|color| card.color.has_color(color))
674}
675
676#[inline]
677fn color_from_name_no_alloc(value: &str) -> Option<Color> {
678    match value.as_bytes() {
679        [b'W'] | [b'w'] => Some(Color::White),
680        [b'U'] | [b'u'] => Some(Color::Blue),
681        [b'B'] | [b'b'] => Some(Color::Black),
682        [b'R'] | [b'r'] => Some(Color::Red),
683        [b'G'] | [b'g'] => Some(Color::Green),
684        _ if value.eq_ignore_ascii_case("white") => Some(Color::White),
685        _ if value.eq_ignore_ascii_case("blue") => Some(Color::Blue),
686        _ if value.eq_ignore_ascii_case("black") => Some(Color::Black),
687        _ if value.eq_ignore_ascii_case("red") => Some(Color::Red),
688        _ if value.eq_ignore_ascii_case("green") => Some(Color::Green),
689        _ => None,
690    }
691}
692
693#[inline(always)]
694fn matches_card_type_predicate(card_type: &CardSelectorType, card: &Card) -> bool {
695    match card_type {
696        CardSelectorType::Card => true,
697        CardSelectorType::Creature => card.is_creature(),
698        CardSelectorType::Land => card.is_land(),
699        CardSelectorType::Instant => card.type_line.is_instant(),
700        CardSelectorType::Sorcery => card.type_line.is_sorcery(),
701        CardSelectorType::Artifact => card.type_line.is_artifact(),
702        CardSelectorType::Enchantment => card.type_line.is_enchantment(),
703        CardSelectorType::Planeswalker => card.type_line.is_planeswalker(),
704        CardSelectorType::Permanent => card.is_permanent(),
705        CardSelectorType::Spell => true,
706        CardSelectorType::NonLand => !card.is_land(),
707        CardSelectorType::NonCreature => !card.is_creature(),
708        CardSelectorType::Named(name) => card.card_name.eq_ignore_ascii_case(name),
709        CardSelectorType::Subtype(subtype) => card.has_subtype(subtype),
710    }
711}
712
713#[inline(always)]
714fn matches_card_supertype_predicate(supertype: CardSupertypeSelector, card: &Card) -> bool {
715    match supertype {
716        CardSupertypeSelector::Basic => card.type_line.is_basic(),
717        CardSupertypeSelector::Snow => card.type_line.is_snow(),
718    }
719}
720
721#[inline(always)]
722fn matches_card_controller(
723    controller: ControllerSelector,
724    card_controller: PlayerId,
725    source_controller: PlayerId,
726) -> bool {
727    match controller {
728        ControllerSelector::You => card_controller == source_controller,
729        ControllerSelector::Opponent => card_controller != source_controller,
730    }
731}
732
733#[inline(always)]
734fn matches_card_identity(
735    identity: CardIdentitySelector,
736    card: &Card,
737    context: MatchContext<'_>,
738) -> bool {
739    match identity {
740        CardIdentitySelector::Self_ => card.id == context.source_card.id,
741        CardIdentitySelector::Other => card.id != context.source_card.id,
742    }
743}
744
745fn matches_card_state(state: CardStateSelector, card: &Card, context: MatchContext<'_>) -> bool {
746    match state {
747        CardStateSelector::FaceDown => card.face_down,
748        CardStateSelector::Paired => card.paired_with.is_some(),
749        CardStateSelector::PairedWithSource => card.paired_with == Some(context.source_card.id),
750        CardStateSelector::Attached => {
751            card.attached_to.is_some() || card.attached_to_player.is_some()
752        }
753        CardStateSelector::Equipped => card.attached_to.is_some() && card.type_line.is_artifact(),
754        CardStateSelector::Enchanted => {
755            card.attached_to.is_some() && card.type_line.is_enchantment()
756        }
757        CardStateSelector::HasCounters => card.counters.values().any(|count| *count > 0),
758        CardStateSelector::IsImprinted => context.source_card.imprinted_cards.contains(&card.id),
759        CardStateSelector::Chosen => {
760            context.source_card.chosen_cards.contains(&card.id)
761                || context
762                    .source_card
763                    .named_cards
764                    .iter()
765                    .any(|name| card.card_name.eq_ignore_ascii_case(name))
766        }
767        CardStateSelector::ChosenCard => context.source_card.chosen_cards.contains(&card.id),
768        CardStateSelector::NamedCard => context
769            .source_card
770            .named_cards
771            .iter()
772            .any(|name| card.card_name.eq_ignore_ascii_case(name)),
773        CardStateSelector::ChosenColor => context
774            .source_card
775            .chosen_colors
776            .iter()
777            .filter_map(|color| color_from_name_no_alloc(color))
778            .any(|color| card.color.has_color(color)),
779        CardStateSelector::EnteredThisTurn => card.entered_this_turn(),
780        CardStateSelector::WasDealtDamageThisTurn => !card.damage_sources_this_turn.is_empty(),
781        CardStateSelector::Historic => {
782            card.type_line.is_artifact()
783                || card.type_line.is_legendary()
784                || card.has_subtype("Saga")
785        }
786        CardStateSelector::Modified => {
787            card.counters.values().any(|count| *count > 0)
788                || card.attached_to.is_some()
789                || card.power_modifier != 0
790                || card.toughness_modifier != 0
791                || card.static_power_modifier != 0
792                || card.static_toughness_modifier != 0
793        }
794        CardStateSelector::Saddled => card.get_s_var("SaddledBy").is_some(),
795        CardStateSelector::Solved => card.is_solved(),
796        CardStateSelector::FullyUnlocked => card.unlocked_doors.len() == 2,
797        CardStateSelector::MayPlaySource => card.may_play(context.source_controller),
798        CardStateSelector::Suspended => card.is_suspended(),
799        CardStateSelector::SingleTarget => false,
800        CardStateSelector::PromisedGift => card.promised_gift.is_some(),
801        CardStateSelector::RingBearer => context
802            .game
803            .is_some_and(|game| game.player(card.controller).ring_bearer == Some(card.id)),
804    }
805}
806
807fn matches_context_predicate(
808    predicate: &ContextPredicate,
809    card: &Card,
810    context: MatchContext<'_>,
811) -> bool {
812    match predicate {
813        ContextPredicate::Attacking(target) => {
814            matches_attacking_predicate(target.as_ref(), card, context)
815        }
816        ContextPredicate::Blocking(target) => {
817            matches_blocking_predicate(target.as_ref(), card, context)
818        }
819        ContextPredicate::BlockedByValidThisTurn(target) => {
820            matches_blocked_by_valid_this_turn_target(target, card, context)
821        }
822        ContextPredicate::BlockedByValidThisTurnType(card_type) => {
823            matches_blocked_by_valid_this_turn_type(card_type, card, context)
824        }
825        ContextPredicate::BlockedValidThisTurn(card_type)
826        | ContextPredicate::BlockingValid(card_type) => {
827            matches_blocked_valid_this_turn_type(card_type, card, context)
828        }
829        ContextPredicate::Blocked => context.combat.map_or(
830            card.damage_history.creature_got_blocked_this_combat,
831            |combat| combat.was_blocked_this_combat(card.id),
832        ),
833        ContextPredicate::AttackedThisTurn => !card.damage_history.attacked_this_turn.is_empty(),
834        ContextPredicate::BlockingSource => context.combat.is_some_and(|combat| {
835            combat
836                .get_attackers_for(card.id)
837                .contains(&context.source_card.id)
838        }),
839        ContextPredicate::BlockedBySource => context.combat.is_some_and(|combat| {
840            combat
841                .get_blockers_for(card.id)
842                .contains(&context.source_card.id)
843        }),
844        ContextPredicate::WasCastFrom(_) => false,
845        ContextPredicate::EnteredThisTurnFrom(zone) => {
846            matches_entered_this_turn_from(*zone, card, context)
847        }
848        ContextPredicate::EnteredUnder(target) => {
849            card.entered_this_turn()
850                && relation_target_player_any(target, context, |player| card.controller == player)
851        }
852        ContextPredicate::TopLibrary => false,
853        ContextPredicate::ExiledWithSource => {
854            context.source_card.imprinted_cards.contains(&card.id)
855        }
856        ContextPredicate::RememberedPlayerCtrl => {
857            context.remembered_players.contains(&card.controller)
858        }
859        ContextPredicate::TargetedPlayerCtrl => context.targeted_players.contains(&card.controller),
860        ContextPredicate::ControlledBy(reference) => {
861            matches_controlled_by_reference(reference, card, context)
862        }
863        ContextPredicate::ActivePlayerCtrl
864        | ContextPredicate::DefenderCtrl
865        | ContextPredicate::EnchantedController
866        | ContextPredicate::NotDefinedTargeted => false,
867    }
868}
869
870fn matches_controlled_by_reference(
871    reference: &str,
872    card: &Card,
873    context: MatchContext<'_>,
874) -> bool {
875    if reference.eq_ignore_ascii_case("You") || reference.eq_ignore_ascii_case("YouCtrl") {
876        card.controller == context.source_controller
877    } else if reference.eq_ignore_ascii_case("Opponent")
878        || reference.eq_ignore_ascii_case("OppCtrl")
879        || reference.eq_ignore_ascii_case("OpponentCtrl")
880    {
881        card.controller != context.source_controller
882    } else if reference.eq_ignore_ascii_case("Remembered")
883        || reference.eq_ignore_ascii_case("RememberedPlayer")
884        || reference.eq_ignore_ascii_case("RememberedController")
885    {
886        context.remembered_players.contains(&card.controller)
887    } else if reference.eq_ignore_ascii_case("Targeted")
888        || reference.eq_ignore_ascii_case("TargetedPlayer")
889        || reference.eq_ignore_ascii_case("TargetedController")
890    {
891        context.targeted_players.contains(&card.controller)
892    } else if let Some(target) = raw_target_ref(reference) {
893        relation_target_player_any(&target, context, |player| card.controller == player)
894    } else {
895        false
896    }
897}
898
899fn matches_relation_predicate(
900    predicate: &RelationPredicate,
901    card: &Card,
902    context: MatchContext<'_>,
903) -> bool {
904    match predicate {
905        RelationPredicate::SharesNameWith(target) => {
906            relation_target_card_any(target, card, context, |target| {
907                card.card_name.eq_ignore_ascii_case(&target.card_name)
908            })
909        }
910        RelationPredicate::DoesNotShareNameWith(target) => {
911            !relation_target_card_any(target, card, context, |target| {
912                card.card_name.eq_ignore_ascii_case(&target.card_name)
913            })
914        }
915
916        RelationPredicate::SharesCardTypeWith(target) => {
917            relation_target_card_any(target, card, context, |target| {
918                card.shares_card_type_with(target)
919            })
920        }
921        RelationPredicate::SharesCreatureTypeWith(target) => {
922            relation_target_card_any(target, card, context, |target| {
923                shares_creature_type(card, target)
924            })
925        }
926        RelationPredicate::SharesColorWith(target) => {
927            relation_target_card_any(target, card, context, |target| {
928                card.color.shares_color_with(target.color)
929            })
930        }
931        RelationPredicate::SharesManaValueWith(target) => {
932            relation_target_card_any(target, card, context, |target| {
933                card.mana_cost.cmc() == target.mana_cost.cmc()
934            })
935        }
936        RelationPredicate::AttachedTo(target) => {
937            card.attached_to.is_some_and(|attached_to| {
938                relation_target_contains_id(target, attached_to, context)
939            }) || card.attached_to_player.is_some_and(|attached_to| {
940                relation_target_player_any(target, context, |player| player == attached_to)
941            })
942        }
943        RelationPredicate::AttachedToType(card_type) => {
944            let Some(game) = context.game else {
945                return false;
946            };
947            let Some(attached_to) = card.attached_to else {
948                return false;
949            };
950            matches_card_type_predicate(card_type, game.card(attached_to))
951        }
952        RelationPredicate::OwnedBy(target) => {
953            relation_target_player_any(target, context, |player| card.owner == player)
954        }
955        RelationPredicate::OpponentOf(target) => {
956            relation_target_player_any(target, context, |player| card.controller != player)
957        }
958        RelationPredicate::IsTargeting(target) => {
959            relation_target_contains_id(target, card.id, context)
960                || relation_target_player_any(target, context, |player| {
961                    context.targeted_players.contains(&player)
962                })
963        }
964    }
965}
966
967fn relation_target_card_any(
968    target: &TargetRef,
969    subject: &Card,
970    context: MatchContext<'_>,
971    mut predicate: impl FnMut(&Card) -> bool,
972) -> bool {
973    match target {
974        TargetRef::Source => predicate(context.source_card),
975        TargetRef::Remembered | TargetRef::RememberedLki => context.game.is_some_and(|game| {
976            context
977                .remembered_cards
978                .iter()
979                .any(|id| predicate(game.card(*id)))
980        }),
981        TargetRef::Imprinted => context.game.is_some_and(|game| {
982            context
983                .source_card
984                .imprinted_cards
985                .iter()
986                .any(|id| predicate(game.card(*id)))
987        }),
988        TargetRef::ChosenCard => context.game.is_some_and(|game| {
989            context
990                .source_card
991                .chosen_cards
992                .iter()
993                .any(|id| predicate(game.card(*id)))
994        }),
995        TargetRef::Targeted => {
996            let Some(game) = context.game else {
997                return false;
998            };
999            context
1000                .targeted_cards
1001                .iter()
1002                .any(|id| predicate(game.card(*id)))
1003        }
1004        TargetRef::Battlefield => context.game.is_some_and(|game| {
1005            game.cards_in_all_zones(ZoneType::Battlefield)
1006                .any(|id| predicate(game.card(id)))
1007        }),
1008        TargetRef::OtherYourBattlefield => context.game.is_some_and(|game| {
1009            game.cards_in_zone(ZoneType::Battlefield, context.source_controller)
1010                .iter()
1011                .copied()
1012                .filter(|id| *id != subject.id)
1013                .any(|id| predicate(game.card(id)))
1014        }),
1015        TargetRef::YourGraveyard => context.game.is_some_and(|game| {
1016            game.cards_in_zone(ZoneType::Graveyard, context.source_controller)
1017                .iter()
1018                .any(|id| predicate(game.card(*id)))
1019        }),
1020        TargetRef::Player
1021        | TargetRef::Opponent
1022        | TargetRef::ChosenPlayer
1023        | TargetRef::TriggeredPlayer
1024        | TargetRef::TriggeredCardController
1025        | TargetRef::TriggeredDefendingPlayer
1026        | TargetRef::TriggeredAttackedTarget => false,
1027        TargetRef::TriggeredTarget | TargetRef::TriggeredCard => {
1028            let (Some(game), Some(card_id)) = (context.game, context.triggering_card) else {
1029                return false;
1030            };
1031            predicate(game.card(card_id))
1032        }
1033        TargetRef::Commander => context.game.is_some_and(|game| {
1034            game.player_registered_commanders(context.source_controller)
1035                .iter()
1036                .any(|id| predicate(game.card(*id)))
1037        }),
1038    }
1039}
1040
1041fn relation_target_player_any(
1042    target: &TargetRef,
1043    context: MatchContext<'_>,
1044    mut predicate: impl FnMut(PlayerId) -> bool,
1045) -> bool {
1046    match target {
1047        TargetRef::Source => predicate(context.source_controller),
1048        TargetRef::Remembered | TargetRef::RememberedLki => {
1049            context.remembered_players.iter().copied().any(predicate)
1050        }
1051        TargetRef::Imprinted | TargetRef::ChosenCard => false,
1052        TargetRef::ChosenPlayer => context.source_card.chosen_player.is_some_and(predicate),
1053        TargetRef::Targeted => context.targeted_players.iter().copied().any(predicate),
1054        TargetRef::Player => {
1055            context.targeted_players.iter().copied().any(&mut predicate)
1056                || context.remembered_players.iter().copied().any(predicate)
1057        }
1058        TargetRef::Opponent => context
1059            .game
1060            .is_some_and(|game| predicate(game.opponent_of(context.source_controller))),
1061        TargetRef::Battlefield | TargetRef::OtherYourBattlefield | TargetRef::YourGraveyard => {
1062            false
1063        }
1064        TargetRef::TriggeredTarget => {
1065            context.triggering_player.is_some_and(&mut predicate)
1066                || context
1067                    .triggering_card
1068                    .and_then(|card_id| context.game.map(|game| game.card(card_id).controller))
1069                    .is_some_and(predicate)
1070        }
1071        TargetRef::TriggeredCard => context
1072            .triggering_card
1073            .and_then(|card_id| context.game.map(|game| game.card(card_id).controller))
1074            .is_some_and(predicate),
1075        TargetRef::TriggeredPlayer => context.triggering_player.is_some_and(predicate),
1076        TargetRef::TriggeredCardController => context
1077            .triggering_card
1078            .and_then(|card_id| context.game.map(|game| game.card(card_id).controller))
1079            .is_some_and(predicate),
1080        TargetRef::TriggeredDefendingPlayer | TargetRef::TriggeredAttackedTarget => {
1081            triggered_defending_player(context).is_some_and(predicate)
1082        }
1083        TargetRef::Commander => predicate(context.source_controller),
1084    }
1085}
1086
1087fn relation_target_contains_id(
1088    target: &TargetRef,
1089    card_id: CardId,
1090    context: MatchContext<'_>,
1091) -> bool {
1092    match target {
1093        TargetRef::Source => context.source_card.id == card_id,
1094        TargetRef::Remembered | TargetRef::RememberedLki => {
1095            context.remembered_cards.contains(&card_id)
1096        }
1097        TargetRef::Imprinted => context.source_card.imprinted_cards.contains(&card_id),
1098        TargetRef::ChosenCard => context.source_card.chosen_cards.contains(&card_id),
1099        TargetRef::Targeted => context.targeted_cards.contains(&card_id),
1100        TargetRef::OtherYourBattlefield => context.game.is_some_and(|game| {
1101            card_id != context.source_card.id
1102                && game.card(card_id).zone == ZoneType::Battlefield
1103                && game.card(card_id).controller == context.source_controller
1104        }),
1105        TargetRef::Player
1106        | TargetRef::Opponent
1107        | TargetRef::Battlefield
1108        | TargetRef::YourGraveyard
1109        | TargetRef::ChosenPlayer
1110        | TargetRef::TriggeredPlayer
1111        | TargetRef::TriggeredCardController
1112        | TargetRef::TriggeredDefendingPlayer
1113        | TargetRef::TriggeredAttackedTarget => false,
1114        TargetRef::TriggeredTarget | TargetRef::TriggeredCard => {
1115            context.triggering_card == Some(card_id)
1116        }
1117        TargetRef::Commander => context.game.is_some_and(|game| {
1118            game.player_registered_commanders(context.source_controller)
1119                .contains(&card_id)
1120        }),
1121    }
1122}
1123
1124fn matches_attacking_predicate(
1125    target: Option<&TargetRef>,
1126    card: &Card,
1127    context: MatchContext<'_>,
1128) -> bool {
1129    let Some(target) = target else {
1130        return context
1131            .combat
1132            .map_or(card.attacking_player.is_some(), |combat| {
1133                combat.is_attacking(card.id)
1134            });
1135    };
1136    if let Some(combat) = context.combat {
1137        return combat
1138            .attackers
1139            .iter()
1140            .find(|(attacker, _)| *attacker == card.id)
1141            .is_some_and(|(_, defender)| matches_defender_target(*defender, target, context));
1142    }
1143    card.attacking_player
1144        .is_some_and(|player| matches_player_target(player, target, context))
1145}
1146
1147fn matches_blocking_predicate(
1148    target: Option<&TargetRef>,
1149    card: &Card,
1150    context: MatchContext<'_>,
1151) -> bool {
1152    let Some(target) = target else {
1153        return context
1154            .combat
1155            .map_or(card.damage_history.creature_blocked_this_combat, |combat| {
1156                combat.was_blocking(card.id)
1157            });
1158    };
1159    let Some(combat) = context.combat else {
1160        return false;
1161    };
1162    combat
1163        .blockers
1164        .iter()
1165        .filter(|(blocker, _)| *blocker == card.id)
1166        .any(|(_, attacker)| relation_target_contains_id(target, *attacker, context))
1167}
1168
1169fn matches_blocked_by_valid_this_turn_target(
1170    target: &TargetRef,
1171    card: &Card,
1172    context: MatchContext<'_>,
1173) -> bool {
1174    let Some(combat) = context.combat else {
1175        return false;
1176    };
1177    combat
1178        .blockers
1179        .iter()
1180        .filter(|(_, attacker)| *attacker == card.id)
1181        .any(|(blocker, _)| relation_target_contains_id(target, *blocker, context))
1182}
1183
1184fn matches_blocked_by_valid_this_turn_type(
1185    card_type: &CardSelectorType,
1186    card: &Card,
1187    context: MatchContext<'_>,
1188) -> bool {
1189    let (Some(combat), Some(game)) = (context.combat, context.game) else {
1190        return false;
1191    };
1192    combat
1193        .blockers
1194        .iter()
1195        .filter(|(_, attacker)| *attacker == card.id)
1196        .any(|(blocker, _)| matches_card_type_predicate(card_type, game.card(*blocker)))
1197}
1198
1199fn matches_blocked_valid_this_turn_type(
1200    card_type: &CardSelectorType,
1201    card: &Card,
1202    context: MatchContext<'_>,
1203) -> bool {
1204    let (Some(combat), Some(game)) = (context.combat, context.game) else {
1205        return false;
1206    };
1207    combat
1208        .blockers
1209        .iter()
1210        .filter(|(blocker, _)| *blocker == card.id)
1211        .any(|(_, attacker)| matches_card_type_predicate(card_type, game.card(*attacker)))
1212}
1213
1214fn matches_defender_target(
1215    defender: DefenderId,
1216    target: &TargetRef,
1217    context: MatchContext<'_>,
1218) -> bool {
1219    match defender {
1220        DefenderId::Player(player) => matches_player_target(player, target, context),
1221        DefenderId::Permanent(card_id) => relation_target_contains_id(target, card_id, context),
1222    }
1223}
1224
1225fn matches_player_target(player: PlayerId, target: &TargetRef, context: MatchContext<'_>) -> bool {
1226    match target {
1227        TargetRef::Player => true,
1228        TargetRef::Opponent => player != context.source_controller,
1229        _ => relation_target_player_any(target, context, |target_player| player == target_player),
1230    }
1231}
1232
1233fn triggered_defending_player(context: MatchContext<'_>) -> Option<PlayerId> {
1234    context
1235        .triggering_player
1236        .or_else(|| context.combat.and_then(|combat| combat.defending_player))
1237}
1238
1239fn shares_creature_type(card: &Card, target: &Card) -> bool {
1240    card.is_creature()
1241        && target.is_creature()
1242        && card
1243            .type_line
1244            .subtypes
1245            .iter()
1246            .any(|subtype| target.type_line.has_subtype(subtype))
1247}
1248
1249fn matches_entered_this_turn_from(zone: ZoneType, card: &Card, _context: MatchContext<'_>) -> bool {
1250    match zone {
1251        ZoneType::Battlefield => card.entered_this_turn(),
1252        _ => false,
1253    }
1254}
1255
1256fn matches_card_color(color: CardColorSelector, card: &Card) -> bool {
1257    match color {
1258        CardColorSelector::White => card.color.has_white(),
1259        CardColorSelector::Blue => card.color.has_blue(),
1260        CardColorSelector::Black => card.color.has_black(),
1261        CardColorSelector::Red => card.color.has_red(),
1262        CardColorSelector::Green => card.color.has_green(),
1263    }
1264}
1265
1266fn matches_numeric_comparison(
1267    property: NumericSelectorProperty,
1268    operator: SelectorCompareOperator,
1269    threshold: &SelectorNumericOperand,
1270    card: &Card,
1271    context: MatchContext<'_>,
1272) -> bool {
1273    let Some(threshold) = resolve_selector_operand(threshold, context) else {
1274        return true;
1275    };
1276    let Some(value) = resolve_numeric_property(property, card, context) else {
1277        return true;
1278    };
1279    compare_selector_value(value, operator, threshold)
1280}
1281
1282fn resolve_numeric_property(
1283    property: NumericSelectorProperty,
1284    card: &Card,
1285    context: MatchContext<'_>,
1286) -> Option<i32> {
1287    match property {
1288        NumericSelectorProperty::ManaValue => Some(effective_mana_value(card, context)),
1289        NumericSelectorProperty::Power => Some(card.power()),
1290        NumericSelectorProperty::Toughness => Some(card.toughness()),
1291        NumericSelectorProperty::TargetCount => {
1292            Some((context.targeted_cards.len() + context.targeted_players.len()) as i32)
1293        }
1294        NumericSelectorProperty::ManaSpent => {
1295            Some(context.source_card.paying_mana_to_cast.len() as i32)
1296        }
1297    }
1298}
1299
1300fn effective_mana_value(card: &Card, context: MatchContext<'_>) -> i32 {
1301    let mut mana_value = card.mana_cost.cmc();
1302    if let Some(sa) = context.spell_ability {
1303        if sa.source == Some(card.id) {
1304            mana_value += sa.x_mana_cost_paid as i32 * card.mana_cost.count_x() as i32;
1305        }
1306    }
1307    mana_value
1308}
1309
1310fn matches_counter_comparison(
1311    operator: SelectorCompareOperator,
1312    threshold: &SelectorNumericOperand,
1313    counter_type: &str,
1314    card: &Card,
1315    context: MatchContext<'_>,
1316) -> bool {
1317    let Some(threshold) = resolve_selector_operand(threshold, context) else {
1318        return true;
1319    };
1320    use crate::ability::effects::parse_counter_type;
1321    let counter_type = parse_counter_type(counter_type);
1322    let count = card.counter_count(&counter_type);
1323    compare_selector_value(count, operator, threshold)
1324}
1325
1326fn resolve_selector_operand(
1327    operand: &SelectorNumericOperand,
1328    context: MatchContext<'_>,
1329) -> Option<i32> {
1330    match operand {
1331        SelectorNumericOperand::Literal(value) => Some(*value),
1332        SelectorNumericOperand::Symbol(symbol) => {
1333            if symbol.eq_ignore_ascii_case("X") {
1334                if let Some(sa) = context.spell_ability {
1335                    return Some(sa.x_mana_cost_paid as i32);
1336                }
1337            }
1338            let value = context.source_card.get_s_var(symbol)?;
1339            if let Ok(parsed) = value.trim().parse::<i32>() {
1340                return Some(parsed);
1341            }
1342            if value == "TriggeredCard$CardManaCost" {
1343                let game = context.game?;
1344                let card = context.triggering_card?;
1345                return Some(game.card(card).mana_cost.cmc());
1346            }
1347            if value == "TriggeredCard$CardPower" {
1348                let game = context.game?;
1349                let card = context.triggering_card?;
1350                return Some(crate::lki::resolve_lki_power(game, card));
1351            }
1352            if value == "TriggeredCard$CardToughness" {
1353                let game = context.game?;
1354                let card = context.triggering_card?;
1355                return Some(crate::lki::resolve_lki_toughness(game, card));
1356            }
1357            if value.starts_with("Count$") || value.starts_with("PlayerCount") {
1358                let game = context.game?;
1359                let sa = crate::spellability::SpellAbility::new_empty(
1360                    Some(context.source_card.id),
1361                    context.source_controller,
1362                );
1363                return Some(crate::svar::resolve_svar_expression(
1364                    value,
1365                    game,
1366                    context.source_card.id,
1367                    context.source_controller,
1368                    &sa,
1369                ));
1370            }
1371            None
1372        }
1373    }
1374}
1375
1376fn compare_selector_value(actual: i32, operator: SelectorCompareOperator, expected: i32) -> bool {
1377    match operator {
1378        SelectorCompareOperator::Eq => actual == expected,
1379        SelectorCompareOperator::Ne => actual != expected,
1380        SelectorCompareOperator::Lt => actual < expected,
1381        SelectorCompareOperator::Le => actual <= expected,
1382        SelectorCompareOperator::Gt => actual > expected,
1383        SelectorCompareOperator::Ge => actual >= expected,
1384    }
1385}
1386
1387fn matches_raw_card_predicate(raw: &str, card: &Card, context: MatchContext<'_>) -> bool {
1388    crate::perf::increment(crate::perf::Metric::SelectorRawPredicates, 1);
1389    if let Some(result) = matches_domain_predicate(raw, card, context) {
1390        return result;
1391    }
1392    legacy_matches_card_atom(raw, card, context)
1393}
1394
1395fn legacy_matches_card_atom(raw: &str, card: &Card, context: MatchContext<'_>) -> bool {
1396    let source = context.source_card;
1397    let raw = raw.trim();
1398    if raw.is_empty() {
1399        return true;
1400    }
1401    if let Some(result) = matches_domain_predicate(raw, card, context) {
1402        return result;
1403    }
1404    let (negated, value) = if let Some(stripped) = raw.strip_prefix('!') {
1405        (true, stripped)
1406    } else {
1407        (false, raw)
1408    };
1409    let value_lower = value.to_ascii_lowercase();
1410    if negated {
1411        let positive_match = match value_lower.as_str() {
1412            "token" => card.is_token,
1413            "creature" => card.is_creature(),
1414            "land" => card.is_land(),
1415            "artifact" => card.type_line.is_artifact(),
1416            "enchantment" => card.type_line.is_enchantment(),
1417            "legendary" => card.type_line.is_legendary(),
1418            "basic" => card.type_line.is_basic(),
1419            "snow" => card.type_line.is_snow(),
1420            "issolved" => card.is_solved(),
1421            "suspended" => card.is_suspended(),
1422            "fullyunlocked" => card.unlocked_doors.len() == 2,
1423            _ => card.has_subtype(value),
1424        };
1425        return !positive_match;
1426    }
1427
1428    match value_lower.as_str() {
1429        "self" | "strictlyself" | "card.self" => card.id == source.id,
1430        "other" | "strictlyother" => card.id != source.id,
1431        "youctrl" | "youcontrol" | "you" => card.controller == source.controller,
1432        "youown" => card.owner == source.controller,
1433        "youdontctrl" => card.controller != source.controller,
1434        "youdontown" => card.owner != source.controller,
1435        "isremembered" | "card.isremembered" => source.remembered_cards.contains(&card.id),
1436        "istriggerremembered" | "card.istriggerremembered" => {
1437            context.trigger_remembered_cards.contains(&card.id)
1438        }
1439        "effectsource" | "card.effectsource" => source.effect_source == Some(card.id),
1440        "oppctrl" | "opponentctrl" | "opponent" => card.controller != source.controller,
1441        "chosenctrl" => Some(card.controller) == source.chosen_player,
1442        "oppown" | "opponentown" => card.owner != source.controller,
1443        "targetedplayerown" | "targetedown" | "targetedowner" => {
1444            context.targeted_players.contains(&card.owner)
1445        }
1446        "iscommander" => card.is_commander,
1447        "legendary" => card.type_line.is_legendary(),
1448        "basic" => card.type_line.is_basic(),
1449        "snow" => card.type_line.is_snow(),
1450        "kicked" => card.kicked,
1451        "cameundercontrolsincelastupkeep" => card.came_under_control_since_last_upkeep(),
1452        "noncreature" => !card.is_creature(),
1453        "nonland" => !card.is_land(),
1454        "nonlegendary" => !card.type_line.is_legendary(),
1455        "nonbasic" => !card.type_line.is_basic(),
1456        "nonsnow" => !card.type_line.is_snow(),
1457        "token" => card.is_token,
1458        "nontoken" => !card.is_token,
1459        "tapped" => card.tapped,
1460        "untapped" => !card.tapped,
1461        "startedtheturnuntapped" => !card.started_turn_tapped,
1462        "startedtheturntapped" => card.started_turn_tapped,
1463        "multicolor" => card.color.is_multicolor(),
1464        "colorless" => card.color.is_colorless(),
1465        "whitesource" => matches_card_color(CardColorSelector::White, card),
1466        "bluesource" => matches_card_color(CardColorSelector::Blue, card),
1467        "blacksource" => matches_card_color(CardColorSelector::Black, card),
1468        "redsource" => matches_card_color(CardColorSelector::Red, card),
1469        "greensource" => matches_card_color(CardColorSelector::Green, card),
1470        "colorlesssource" => card.color.is_colorless(),
1471        "chosencolorsource" => matches_chosen_color_source(card, context),
1472        "attacking" => matches_context_predicate(&ContextPredicate::Attacking(None), card, context),
1473        "attackingyou" => matches_context_predicate(
1474            &ContextPredicate::Attacking(Some(TargetRef::Source)),
1475            card,
1476            context,
1477        ),
1478        "blocking" => matches_context_predicate(&ContextPredicate::Blocking(None), card, context),
1479        "blocked" => matches_context_predicate(&ContextPredicate::Blocked, card, context),
1480        "attackedthisturn" => {
1481            matches_context_predicate(&ContextPredicate::AttackedThisTurn, card, context)
1482        }
1483        "blockingsource" => {
1484            matches_context_predicate(&ContextPredicate::BlockingSource, card, context)
1485        }
1486        "blockedbysource" => {
1487            matches_context_predicate(&ContextPredicate::BlockedBySource, card, context)
1488        }
1489        "samename" => matches_relation_predicate(
1490            &RelationPredicate::SharesNameWith(TargetRef::Source),
1491            card,
1492            context,
1493        ),
1494        shares if shares.starts_with("sharesnamewith") => {
1495            raw_target_ref(&value["sharesNameWith".len()..]).is_some_and(|target| {
1496                matches_relation_predicate(
1497                    &RelationPredicate::SharesNameWith(target),
1498                    card,
1499                    context,
1500                )
1501            })
1502        }
1503        shares if shares.starts_with("doesnotsharenamewith") => {
1504            raw_target_ref(&value["doesNotShareNameWith".len()..]).is_some_and(|target| {
1505                matches_relation_predicate(
1506                    &RelationPredicate::DoesNotShareNameWith(target),
1507                    card,
1508                    context,
1509                )
1510            })
1511        }
1512        shares if shares.starts_with("sharescardtypewith") => {
1513            raw_target_ref(&value["sharesCardTypeWith".len()..]).is_some_and(|target| {
1514                matches_relation_predicate(
1515                    &RelationPredicate::SharesCardTypeWith(target),
1516                    card,
1517                    context,
1518                )
1519            })
1520        }
1521        shares if shares.starts_with("sharescolorwith") => {
1522            raw_target_ref(&value["SharesColorWith".len()..]).is_some_and(|target| {
1523                matches_relation_predicate(
1524                    &RelationPredicate::SharesColorWith(target),
1525                    card,
1526                    context,
1527                )
1528            })
1529        }
1530        shares if shares.starts_with("sharescmcwith") => {
1531            raw_target_ref(&value["SharesCMCWith".len()..]).is_some_and(|target| {
1532                matches_relation_predicate(
1533                    &RelationPredicate::SharesManaValueWith(target),
1534                    card,
1535                    context,
1536                )
1537            })
1538        }
1539        shares if shares.starts_with("sharescreaturetypewith") => {
1540            raw_target_ref(&value["sharesCreatureTypeWith".len()..]).is_some_and(|target| {
1541                matches_relation_predicate(
1542                    &RelationPredicate::SharesCreatureTypeWith(target),
1543                    card,
1544                    context,
1545                )
1546            })
1547        }
1548        attacking if attacking.starts_with("attacking ") => {
1549            raw_target_ref(&value["attacking ".len()..]).is_some_and(|target| {
1550                matches_context_predicate(&ContextPredicate::Attacking(Some(target)), card, context)
1551            })
1552        }
1553        blocked_by if blocked_by.starts_with("blockedbyvalidthisturn ") => {
1554            raw_blocked_by_valid_this_turn(&value["blockedByValidThisTurn ".len()..])
1555                .is_some_and(|predicate| matches_context_predicate(&predicate, card, context))
1556        }
1557        blocked if blocked.starts_with("blockedvalidthisturn ") => raw_card_selector_type(
1558            &value["blockedValidThisTurn ".len()..],
1559        )
1560        .is_some_and(|card_type| {
1561            matches_context_predicate(
1562                &ContextPredicate::BlockedValidThisTurn(card_type),
1563                card,
1564                context,
1565            )
1566        }),
1567        blocking_valid if blocking_valid.starts_with("blockingvalid ") => {
1568            raw_card_selector_type(&value["blockingValid ".len()..]).is_some_and(|card_type| {
1569                matches_context_predicate(
1570                    &ContextPredicate::BlockingValid(card_type),
1571                    card,
1572                    context,
1573                )
1574            })
1575        }
1576        blocking if blocking.starts_with("blocking ") => {
1577            raw_target_ref(&value["blocking ".len()..]).is_some_and(|target| {
1578                matches_context_predicate(&ContextPredicate::Blocking(Some(target)), card, context)
1579            })
1580        }
1581        controlled if controlled.starts_with("controlledby ") => {
1582            matches_controlled_by_reference(value["ControlledBy ".len()..].trim(), card, context)
1583        }
1584        attached if attached.starts_with("attachedto ") => {
1585            let relation = raw_attached_to_relation(value["AttachedTo ".len()..].trim());
1586            relation.is_some_and(|relation| matches_relation_predicate(&relation, card, context))
1587        }
1588        owned if owned.starts_with("ownedby ") => raw_target_ref(&value["OwnedBy ".len()..])
1589            .is_some_and(|target| {
1590                matches_relation_predicate(&RelationPredicate::OwnedBy(target), card, context)
1591            }),
1592        opponent if opponent.starts_with("opponentof ") => {
1593            raw_target_ref(&value["OpponentOf ".len()..]).is_some_and(|target| {
1594                matches_relation_predicate(&RelationPredicate::OpponentOf(target), card, context)
1595            })
1596        }
1597        targeting if targeting.starts_with("istargeting ") => {
1598            raw_target_ref(&value["IsTargeting ".len()..]).is_some_and(|target| {
1599                matches_relation_predicate(&RelationPredicate::IsTargeting(target), card, context)
1600            })
1601        }
1602        "inzonebattlefield" => card.zone == forge_foundation::ZoneType::Battlefield,
1603        "inzonegraveyard" => card.zone == forge_foundation::ZoneType::Graveyard,
1604        "inzonehand" => card.zone == forge_foundation::ZoneType::Hand,
1605        "inzoneexile" => card.zone == forge_foundation::ZoneType::Exile,
1606        "inzonestack" => card.zone == forge_foundation::ZoneType::Stack,
1607        "damagedby" => card
1608            .damage_sources_this_turn
1609            .contains(&context.source_card.id),
1610        "equippedby" | "enchantedby" | "attachedby" => {
1611            context.source_card.attached_to == Some(card.id)
1612        }
1613        "facedown" => matches_card_state(CardStateSelector::FaceDown, card, context),
1614        "paired" => matches_card_state(CardStateSelector::Paired, card, context),
1615        "pairedwith" => matches_card_state(CardStateSelector::PairedWithSource, card, context),
1616        "attached" => matches_card_state(CardStateSelector::Attached, card, context),
1617        "equipped" => matches_card_state(CardStateSelector::Equipped, card, context),
1618        "enchanted" => matches_card_state(CardStateSelector::Enchanted, card, context),
1619        "hascounters" => matches_card_state(CardStateSelector::HasCounters, card, context),
1620        "isimprinted" => matches_card_state(CardStateSelector::IsImprinted, card, context),
1621        "chosen" => matches_card_state(CardStateSelector::Chosen, card, context),
1622        "chosencard" | "chosencardstrict" => {
1623            matches_card_state(CardStateSelector::ChosenCard, card, context)
1624        }
1625        "namedcard" => matches_card_state(CardStateSelector::NamedCard, card, context),
1626        "chosencolor" => matches_card_state(CardStateSelector::ChosenColor, card, context),
1627        "thisturnentered" | "thisturnenteredfrom_battlefield" => {
1628            matches_card_state(CardStateSelector::EnteredThisTurn, card, context)
1629        }
1630        entered if entered.starts_with("enteredunder ") => {
1631            raw_target_ref(&value["EnteredUnder ".len()..]).is_some_and(|target| {
1632                matches_context_predicate(&ContextPredicate::EnteredUnder(target), card, context)
1633            })
1634        }
1635        "wasdealtdamagethisturn" => {
1636            matches_card_state(CardStateSelector::WasDealtDamageThisTurn, card, context)
1637        }
1638        dealt if dealt.starts_with("dealtcombatdamagethisturn") => {
1639            let Some(target_text) = value.split_once(' ').map(|(_, target)| target.trim()) else {
1640                return card
1641                    .damage_history
1642                    .damage_done_this_turn
1643                    .iter()
1644                    .any(|damage| damage.is_combat && damage.amount > 0);
1645            };
1646            let Some(target) = raw_target_ref(target_text) else {
1647                return false;
1648            };
1649            card.damage_history.damage_done_this_turn.iter().any(|damage| {
1650                damage.is_combat
1651                    && damage.amount > 0
1652                    && matches!(
1653                        damage.target,
1654                        Some(crate::card::card_damage_history::TrackedEntity::Player(player))
1655                            if relation_target_player_any(&target, context, |target_player| target_player == player)
1656                    )
1657            })
1658        }
1659        "historic" => matches_card_state(CardStateSelector::Historic, card, context),
1660        "modified" => matches_card_state(CardStateSelector::Modified, card, context),
1661        "issaddled" => matches_card_state(CardStateSelector::Saddled, card, context),
1662        "issolved" => matches_card_state(CardStateSelector::Solved, card, context),
1663        "fullyunlocked" => matches_card_state(CardStateSelector::FullyUnlocked, card, context),
1664        "mayplaysource" => matches_card_state(CardStateSelector::MayPlaySource, card, context),
1665        "exiledwithsource" => {
1666            matches_context_predicate(&ContextPredicate::ExiledWithSource, card, context)
1667        }
1668        "toplibrary" => matches_context_predicate(&ContextPredicate::TopLibrary, card, context),
1669        "suspended" => matches_card_state(CardStateSelector::Suspended, card, context),
1670        "singletarget" => matches_card_state(CardStateSelector::SingleTarget, card, context),
1671        "promisedgift" => matches_card_state(CardStateSelector::PromisedGift, card, context),
1672        "isringbearer" => matches_card_state(CardStateSelector::RingBearer, card, context),
1673        "rememberedplayerctrl" => {
1674            matches_context_predicate(&ContextPredicate::RememberedPlayerCtrl, card, context)
1675        }
1676        "wascast" => card.was_cast(),
1677        "wascastbyyou" => card.was_cast() && card.controller == context.source_controller,
1678        was_cast_from if was_cast_from.starts_with("wascastfrom") => {
1679            matches_was_cast_from(&value[11..], card, context)
1680        }
1681        named if named.starts_with("named") => {
1682            card.card_name.eq_ignore_ascii_case(value[5..].trim())
1683        }
1684        _ if value.starts_with("counters_") => check_counter_condition(value, card),
1685        _ => {
1686            if value_lower.starts_with("cmc") {
1687                let original_rest = &value[3..];
1688                check_cmc_condition_with_context(original_rest, card, Some(context))
1689            } else if let Some(rest) = value_lower.strip_prefix("power") {
1690                check_power_condition(rest, card)
1691            } else if let Some(rest) = value_lower.strip_prefix("toughness") {
1692                check_toughness_condition(rest, card)
1693            } else if let Some(color) = Color::from_name(&value_lower) {
1694                card.color.has_color(color)
1695            } else if let Some(keyword_suffix) = value_lower.strip_prefix("with") {
1696                if keyword_suffix.strip_prefix("out").is_some() {
1697                    !card.has_keyword(&value[7..])
1698                } else if !keyword_suffix.is_empty() {
1699                    card.has_keyword(&value[4..])
1700                } else {
1701                    true
1702                }
1703            } else if let Some(negated_value) = value_lower.strip_prefix("non") {
1704                let positive_match = match negated_value {
1705                    "creature" => card.is_creature(),
1706                    "land" => card.is_land(),
1707                    "artifact" => card.type_line.is_artifact(),
1708                    "enchantment" => card.type_line.is_enchantment(),
1709                    "token" => card.is_token,
1710                    "colorless" => card.color.is_colorless(),
1711                    _ => {
1712                        if let Some(color) = Color::from_name(negated_value) {
1713                            card.color.has_color(color)
1714                        } else {
1715                            card.has_subtype(&value[3..])
1716                        }
1717                    }
1718                };
1719                !positive_match
1720            } else if value_lower == "chosentype" {
1721                source.chosen_type.as_ref().is_some_and(|ct| {
1722                    card.type_line.has_subtype(ct) || card.has_keyword("Changeling")
1723                })
1724            } else {
1725                let color_name = value.strip_suffix("Source").unwrap_or(value);
1726                if let Some(color) = Color::from_name(&color_name.to_lowercase()) {
1727                    card.color.has_color(color)
1728                } else if color_name.eq_ignore_ascii_case("Colorless") {
1729                    card.color.is_colorless()
1730                } else {
1731                    card.has_subtype(value)
1732                }
1733            }
1734        }
1735    }
1736}
1737
1738fn matches_domain_predicate(raw: &str, card: &Card, context: MatchContext<'_>) -> Option<bool> {
1739    crate::ability::selector_domain::matches_selector_domain_predicate(raw, card, context)
1740        .or_else(|| {
1741            crate::cost::selector_domain::matches_selector_domain_predicate(raw, card, context)
1742        })
1743        .or_else(|| {
1744            crate::trigger::selector_domain::matches_selector_domain_predicate(raw, card, context)
1745        })
1746        .or_else(|| {
1747            crate::combat::selector_domain::matches_selector_domain_predicate(raw, card, context)
1748        })
1749}
1750
1751fn raw_target_ref(value: &str) -> Option<TargetRef> {
1752    let value = value.trim();
1753    if value.is_empty()
1754        || value.eq_ignore_ascii_case("Self")
1755        || value.eq_ignore_ascii_case("Source")
1756        || value.eq_ignore_ascii_case("You")
1757        || value.eq_ignore_ascii_case("YouCtrl")
1758    {
1759        Some(TargetRef::Source)
1760    } else if value.eq_ignore_ascii_case("Remembered") {
1761        Some(TargetRef::Remembered)
1762    } else if value.eq_ignore_ascii_case("RememberedLKI") {
1763        Some(TargetRef::RememberedLki)
1764    } else if value.eq_ignore_ascii_case("Imprinted") {
1765        Some(TargetRef::Imprinted)
1766    } else if value.eq_ignore_ascii_case("ChosenCard") {
1767        Some(TargetRef::ChosenCard)
1768    } else if value.eq_ignore_ascii_case("ChosenPlayer") {
1769        Some(TargetRef::ChosenPlayer)
1770    } else if value.eq_ignore_ascii_case("Targeted") {
1771        Some(TargetRef::Targeted)
1772    } else if value.eq_ignore_ascii_case("TargetedPlayer")
1773        || value.eq_ignore_ascii_case("TargetedController")
1774    {
1775        Some(TargetRef::Targeted)
1776    } else if value.eq_ignore_ascii_case("Player") {
1777        Some(TargetRef::Player)
1778    } else if value.eq_ignore_ascii_case("Opponent") {
1779        Some(TargetRef::Opponent)
1780    } else if value.eq_ignore_ascii_case("Battlefield") {
1781        Some(TargetRef::Battlefield)
1782    } else if value.eq_ignore_ascii_case("OtherYourBattlefield") {
1783        Some(TargetRef::OtherYourBattlefield)
1784    } else if value.eq_ignore_ascii_case("YourGraveyard") {
1785        Some(TargetRef::YourGraveyard)
1786    } else if value.eq_ignore_ascii_case("TriggeredTarget") {
1787        Some(TargetRef::TriggeredTarget)
1788    } else if value.eq_ignore_ascii_case("TriggeredPlayer") {
1789        Some(TargetRef::TriggeredPlayer)
1790    } else if value.eq_ignore_ascii_case("TriggeredCard") {
1791        Some(TargetRef::TriggeredCard)
1792    } else if value.eq_ignore_ascii_case("TriggeredCardController") {
1793        Some(TargetRef::TriggeredCardController)
1794    } else if value.eq_ignore_ascii_case("TriggeredDefendingPlayer") {
1795        Some(TargetRef::TriggeredDefendingPlayer)
1796    } else if value.eq_ignore_ascii_case("TriggeredAttackedTarget") {
1797        Some(TargetRef::TriggeredAttackedTarget)
1798    } else if value.eq_ignore_ascii_case("Commander") {
1799        Some(TargetRef::Commander)
1800    } else {
1801        None
1802    }
1803}
1804
1805fn raw_blocked_by_valid_this_turn(value: &str) -> Option<ContextPredicate> {
1806    if let Some(target) = raw_target_ref(value) {
1807        return Some(ContextPredicate::BlockedByValidThisTurn(target));
1808    }
1809    raw_card_selector_type(value).map(ContextPredicate::BlockedByValidThisTurnType)
1810}
1811
1812fn raw_card_selector_type(value: &str) -> Option<CardSelectorType> {
1813    let value = value.trim();
1814    match value.to_ascii_lowercase().as_str() {
1815        "card" => Some(CardSelectorType::Card),
1816        "creature" => Some(CardSelectorType::Creature),
1817        "land" => Some(CardSelectorType::Land),
1818        "artifact" => Some(CardSelectorType::Artifact),
1819        "enchantment" => Some(CardSelectorType::Enchantment),
1820        "planeswalker" => Some(CardSelectorType::Planeswalker),
1821        "permanent" => Some(CardSelectorType::Permanent),
1822        "nonland" => Some(CardSelectorType::NonLand),
1823        "noncreature" => Some(CardSelectorType::NonCreature),
1824        _ if value
1825            .chars()
1826            .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '\'') =>
1827        {
1828            Some(CardSelectorType::Subtype(value.to_string()))
1829        }
1830        _ => None,
1831    }
1832}
1833
1834/// Mirrors Java `CardProperty`'s `wasCastFrom` branch. Java reads the owner off
1835/// `Card.castFrom` (a `Zone`); Rust stores only the zone type, so `Your`/`Their`
1836/// resolve the origin zone's owner as the card's owner.
1837fn matches_was_cast_from(suffix: &str, card: &Card, context: MatchContext<'_>) -> bool {
1838    let Some(cast_from) = card.cast_from else {
1839        return false;
1840    };
1841    let (zone_owner, rest) = if let Some(rest) = suffix.strip_prefix("Your") {
1842        (Some(context.source_controller), rest)
1843    } else if let Some(rest) = suffix.strip_prefix("Their") {
1844        (Some(card.controller), rest)
1845    } else {
1846        (None, suffix)
1847    };
1848    let (by_you, zone_name) = match rest.strip_suffix("ByYou") {
1849        Some(zone_name) => (true, zone_name),
1850        None => (false, rest),
1851    };
1852    if zone_owner.is_some_and(|owner| owner != card.owner) {
1853        return false;
1854    }
1855    if by_you && card.controller != context.source_controller {
1856        return false;
1857    }
1858    ZoneType::from_str_compat(zone_name) == Some(cast_from)
1859}
1860
1861fn raw_attached_to_relation(value: &str) -> Option<RelationPredicate> {
1862    if let Some(target) = raw_target_ref(value) {
1863        return Some(RelationPredicate::AttachedTo(target));
1864    }
1865    let card_type = match value.to_ascii_lowercase().as_str() {
1866        "card" => CardSelectorType::Card,
1867        "creature" => CardSelectorType::Creature,
1868        "land" => CardSelectorType::Land,
1869        "artifact" => CardSelectorType::Artifact,
1870        "enchantment" => CardSelectorType::Enchantment,
1871        "permanent" => CardSelectorType::Permanent,
1872        _ => return None,
1873    };
1874    Some(RelationPredicate::AttachedToType(card_type))
1875}
1876
1877/// Convenience wrapper: None means "no filter" -> always matches.
1878pub fn matches_valid_card_selector_opt(
1879    selector: Option<&CompiledSelector>,
1880    card: &Card,
1881    source: &Card,
1882) -> bool {
1883    match selector {
1884        None => true,
1885        Some(selector) => matches_valid_card_selector(selector, card, source),
1886    }
1887}
1888
1889pub fn matches_valid_card_selector_opt_with_context(
1890    selector: Option<&CompiledSelector>,
1891    card: &Card,
1892    context: MatchContext<'_>,
1893) -> bool {
1894    match selector {
1895        None => true,
1896        Some(selector) => matches_valid_card_selector_with_context(selector, card, context),
1897    }
1898}
1899
1900pub fn matches_valid_card_selector_opt_in_game(
1901    selector: Option<&CompiledSelector>,
1902    card: &Card,
1903    source: &Card,
1904    game: &GameState,
1905) -> bool {
1906    matches_valid_card_selector_opt_with_context(
1907        selector,
1908        card,
1909        MatchContext::from_source(source).with_game(game),
1910    )
1911}
1912
1913#[cfg(debug_assertions)]
1914fn matches_single_valid_card(filter: &str, card: &Card, context: MatchContext<'_>) -> bool {
1915    // Handle comma-separated types with qualifiers (e.g. "Creature.YouCtrl,Artifact.YouCtrl")
1916    if filter.contains(',') {
1917        return filter
1918            .split(',')
1919            .any(|alt| matches_type_and_qualifiers(alt.trim(), card, context));
1920    }
1921
1922    matches_type_and_qualifiers(filter, card, context)
1923}
1924
1925#[cfg(debug_assertions)]
1926fn matches_type_and_qualifiers(filter: &str, card: &Card, context: MatchContext<'_>) -> bool {
1927    // Split on dots for compound filters (e.g. "Creature.Other", "Card.Self")
1928    let parts: Vec<&str> = filter.split('.').collect();
1929    if parts.is_empty() {
1930        return true;
1931    }
1932
1933    let type_part = parts[0];
1934    let qualifiers = &parts[1..];
1935
1936    matches_type_and_qualifier_parts(type_part, qualifiers, card, context)
1937}
1938
1939#[cfg(debug_assertions)]
1940fn matches_type_and_qualifier_parts(
1941    type_part: &str,
1942    qualifiers: &[&str],
1943    card: &Card,
1944    context: MatchContext<'_>,
1945) -> bool {
1946    let source = context.source_card;
1947    // Check the type portion
1948    let type_matches = match type_part {
1949        "Card" | "Any" => true, // matches any card
1950        "Creature" => card.is_creature(),
1951        "Land" => card.is_land(),
1952        "Instant" => card.type_line.is_instant(),
1953        "Sorcery" => card.type_line.is_sorcery(),
1954        "Artifact" => card.type_line.is_artifact(),
1955        "Enchantment" => card.type_line.is_enchantment(),
1956        "Planeswalker" => card.type_line.is_planeswalker(),
1957        "nonland" | "nonLand" | "NonLand" => !card.is_land(),
1958        "noncreature" | "nonCreature" | "NonCreature" => !card.is_creature(),
1959        "Permanent" => card.is_permanent(),
1960        "Spell" => true, // used in some contexts
1961        named if named.to_ascii_lowercase().starts_with("named") => {
1962            card.card_name.eq_ignore_ascii_case(named[5..].trim())
1963        }
1964        // Player-type filters: players are not cards, so never match.
1965        "Player" | "You" | "Opponent" | "Each" | "ActivePlayer" | "NonActivePlayer" => false,
1966        _ => {
1967            // Try comma-separated types within the type portion (e.g. "Instant,Sorcery")
1968            if type_part.contains(',') {
1969                type_part.split(',').any(|t| match t.trim() {
1970                    "Creature" => card.is_creature(),
1971                    "Land" => card.is_land(),
1972                    "Instant" => card.type_line.is_instant(),
1973                    "Sorcery" => card.type_line.is_sorcery(),
1974                    "Artifact" => card.type_line.is_artifact(),
1975                    "Enchantment" => card.type_line.is_enchantment(),
1976                    "Planeswalker" => card.type_line.is_planeswalker(),
1977                    "Card" => true,
1978                    _ => false,
1979                })
1980            } else {
1981                // Try matching as subtype (e.g. "Zombie", "Wall", "Dragon").
1982                // This must be changeling-aware for creature types, matching
1983                // Java's CardType.hasStringType()/hasCreatureType() path.
1984                card.has_subtype(type_part)
1985            }
1986        }
1987    };
1988
1989    if !type_matches {
1990        return false;
1991    }
1992
1993    // Check qualifiers — handle compound "+" syntax (e.g. "Self+kicked", "YouCtrl+nonBlack")
1994    for &qualifier in qualifiers {
1995        // Split compound qualifiers on '+' (e.g. "Self+kicked" → ["Self", "kicked"])
1996        let sub_parts: Vec<&str> = qualifier.split('+').collect();
1997        for sub in &sub_parts {
1998            // Handle "!" prefix as negation (e.g. "!token" → "nontoken")
1999            let (negated, raw) = if let Some(stripped) = sub.strip_prefix('!') {
2000                (true, stripped)
2001            } else {
2002                (false, *sub)
2003            };
2004            let sub_lower = raw.to_ascii_lowercase();
2005            // If negated, invert the boolean result of the positive match.
2006            // "!token" is equivalent to "nontoken", "!Creature" to "nonCreature", etc.
2007            if negated {
2008                let positive_match = match sub_lower.as_str() {
2009                    "token" => card.is_token,
2010                    "creature" => card.is_creature(),
2011                    "land" => card.is_land(),
2012                    "artifact" => card.type_line.is_artifact(),
2013                    "enchantment" => card.type_line.is_enchantment(),
2014                    "legendary" => card.type_line.is_legendary(),
2015                    "basic" => card.type_line.is_basic(),
2016                    "snow" => card.type_line.is_snow(),
2017                    "fullyunlocked" => card.unlocked_doors.len() == 2,
2018                    _ => {
2019                        // Try subtype match
2020                        card.has_subtype(raw)
2021                    }
2022                };
2023                if positive_match {
2024                    return false;
2025                }
2026                continue;
2027            }
2028            match sub_lower.as_str() {
2029                "self" => {
2030                    if card.id != source.id {
2031                        return false;
2032                    }
2033                }
2034                "strictlyself" => {
2035                    if card.id != source.id {
2036                        return false;
2037                    }
2038                }
2039                "other" | "strictlyother" => {
2040                    if card.id == source.id {
2041                        return false;
2042                    }
2043                }
2044                "youctrl" | "youcontrol" | "you" => {
2045                    if card.controller != source.controller {
2046                        return false;
2047                    }
2048                }
2049                "youdontctrl" => {
2050                    if card.controller == source.controller {
2051                        return false;
2052                    }
2053                }
2054                "youown" => {
2055                    if card.owner != source.controller {
2056                        return false;
2057                    }
2058                }
2059                "youdontown" => {
2060                    if card.owner == source.controller {
2061                        return false;
2062                    }
2063                }
2064                "isremembered" => {
2065                    if !source.remembered_cards.contains(&card.id) {
2066                        return false;
2067                    }
2068                }
2069                "istriggerremembered" => {
2070                    if !context.trigger_remembered_cards.contains(&card.id) {
2071                        return false;
2072                    }
2073                }
2074                "effectsource" => {
2075                    if source.effect_source != Some(card.id) {
2076                        return false;
2077                    }
2078                }
2079                "oppctrl" | "opponentctrl" | "opponent" => {
2080                    if card.controller == source.controller {
2081                        return false;
2082                    }
2083                }
2084                "chosenctrl" => {
2085                    if Some(card.controller) != source.chosen_player {
2086                        return false;
2087                    }
2088                }
2089                "oppown" | "opponentown" => {
2090                    if card.owner == source.controller {
2091                        return false;
2092                    }
2093                }
2094                "iscommander" => {
2095                    if !card.is_commander {
2096                        return false;
2097                    }
2098                }
2099                "isringbearer" => {
2100                    if !context.game.is_some_and(|game| {
2101                        game.player(card.controller).ring_bearer == Some(card.id)
2102                    }) {
2103                        return false;
2104                    }
2105                }
2106                "legendary" => {
2107                    if !card.type_line.is_legendary() {
2108                        return false;
2109                    }
2110                }
2111                "basic" => {
2112                    if !card.type_line.is_basic() {
2113                        return false;
2114                    }
2115                }
2116                "snow" => {
2117                    if !card.type_line.is_snow() {
2118                        return false;
2119                    }
2120                }
2121                "kicked" => {
2122                    if !card.kicked {
2123                        return false;
2124                    }
2125                }
2126                "fullyunlocked" => {
2127                    if card.unlocked_doors.len() < 2 {
2128                        return false;
2129                    }
2130                }
2131                "cameundercontrolsincelastupkeep" => {
2132                    if !card.came_under_control_since_last_upkeep() {
2133                        return false;
2134                    }
2135                }
2136                "noncreature" => {
2137                    if card.is_creature() {
2138                        return false;
2139                    }
2140                }
2141                "nonland" => {
2142                    if card.is_land() {
2143                        return false;
2144                    }
2145                }
2146                "token" => {
2147                    if !card.is_token {
2148                        return false;
2149                    }
2150                }
2151                "nontoken" => {
2152                    if card.is_token {
2153                        return false;
2154                    }
2155                }
2156                "tapped" => {
2157                    if !card.tapped {
2158                        return false;
2159                    }
2160                }
2161                "untapped" => {
2162                    if card.tapped {
2163                        return false;
2164                    }
2165                }
2166                "startedtheturnuntapped" => {
2167                    if card.started_turn_tapped {
2168                        return false;
2169                    }
2170                }
2171                "startedtheturntapped" => {
2172                    if !card.started_turn_tapped {
2173                        return false;
2174                    }
2175                }
2176                "multicolor" => {
2177                    if !card.color.is_multicolor() {
2178                        return false;
2179                    }
2180                }
2181                "colorless" => {
2182                    if !card.color.is_colorless() {
2183                        return false;
2184                    }
2185                }
2186                "attacking"
2187                | "attackingyou"
2188                | "chosencolorsource"
2189                | "blocking"
2190                | "blocked"
2191                | "attackedthisturn"
2192                | "blockingsource"
2193                | "blockedbysource"
2194                | "toplibrary"
2195                | "exiledwithsource"
2196                | "rememberedplayerctrl" => {
2197                    if !legacy_matches_card_atom(raw, card, context) {
2198                        return false;
2199                    }
2200                }
2201                controlled if controlled.starts_with("controlledby ") => {
2202                    if !legacy_matches_card_atom(raw, card, context) {
2203                        return false;
2204                    }
2205                }
2206                "inzonebattlefield" => {
2207                    if card.zone != forge_foundation::ZoneType::Battlefield {
2208                        return false;
2209                    }
2210                }
2211                "inzonegraveyard" => {
2212                    if card.zone != forge_foundation::ZoneType::Graveyard {
2213                        return false;
2214                    }
2215                }
2216                "inzonehand" => {
2217                    if card.zone != forge_foundation::ZoneType::Hand {
2218                        return false;
2219                    }
2220                }
2221                "inzoneexile" => {
2222                    if card.zone != forge_foundation::ZoneType::Exile {
2223                        return false;
2224                    }
2225                }
2226                "damagedby" => {
2227                    // Check if this card was dealt damage by the source card this turn
2228                    if !card.damage_sources_this_turn.contains(&source.id) {
2229                        return false;
2230                    }
2231                }
2232                "equippedby" | "enchantedby" | "attachedby" => {
2233                    // Check if source is attached to this card
2234                    if source.attached_to != Some(card.id) {
2235                        return false;
2236                    }
2237                }
2238                "facedown"
2239                | "paired"
2240                | "pairedwith"
2241                | "equipped"
2242                | "enchanted"
2243                | "hascounters"
2244                | "isimprinted"
2245                | "chosen"
2246                | "chosencard"
2247                | "chosencardstrict"
2248                | "namedcard"
2249                | "chosencolor"
2250                | "thisturnentered"
2251                | "thisturnenteredfrom_battlefield"
2252                | "wasdealtdamagethisturn"
2253                | "historic"
2254                | "modified"
2255                | "issaddled"
2256                | "issolved"
2257                | "mayplaysource"
2258                | "suspended"
2259                | "singletarget"
2260                | "promisedgift" => {
2261                    if !legacy_matches_card_atom(raw, card, context) {
2262                        return false;
2263                    }
2264                }
2265                "wascast" => {
2266                    // Mirrors Java CardProperty.java:1923-1926 — card must have been
2267                    // cast (not put onto the battlefield by some other means).
2268                    if !card.was_cast() {
2269                        return false;
2270                    }
2271                }
2272                "wascastbyyou" => {
2273                    // Mirrors Java CardProperty.java:1923-1929: wasCast AND the
2274                    // spell's activating player equals source's controller.
2275                    // Rust doesn't track castSA.activatingPlayer separately; the
2276                    // card's controller at ETB time equals the caster for normal
2277                    // casts, which covers Sunderflock-style triggers.
2278                    if !card.was_cast() || card.controller != source.controller {
2279                        return false;
2280                    }
2281                }
2282                named if named.starts_with("named") => {
2283                    if !card.card_name.eq_ignore_ascii_case(raw[5..].trim()) {
2284                        return false;
2285                    }
2286                }
2287                _ => {
2288                    // Check counters_GE/GT/LT/LE/EQ patterns like "counters_GE3_P1P1"
2289                    if sub.starts_with("counters_") {
2290                        if !check_counter_condition(sub, card) {
2291                            return false;
2292                        }
2293                    } else if sub_lower.starts_with("cmc") {
2294                        // CMC comparisons: cmcEQ1, cmcLE3, cmcGE5
2295                        let original_rest = &sub[3..];
2296                        if !check_cmc_condition_with_context(original_rest, card, Some(context)) {
2297                            return false;
2298                        }
2299                    } else if let Some(rest) = sub_lower.strip_prefix("power") {
2300                        // Power comparisons: powerLE2, powerGE3, etc.
2301                        if !check_power_condition(rest, card) {
2302                            return false;
2303                        }
2304                    } else if let Some(rest) = sub_lower.strip_prefix("toughness") {
2305                        // Toughness comparisons: toughnessLE2, toughnessGE3, etc.
2306                        if !check_toughness_condition(rest, card) {
2307                            return false;
2308                        }
2309                    } else if let Some(color) = Color::from_name(&sub_lower) {
2310                        // Color names: white, blue, black, red, green
2311                        if !card.color.has_color(color) {
2312                            return false;
2313                        }
2314                    } else if let Some(kw) = sub_lower.strip_prefix("with") {
2315                        // "withFlying", "withoutFlying", etc.
2316                        if kw.strip_prefix("out").is_some() {
2317                            // "withoutFlying" — card must NOT have this keyword
2318                            let kw_name = &sub[7..]; // original case
2319                            if card.has_keyword(kw_name) {
2320                                return false;
2321                            }
2322                        } else if !kw.is_empty() {
2323                            // "withFlying" — card must have this keyword
2324                            let kw_name = &sub[4..]; // original case
2325                            if !card.has_keyword(kw_name) {
2326                                return false;
2327                            }
2328                        }
2329                    } else if let Some(negated) = sub_lower.strip_prefix("non") {
2330                        // Negated qualifier: "nonBlack", "nonArtifact", "nonFlying", etc.
2331                        let should_negate = match negated {
2332                            "creature" => card.is_creature(),
2333                            "land" => card.is_land(),
2334                            "artifact" => card.type_line.is_artifact(),
2335                            "enchantment" => card.type_line.is_enchantment(),
2336                            "legendary" => card.type_line.is_legendary(),
2337                            "basic" => card.type_line.is_basic(),
2338                            "snow" => card.type_line.is_snow(),
2339                            "token" => card.is_token,
2340                            "colorless" => card.color.is_colorless(),
2341                            _ => {
2342                                if let Some(color) = Color::from_name(negated) {
2343                                    card.color.has_color(color)
2344                                } else {
2345                                    // nonSubtype: e.g., "nonHuman", "nonWall"
2346                                    card.has_subtype(
2347                                        &sub[3..], // use original case for subtype
2348                                    )
2349                                }
2350                            }
2351                        };
2352                        if should_negate {
2353                            return false;
2354                        }
2355                    } else if sub_lower == "chosentype" {
2356                        // "ChosenType" — card must have the source card's chosen
2357                        // creature type. Changeling counts as all creature types.
2358                        // Mirrors Java CardTraitBase.isValid() ChosenType path.
2359                        let matches = if let Some(ref ct) = source.chosen_type {
2360                            card.type_line.has_subtype(ct) || card.has_keyword("Changeling")
2361                        } else {
2362                            false
2363                        };
2364                        if !matches {
2365                            return false;
2366                        }
2367                    } else if !sub.is_empty() {
2368                        // Color source check: "RedSource", "WhiteSource", "BlackSource", etc.
2369                        // Mirrors Java ForgeScript.cardStateHasProperty: strip "Source" suffix,
2370                        // then check card color. Also handles "nonRedSource" via the non- prefix above.
2371                        let color_name = sub.strip_suffix("Source").unwrap_or(sub);
2372                        if let Some(color) = Color::from_name(&color_name.to_lowercase()) {
2373                            if !card.color.has_color(color) {
2374                                return false;
2375                            }
2376                        } else if color_name.eq_ignore_ascii_case("Colorless") {
2377                            if !card.color.is_colorless() {
2378                                return false;
2379                            }
2380                        } else {
2381                            // Fall through: check as creature subtype (Wall, Zombie, etc.)
2382                            // Mirrors card_has_property behavior: unrecognized qualifiers
2383                            // are checked against the card's type_line subtypes.
2384                            if !card.has_subtype(sub) {
2385                                return false;
2386                            }
2387                        }
2388                    }
2389                }
2390            }
2391        }
2392    }
2393
2394    true
2395}
2396
2397/// Check if a player matches a filter expression like "You", "Opponent", "Each".
2398pub fn matches_valid_player(filter: &str, player: PlayerId, source_controller: PlayerId) -> bool {
2399    let filter = filter.trim();
2400    if filter.is_empty() {
2401        return true;
2402    }
2403
2404    // Handle comma-separated alternatives
2405    if filter.contains(',') {
2406        return filter
2407            .split(',')
2408            .any(|part| matches_single_valid_player(part.trim(), player, source_controller));
2409    }
2410
2411    matches_single_valid_player(filter, player, source_controller)
2412}
2413
2414/// Convenience wrapper: None means "no filter" → always matches.
2415pub fn matches_valid_player_opt(
2416    filter: Option<&str>,
2417    player: PlayerId,
2418    source_controller: PlayerId,
2419) -> bool {
2420    match filter {
2421        None => true,
2422        Some(v) => matches_valid_player(v, player, source_controller),
2423    }
2424}
2425
2426/// Match a precompiled selector against a player without reparsing the
2427/// comma-separated alternatives.
2428pub fn matches_valid_player_selector(
2429    selector: &CompiledSelector,
2430    player: PlayerId,
2431    source_controller: PlayerId,
2432) -> bool {
2433    let result = matches_player_selector_ir(&selector.ir, player, source_controller);
2434    #[cfg(debug_assertions)]
2435    report_selector_drift(
2436        "player",
2437        result,
2438        matches_valid_player(&selector.as_raw(), player, source_controller),
2439        &selector.as_raw(),
2440    );
2441    result
2442}
2443
2444fn matches_player_selector_ir(
2445    selector: &Selector,
2446    player: PlayerId,
2447    source_controller: PlayerId,
2448) -> bool {
2449    if selector.alternatives.is_empty() {
2450        return true;
2451    }
2452
2453    selector.alternatives.iter().any(|alternative| {
2454        alternative
2455            .predicates
2456            .iter()
2457            .all(|predicate| matches_player_predicate(predicate, player, source_controller))
2458    })
2459}
2460
2461fn matches_player_predicate(
2462    predicate: &SelectorPredicate,
2463    player: PlayerId,
2464    source_controller: PlayerId,
2465) -> bool {
2466    match predicate {
2467        SelectorPredicate::Any | SelectorPredicate::Player => true,
2468        SelectorPredicate::PlayerController(controller)
2469        | SelectorPredicate::CardController(controller) => {
2470            matches_player_controller(*controller, player, source_controller)
2471        }
2472        SelectorPredicate::Raw(raw) => matches_single_valid_player(raw, player, source_controller),
2473        // Legacy player matching treats unknown card-oriented predicates as
2474        // permissive, so keep that behavior for mixed ValidTarget paths.
2475        SelectorPredicate::CardType(_)
2476        | SelectorPredicate::CardSupertype(_)
2477        | SelectorPredicate::CardIdentity(_)
2478        | SelectorPredicate::CardOwner(_)
2479        | SelectorPredicate::Tapped(_)
2480        | SelectorPredicate::StartedTurnTapped(_)
2481        | SelectorPredicate::CameUnderControlSinceLastUpkeep
2482        | SelectorPredicate::Zone(_)
2483        | SelectorPredicate::RememberedCard
2484        | SelectorPredicate::TriggerRememberedCard
2485        | SelectorPredicate::EffectSource
2486        | SelectorPredicate::Commander
2487        | SelectorPredicate::Legendary
2488        | SelectorPredicate::Kicked
2489        | SelectorPredicate::Token(_)
2490        | SelectorPredicate::Color(_)
2491        | SelectorPredicate::Multicolor
2492        | SelectorPredicate::Colorless
2493        | SelectorPredicate::SourceColor(_)
2494        | SelectorPredicate::SourceColorless
2495        | SelectorPredicate::ChosenColorSource
2496        | SelectorPredicate::CardState(_)
2497        | SelectorPredicate::Context(_)
2498        | SelectorPredicate::Relation(_)
2499        | SelectorPredicate::DamagedBy
2500        | SelectorPredicate::AttachedBy
2501        | SelectorPredicate::WasCast { .. }
2502        | SelectorPredicate::ChosenType
2503        | SelectorPredicate::Keyword { .. }
2504        | SelectorPredicate::NumericComparison { .. }
2505        | SelectorPredicate::NumericParity { .. }
2506        | SelectorPredicate::CounterComparison { .. }
2507        | SelectorPredicate::Not(_) => true,
2508    }
2509}
2510
2511fn matches_player_controller(
2512    controller: ControllerSelector,
2513    player: PlayerId,
2514    source_controller: PlayerId,
2515) -> bool {
2516    match controller {
2517        ControllerSelector::You => player == source_controller,
2518        ControllerSelector::Opponent => player != source_controller,
2519    }
2520}
2521
2522/// Convenience wrapper: None means "no filter" -> always matches.
2523pub fn matches_valid_player_selector_opt(
2524    selector: Option<&CompiledSelector>,
2525    player: PlayerId,
2526    source_controller: PlayerId,
2527) -> bool {
2528    match selector {
2529        None => true,
2530        Some(selector) => matches_valid_player_selector(selector, player, source_controller),
2531    }
2532}
2533
2534/// Mirrors Java's `CardTraitBase.matchesValid(Object, String[], Card, Player)`.
2535///
2536/// Java uses polymorphic dispatch via `GameObject.isValid()` — both Card and
2537/// Player implement it. In Rust, we take both as Options and try card first,
2538/// then player, mirroring the `instanceof` chain in Java.
2539///
2540/// This eliminates the need for callers to guess whether a filter string can
2541/// match a player (the old `filter_can_match_player` heuristic).
2542pub fn matches_valid(
2543    filter: &str,
2544    card: Option<&Card>,
2545    player: Option<PlayerId>,
2546    source: &Card,
2547    source_controller: PlayerId,
2548) -> bool {
2549    if let Some(card) = card {
2550        matches_valid_card(filter, card, source)
2551    } else if let Some(player) = player {
2552        // Java parity: `Player.isValid` rejects card-oriented filter heads
2553        // (e.g. "Card.Self", "Permanent.YouCtrl"). Without this guard the
2554        // permissive fallback in `matches_single_valid_player` matches any
2555        // unknown head, causing triggers like Ward (`ValidTarget$ Card.Self`)
2556        // to fire on player targets.
2557        if !filter_head_can_match_player(filter) {
2558            return false;
2559        }
2560        matches_valid_player(filter, player, source_controller)
2561    } else {
2562        false
2563    }
2564}
2565
2566fn filter_head_can_match_player(filter: &str) -> bool {
2567    filter.split(',').any(|alternative| {
2568        let head = alternative
2569            .trim()
2570            .split(['.', '+'])
2571            .next()
2572            .unwrap_or("")
2573            .to_ascii_lowercase();
2574        matches!(
2575            head.as_str(),
2576            "" | "you"
2577                | "youctrl"
2578                | "youcontroller"
2579                | "opponent"
2580                | "oppctrl"
2581                | "opponentctrl"
2582                | "any"
2583                | "each"
2584                | "player"
2585                | "active"
2586                | "nonactive"
2587                | "remembered"
2588                | "isremembered"
2589                | "targetedplayer"
2590                | "playerctrl"
2591                | "playercontroller"
2592                | "controller"
2593                | "all"
2594        )
2595    })
2596}
2597
2598fn matches_single_valid_player(
2599    filter: &str,
2600    player: PlayerId,
2601    source_controller: PlayerId,
2602) -> bool {
2603    let filter_lower = filter.to_ascii_lowercase();
2604    if let Some(rest) = filter_lower.strip_prefix("player.") {
2605        return matches_single_valid_player(rest, player, source_controller);
2606    }
2607    match filter_lower.as_str() {
2608        "you" | "youctrl" => player == source_controller,
2609        "opponent" | "oppctrl" | "opponentctrl" => player != source_controller,
2610        "any" | "each" | "player" | "player.ingame" => true,
2611        // "Active" / "NonActive" would need turn info — not currently supported
2612        _ => true, // unknown filter, match all (permissive fallback)
2613    }
2614}
2615
2616/// Check a counter condition like "counters_GE3_P1P1".
2617/// Format: counters_{op}{num}_{counter_type}
2618fn check_counter_condition(condition: &str, card: &Card) -> bool {
2619    use crate::ability::effects::parse_counter_type;
2620    let rest = &condition["counters_".len()..];
2621    if rest.len() < 3 {
2622        return true;
2623    }
2624    let op = &rest[..2];
2625    let after_op = &rest[2..];
2626    let (num_str, counter_type_str) = match after_op.find('_') {
2627        Some(idx) => (&after_op[..idx], &after_op[idx + 1..]),
2628        None => return true,
2629    };
2630    let threshold: i32 = num_str.parse().unwrap_or(0);
2631    let counter_type = parse_counter_type(counter_type_str);
2632    let count = card.counter_count(&counter_type);
2633    match op {
2634        "GE" => count >= threshold,
2635        "GT" => count > threshold,
2636        "LE" => count <= threshold,
2637        "LT" => count < threshold,
2638        "EQ" => count == threshold,
2639        "NE" => count != threshold,
2640        _ => true,
2641    }
2642}
2643
2644/// Check a CMC condition like "cmcEQ1", "cmcLE3", or "cmcLEY".
2645fn check_cmc_condition_with_context(
2646    rest: &str,
2647    card: &Card,
2648    context: Option<MatchContext<'_>>,
2649) -> bool {
2650    let cmc = context
2651        .map(|ctx| effective_mana_value(card, ctx))
2652        .unwrap_or_else(|| card.mana_cost.cmc());
2653    let lower = rest.to_ascii_lowercase();
2654    if lower.starts_with("eq") {
2655        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2656            return cmc == n;
2657        }
2658    } else if lower.starts_with("le") {
2659        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2660            return cmc <= n;
2661        }
2662    } else if lower.starts_with("ge") {
2663        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2664            return cmc >= n;
2665        }
2666    } else if lower.starts_with("lt") {
2667        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2668            return cmc < n;
2669        }
2670    } else if lower.starts_with("gt") {
2671        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2672            return cmc > n;
2673        }
2674    } else if lower.starts_with("ne") {
2675        if let Some(n) = parse_cmc_threshold(&rest[2..], context) {
2676            return cmc != n;
2677        }
2678    }
2679    true // fallback: unknown format passes
2680}
2681
2682fn parse_cmc_threshold(value: &str, context: Option<MatchContext<'_>>) -> Option<i32> {
2683    if let Ok(n) = value.parse::<i32>() {
2684        return Some(n);
2685    }
2686    let context = context?;
2687    // Keep in sync with resolve_selector_operand: X reads the paid X
2688    // from the live spell ability (Java passes the casting SA into
2689    // calculateAmount), not the host SVar evaluated without it.
2690    if value.eq_ignore_ascii_case("X") {
2691        if let Some(sa) = context.spell_ability {
2692            return Some(sa.x_mana_cost_paid as i32);
2693        }
2694    }
2695    let raw = context.source_card.get_s_var(value)?;
2696    if let Ok(n) = raw.trim().parse::<i32>() {
2697        return Some(n);
2698    }
2699    if raw.starts_with("Count$") || raw.starts_with("PlayerCount") {
2700        let game = context.game?;
2701        let sa = crate::spellability::SpellAbility::new_empty(
2702            Some(context.source_card.id),
2703            context.source_controller,
2704        );
2705        return Some(crate::svar::resolve_svar_expression(
2706            raw,
2707            game,
2708            context.source_card.id,
2709            context.source_controller,
2710            &sa,
2711        ));
2712    }
2713    None
2714}
2715
2716/// Check a power condition like "LE2", "GE3", "EQ0".
2717fn check_power_condition(rest: &str, card: &Card) -> bool {
2718    let power = card.power();
2719    if let Some(num_str) = rest.strip_prefix("eq") {
2720        if let Ok(n) = num_str.parse::<i32>() {
2721            return power == n;
2722        }
2723    } else if let Some(num_str) = rest.strip_prefix("le") {
2724        if let Ok(n) = num_str.parse::<i32>() {
2725            return power <= n;
2726        }
2727    } else if let Some(num_str) = rest.strip_prefix("ge") {
2728        if let Ok(n) = num_str.parse::<i32>() {
2729            return power >= n;
2730        }
2731    } else if let Some(num_str) = rest.strip_prefix("lt") {
2732        if let Ok(n) = num_str.parse::<i32>() {
2733            return power < n;
2734        }
2735    } else if let Some(num_str) = rest.strip_prefix("gt") {
2736        if let Ok(n) = num_str.parse::<i32>() {
2737            return power > n;
2738        }
2739    } else if let Some(num_str) = rest.strip_prefix("ne") {
2740        if let Ok(n) = num_str.parse::<i32>() {
2741            return power != n;
2742        }
2743    }
2744    true // fallback: unknown format passes
2745}
2746
2747/// Check a toughness condition like "LE2", "GE3", "EQ0".
2748fn check_toughness_condition(rest: &str, card: &Card) -> bool {
2749    let toughness = card.toughness();
2750    if let Some(num_str) = rest.strip_prefix("eq") {
2751        if let Ok(n) = num_str.parse::<i32>() {
2752            return toughness == n;
2753        }
2754    } else if let Some(num_str) = rest.strip_prefix("le") {
2755        if let Ok(n) = num_str.parse::<i32>() {
2756            return toughness <= n;
2757        }
2758    } else if let Some(num_str) = rest.strip_prefix("ge") {
2759        if let Ok(n) = num_str.parse::<i32>() {
2760            return toughness >= n;
2761        }
2762    } else if let Some(num_str) = rest.strip_prefix("lt") {
2763        if let Ok(n) = num_str.parse::<i32>() {
2764            return toughness < n;
2765        }
2766    } else if let Some(num_str) = rest.strip_prefix("gt") {
2767        if let Ok(n) = num_str.parse::<i32>() {
2768            return toughness > n;
2769        }
2770    } else if let Some(num_str) = rest.strip_prefix("ne") {
2771        if let Ok(n) = num_str.parse::<i32>() {
2772            return toughness != n;
2773        }
2774    }
2775    true // fallback: unknown format passes
2776}
2777
2778// ── Common requirement checks ───────────────────────────────────────────────
2779//
2780// These mirror Java's `CardTraitBase.meetsCommonRequirements()` — shared
2781// validation logic used by triggers, static abilities, replacement effects,
2782// and cost adjustment. Previously duplicated in 4+ locations.
2783
2784pub fn check_svar_requirement(
2785    game: &GameState,
2786    source: &Card,
2787    svar_source: &dyn HasSVars,
2788    check_name: &str,
2789    compare: &str,
2790) -> bool {
2791    let value = requirement_amount(source, svar_source, check_name, game);
2792    compare_requirement_amount(source, svar_source, compare, game, value)
2793}
2794
2795fn check_condition_value(game: &GameState, condition: Option<&str>, source: &Card) -> bool {
2796    let Some(condition) = condition else {
2797        return true;
2798    };
2799    let controller = requirement_controller(game, source);
2800    match condition {
2801        "PlayerTurn" => game.active_player() == controller,
2802        "NotPlayerTurn" => game.active_player() != controller,
2803        "Threshold" => game.player_has_threshold(controller),
2804        "Hellbent" => game.player_has_hellbent(controller),
2805        "Metalcraft" => game.player_has_metalcraft(controller),
2806        "Delirium" => game.player_has_delirium(controller),
2807        "Ferocious" => game.player_has_ferocious(controller),
2808        "Desert" => game.player_has_desert(controller),
2809        "Blessing" => game.player_has_blessing(controller),
2810        "Solved" => source.is_solved(),
2811        "Monarch" => game.monarch == Some(controller),
2812        "Night" => game.is_night,
2813        "FatefulHour" => game.player(controller).life <= 5,
2814        _ => true, // unknown condition — permissive fallback
2815    }
2816}
2817
2818fn meets_card_trait_requirements(
2819    requirements: &CardTraitRequirementsIr,
2820    game: &GameState,
2821    source: &Card,
2822    svar_source: &dyn HasSVars,
2823) -> bool {
2824    if requirements.is_empty() {
2825        return true;
2826    }
2827
2828    let _perf_scope =
2829        crate::perf::ParamsLookupScopeGuard::enter(crate::perf::ParamsLookupScope::ValidFilter);
2830    let controller = requirement_controller(game, source);
2831
2832    if !check_boolean_requirement(
2833        requirements.metalcraft.as_deref(),
2834        game.player_has_metalcraft(controller),
2835    ) {
2836        return false;
2837    }
2838    if !check_boolean_requirement(
2839        requirements.delirium.as_deref(),
2840        game.player_has_delirium(controller),
2841    ) {
2842        return false;
2843    }
2844    if !check_boolean_requirement(
2845        requirements.threshold.as_deref(),
2846        game.player_has_threshold(controller),
2847    ) {
2848        return false;
2849    }
2850    if !check_boolean_requirement(
2851        requirements.hellbent.as_deref(),
2852        game.player_has_hellbent(controller),
2853    ) {
2854        return false;
2855    }
2856    if !check_boolean_requirement(
2857        requirements.bloodthirst.as_deref(),
2858        game.player_has_bloodthirst(controller),
2859    ) {
2860        return false;
2861    }
2862    if !check_boolean_requirement(
2863        requirements.fateful_hour.as_deref(),
2864        game.player(controller).life <= 5,
2865    ) {
2866        return false;
2867    }
2868    if !check_boolean_requirement(
2869        requirements.monarch.as_deref(),
2870        game.monarch == Some(controller),
2871    ) {
2872        return false;
2873    }
2874    if let Some(revolt) = requirements.revolt.as_deref() {
2875        if revolt.eq_ignore_ascii_case("True") != game.player_has_revolt(controller) {
2876            return false;
2877        } else if revolt.eq_ignore_ascii_case("None")
2878            && game
2879                .alive_players()
2880                .into_iter()
2881                .any(|pid| game.player_has_revolt(pid))
2882        {
2883            return false;
2884        }
2885    }
2886    if !check_boolean_requirement(
2887        requirements.desert.as_deref(),
2888        game.player_has_desert(controller),
2889    ) {
2890        return false;
2891    }
2892    if !check_boolean_requirement(
2893        requirements.blessing.as_deref(),
2894        game.player_has_blessing(controller),
2895    ) {
2896        return false;
2897    }
2898
2899    if let Some(day_time) = requirements.day_time.as_deref() {
2900        if day_time.eq_ignore_ascii_case("Day") {
2901            if !game.is_day() {
2902                return false;
2903            }
2904        } else if day_time.eq_ignore_ascii_case("Night") {
2905            if !game.is_night {
2906                return false;
2907            }
2908        } else if day_time.eq_ignore_ascii_case("Neither") && !game.is_neither_day_nor_night() {
2909            return false;
2910        }
2911    }
2912
2913    if let Some(adamant) = requirements.adamant.as_deref() {
2914        let color_mask = ManaAtom::from_name(&adamant.to_ascii_lowercase());
2915        if adamant.eq_ignore_ascii_case("Any") {
2916            let has_three = [
2917                ManaAtom::WHITE,
2918                ManaAtom::BLUE,
2919                ManaAtom::BLACK,
2920                ManaAtom::RED,
2921                ManaAtom::GREEN,
2922            ]
2923            .into_iter()
2924            .any(|mask| paying_color_count(&source.paying_mana_to_cast, mask) >= 3);
2925            if !has_three {
2926                return false;
2927            }
2928        } else if paying_color_count(&source.paying_mana_to_cast, color_mask) < 3 {
2929            return false;
2930        }
2931    }
2932
2933    if let Some(life_total) = requirements.life_total.as_deref() {
2934        let compare = requirements.life_amount.as_deref().unwrap_or("GE1");
2935        let life = player_life_for_requirement(game, source, life_total);
2936        if !compare_requirement_amount(source, svar_source, compare, game, life) {
2937            return false;
2938        }
2939    }
2940
2941    if let Some(is_present) = requirements.is_present.as_deref() {
2942        let present_compare = requirements.present_compare.as_deref().unwrap_or("GE1");
2943        let present_player = requirements.present_player.as_deref().unwrap_or("Any");
2944        let present_zone = requirements
2945            .present_zone
2946            .as_deref()
2947            .and_then(parse_zone_name)
2948            .unwrap_or(ZoneType::Battlefield);
2949        let selector = requirements
2950            .is_present_selector
2951            .clone()
2952            .unwrap_or_else(|| cached_compiled_selector(is_present));
2953        let count = collect_present_cards(
2954            game,
2955            source,
2956            requirements.present_defined.as_deref(),
2957            present_player,
2958            present_zone,
2959        )
2960        .into_iter()
2961        .filter(|&cid| matches_valid_card_selector_in_game(&selector, game.card(cid), source, game))
2962        .count() as i32;
2963        if !compare_requirement_amount(source, svar_source, present_compare, game, count) {
2964            return false;
2965        }
2966    }
2967
2968    if let Some(is_present) = requirements.is_present2.as_deref() {
2969        let present_compare = requirements.present_compare2.as_deref().unwrap_or("GE1");
2970        let present_player = requirements.present_player2.as_deref().unwrap_or("Any");
2971        let present_zone = requirements
2972            .present_zone2
2973            .as_deref()
2974            .and_then(parse_zone_name)
2975            .unwrap_or(ZoneType::Battlefield);
2976        let selector = requirements
2977            .is_present2_selector
2978            .clone()
2979            .unwrap_or_else(|| cached_compiled_selector(is_present));
2980        let count = collect_present_cards(game, source, None, present_player, present_zone)
2981            .into_iter()
2982            .filter(|&cid| {
2983                matches_valid_card_selector_in_game(&selector, game.card(cid), source, game)
2984            })
2985            .count() as i32;
2986        if !compare_requirement_amount(source, svar_source, present_compare, game, count) {
2987            return false;
2988        }
2989    }
2990
2991    if let Some(defined_players) = requirements.check_defined_player.as_deref() {
2992        let players = crate::ability::ability_utils::get_defined_players(
2993            game,
2994            Some(source.id),
2995            defined_players,
2996            Some(controller),
2997        );
2998        let compare = requirements
2999            .defined_player_compare
3000            .as_deref()
3001            .unwrap_or("GE1");
3002        if !compare_requirement_amount(source, svar_source, compare, game, players.len() as i32) {
3003            return false;
3004        }
3005    }
3006
3007    if let Some(check_name) = requirements.check_svar.as_deref() {
3008        let compare = requirements.svar_compare.as_deref().unwrap_or("GE1");
3009        if !check_svar_requirement(game, source, svar_source, check_name, compare) {
3010            return false;
3011        }
3012        if let Some(check_name) = requirements.check_second_svar.as_deref() {
3013            let compare = requirements.second_svar_compare.as_deref().unwrap_or("GE1");
3014            if !check_svar_requirement(game, source, svar_source, check_name, compare) {
3015                return false;
3016            }
3017        }
3018    }
3019
3020    if let Some(mana_spent) = requirements.mana_spent.as_deref() {
3021        let colors = ManaAtom::from_name(&mana_spent.to_ascii_lowercase());
3022        if !has_all_spent_colors(source.colors_spent_to_cast, colors) {
3023            return false;
3024        }
3025    }
3026    if let Some(mana_not_spent) = requirements.mana_not_spent.as_deref() {
3027        let colors = ManaAtom::from_name(&mana_not_spent.to_ascii_lowercase());
3028        if has_all_spent_colors(source.colors_spent_to_cast, colors) {
3029            return false;
3030        }
3031    }
3032
3033    if requirements.werewolf_transform_condition
3034        && !game.stack.get_spells_cast_last_turn().is_empty()
3035    {
3036        return false;
3037    }
3038    if requirements.werewolf_untransform_condition {
3039        let cast_last_turn = game.stack.get_spells_cast_last_turn();
3040        let mut condition_met = false;
3041        for pid in game.alive_players() {
3042            let count = cast_last_turn
3043                .iter()
3044                .filter(|&&cid| game.card(cid).controller == pid)
3045                .count();
3046            if count > 1 {
3047                condition_met = true;
3048                break;
3049            }
3050        }
3051        if !condition_met {
3052            return false;
3053        }
3054    }
3055
3056    if let Some(class_level) = requirements.class_level.as_deref() {
3057        let min = class_level.parse::<i32>().unwrap_or(0);
3058        if source.class_level < min {
3059            return false;
3060        }
3061    }
3062
3063    check_condition_value(game, requirements.condition.as_deref(), source)
3064}
3065
3066/// Parse a zone name string into ZoneType.
3067fn parse_zone_name(name: &str) -> Option<ZoneType> {
3068    ZoneType::from_str_compat(name)
3069}