Skip to main content

ferrichess_study/tree/
builder.rs

1use std::collections::HashMap;
2
3use shakmaty::{Chess, Move, Position};
4
5use crate::{
6    domain::{DepthLimit, PositionKey, RepertoireSide},
7    raw::{EmbeddedMove, ParsedMove, RawParser},
8};
9
10use super::{
11    CommentVariationDecision, MoveTree, NodeId, TreeError, policy::decide_comment_variation,
12};
13
14/// Why a nonblank source line was retained as a comment.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum CommentReason {
17    /// The line did not begin with an explicit move number.
18    Prose,
19    /// The line uses `--` as an instructional placeholder for an irrelevant move.
20    InstructionalNullMove,
21    /// The line's explicit move number precedes the current mainline position.
22    BacktrackedMove,
23    /// No legal move could be read at the current position.
24    NoLegalMove,
25    /// Legal moves were followed by text that could not be parsed as moves.
26    UnparsedTail,
27    /// The line explicitly attaches a comment to an exact mainline ply.
28    ExactPly,
29}
30
31/// The position-aware classification of one raw source line.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub enum ClassifiedRawLine {
34    Blank,
35    Mainline {
36        starting_ply: Option<u32>,
37        moves: Vec<ParsedMove>,
38    },
39    Comment {
40        text: String,
41        reason: CommentReason,
42        starting_ply: Option<u32>,
43        moves: Vec<ParsedMove>,
44        leftover: String,
45    },
46}
47
48/// A classified source line with its one-based line number.
49#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct RawLineRecord {
51    pub line_number: usize,
52    pub original: String,
53    pub classification: ClassifiedRawLine,
54}
55
56/// A move tree and the trace used to construct it from raw text.
57#[derive(Clone, Debug, Eq, PartialEq)]
58pub struct BuiltRawTree {
59    pub tree: MoveTree,
60    pub lines: Vec<RawLineRecord>,
61}
62
63/// Builds one mainline move tree from raw repertoire text.
64#[derive(Clone, Debug)]
65pub struct RawTreeBuilder {
66    parser: RawParser,
67    repertoire_side: RepertoireSide,
68    depth_limit: DepthLimit,
69    comment_variations: bool,
70}
71
72impl RawTreeBuilder {
73    #[must_use]
74    pub fn new(repertoire_side: RepertoireSide) -> Self {
75        Self {
76            parser: RawParser::new(),
77            repertoire_side,
78            depth_limit: DepthLimit::Unlimited,
79            comment_variations: false,
80        }
81    }
82
83    #[must_use]
84    pub const fn with_depth_limit(mut self, depth_limit: DepthLimit) -> Self {
85        self.depth_limit = depth_limit;
86        self
87    }
88
89    /// Enables compatible numbered move sequences in comments as variations.
90    #[must_use]
91    pub const fn with_comment_variations(mut self, enabled: bool) -> Self {
92        self.comment_variations = enabled;
93        self
94    }
95
96    /// Parses raw text without performing any filesystem or rendering work.
97    pub fn build(&self, text: &str) -> Result<BuiltRawTree, TreeError> {
98        let source_lines: Vec<&str> = text.lines().collect();
99        let (final_clean_ply, repertoire_moves) = self.scan_clean_mainline(&source_lines);
100        let mut tree = MoveTree::new();
101        let mut position = Chess::default();
102        let mut positions_by_ply = vec![position.clone()];
103        let mut nodes_by_ply = vec![tree.root()];
104        let mut current_node = Some(tree.root());
105        let mut records = Vec::new();
106        let mut exact_ply_comments = Vec::new();
107        let maximum_ply = self.maximum_ply();
108
109        for (line_index, original) in source_lines.iter().copied().enumerate() {
110            let stripped = original.trim();
111            let classification = if stripped.is_empty() {
112                ClassifiedRawLine::Blank
113            } else if let Some((ply, text)) = parse_ply_comment_directive(stripped) {
114                exact_ply_comments.push((line_index + 1, ply, text.to_owned()));
115                ClassifiedRawLine::Comment {
116                    text: text.to_owned(),
117                    reason: CommentReason::ExactPly,
118                    starting_ply: Some(ply),
119                    moves: Vec::new(),
120                    leftover: String::new(),
121                }
122            } else if self.parser.has_instructional_null_move(stripped) {
123                let normalized = self.parser.normalize_comment_text(
124                    stripped,
125                    Some(&position),
126                    Some(&positions_by_ply),
127                );
128                self.attach_comment(&mut tree, current_node, &normalized)?;
129                ClassifiedRawLine::Comment {
130                    text: normalized,
131                    reason: CommentReason::InstructionalNullMove,
132                    starting_ply: self.parser.starting_ply_for_move_line(stripped),
133                    moves: Vec::new(),
134                    leftover: String::new(),
135                }
136            } else if !self.parser.is_move_line(stripped) {
137                let normalized = self.parser.normalize_comment_text(
138                    stripped,
139                    Some(&position),
140                    Some(&positions_by_ply),
141                );
142                self.attach_comment(&mut tree, current_node, &normalized)?;
143                self.maybe_add_comment_variation(
144                    &mut tree,
145                    &nodes_by_ply,
146                    &positions_by_ply,
147                    current_node,
148                    stripped,
149                    &source_lines,
150                    line_index,
151                    &position,
152                    final_clean_ply,
153                    maximum_ply,
154                    &repertoire_moves,
155                )?;
156                ClassifiedRawLine::Comment {
157                    text: normalized,
158                    reason: CommentReason::Prose,
159                    starting_ply: None,
160                    moves: Vec::new(),
161                    leftover: String::new(),
162                }
163            } else {
164                let starting_ply = self.parser.starting_ply_for_move_line(stripped);
165                if starting_ply.is_some_and(|ply| ply < position_ply(&position)) {
166                    let normalized = self.parser.normalize_comment_text(
167                        stripped,
168                        Some(&position),
169                        Some(&positions_by_ply),
170                    );
171                    self.attach_comment(&mut tree, current_node, &normalized)?;
172                    self.maybe_add_comment_variation(
173                        &mut tree,
174                        &nodes_by_ply,
175                        &positions_by_ply,
176                        current_node,
177                        stripped,
178                        &source_lines,
179                        line_index,
180                        &position,
181                        final_clean_ply,
182                        maximum_ply,
183                        &repertoire_moves,
184                    )?;
185                    ClassifiedRawLine::Comment {
186                        text: normalized,
187                        reason: CommentReason::BacktrackedMove,
188                        starting_ply,
189                        moves: Vec::new(),
190                        leftover: String::new(),
191                    }
192                } else {
193                    let parsed = self.parser.parse_move_line(stripped, &position);
194                    if parsed.moves.is_empty() || !parsed.leftover.is_empty() {
195                        let reason = if parsed.moves.is_empty() {
196                            CommentReason::NoLegalMove
197                        } else {
198                            CommentReason::UnparsedTail
199                        };
200                        let normalized = self.parser.normalize_comment_text(
201                            stripped,
202                            Some(&position),
203                            Some(&positions_by_ply),
204                        );
205                        self.attach_comment(&mut tree, current_node, &normalized)?;
206                        self.maybe_add_comment_variation(
207                            &mut tree,
208                            &nodes_by_ply,
209                            &positions_by_ply,
210                            current_node,
211                            stripped,
212                            &source_lines,
213                            line_index,
214                            &position,
215                            final_clean_ply,
216                            maximum_ply,
217                            &repertoire_moves,
218                        )?;
219                        ClassifiedRawLine::Comment {
220                            text: normalized,
221                            reason,
222                            starting_ply,
223                            moves: parsed.moves,
224                            leftover: parsed.leftover,
225                        }
226                    } else {
227                        for parsed_move in &parsed.moves {
228                            let next_ply = position_ply(&position) + 1;
229                            if maximum_ply.is_none_or(|limit| next_ply <= limit) {
230                                let parent = current_node.expect(
231                                    "an included move cannot follow an excluded mainline move",
232                                );
233                                let child = find_child(&tree, parent, parsed_move.chess_move)
234                                    .map_or_else(
235                                        || tree.add_child(parent, parsed_move.chess_move),
236                                        Ok,
237                                    )?;
238                                tree.promote_child(parent, child)?;
239                                if let Some(annotation) = parsed_move.annotation {
240                                    tree.node_mut(child)
241                                        .ok_or(TreeError::UnknownNode(child))?
242                                        .add_annotation(annotation);
243                                }
244                                current_node = Some(child);
245                            } else {
246                                current_node = None;
247                            }
248
249                            position.play_unchecked(parsed_move.chess_move);
250                            positions_by_ply.push(position.clone());
251                            if let Some(node) = current_node {
252                                nodes_by_ply.push(node);
253                            }
254                        }
255                        ClassifiedRawLine::Mainline {
256                            starting_ply,
257                            moves: parsed.moves,
258                        }
259                    }
260                }
261            };
262
263            records.push(RawLineRecord {
264                line_number: line_index + 1,
265                original: original.to_owned(),
266                classification,
267            });
268        }
269
270        for (line_number, ply, text) in exact_ply_comments {
271            if let Some(&node) = nodes_by_ply.get(ply as usize) {
272                self.attach_comment(&mut tree, Some(node), &text)?;
273            } else if maximum_ply.is_none_or(|limit| ply <= limit) {
274                return Err(TreeError::PlyCommentOutOfBounds {
275                    line_number,
276                    ply,
277                    available_plies: nodes_by_ply.len().saturating_sub(1) as u32,
278                });
279            }
280        }
281
282        tree.validate()?;
283        Ok(BuiltRawTree {
284            tree,
285            lines: records,
286        })
287    }
288
289    #[allow(clippy::too_many_arguments)]
290    fn maybe_add_comment_variation(
291        &self,
292        tree: &mut MoveTree,
293        nodes_by_ply: &[NodeId],
294        positions_by_ply: &[Chess],
295        current_node: Option<NodeId>,
296        text: &str,
297        source_lines: &[&str],
298        line_index: usize,
299        current_position: &Chess,
300        final_clean_ply: u32,
301        maximum_ply: Option<u32>,
302        repertoire_moves: &HashMap<PositionKey, Move>,
303    ) -> Result<(), TreeError> {
304        if !self.comment_variations
305            || current_node.is_none()
306            || !self.has_later_clean_move_line(&source_lines[line_index + 1..], current_position)
307        {
308            return Ok(());
309        }
310        let Some(start_ply) = self.parser.first_numbered_ply(text) else {
311            return Ok(());
312        };
313        let (anchor, anchor_position) = if let (Some(&node), Some(position)) = (
314            nodes_by_ply.get(start_ply as usize),
315            positions_by_ply.get(start_ply as usize),
316        ) {
317            (node, position.clone())
318        } else if start_ply == position_ply(current_position) {
319            (
320                current_node.expect("checked above"),
321                current_position.clone(),
322            )
323        } else {
324            return Ok(());
325        };
326        let moves = self
327            .parser
328            .parse_embedded_move_sequences(text, &anchor_position);
329        let variation_end = start_ply.saturating_add(moves.len() as u32);
330        if moves.is_empty()
331            || variation_end > final_clean_ply
332            || maximum_ply.is_some_and(|limit| variation_end > limit)
333        {
334            return Ok(());
335        }
336        self.add_variation_line(tree, anchor, anchor_position, &moves, repertoire_moves)
337    }
338
339    fn add_variation_line(
340        &self,
341        tree: &mut MoveTree,
342        anchor: NodeId,
343        position: Chess,
344        moves: &[EmbeddedMove],
345        repertoire_moves: &HashMap<PositionKey, Move>,
346    ) -> Result<(), TreeError> {
347        if decide_comment_variation(
348            tree,
349            anchor,
350            &position,
351            moves,
352            self.repertoire_side,
353            repertoire_moves,
354        ) != CommentVariationDecision::Accepted
355        {
356            return Ok(());
357        }
358        let mut parent = anchor;
359        for item in moves {
360            let child = match find_child(tree, parent, item.chess_move) {
361                Some(child) => child,
362                None => {
363                    let child = tree.add_child(parent, item.chess_move)?;
364                    if let Some(annotation) = item.annotation {
365                        tree.node_mut(child)
366                            .ok_or(TreeError::UnknownNode(child))?
367                            .add_annotation(annotation);
368                    }
369                    child
370                }
371            };
372            parent = child;
373        }
374        Ok(())
375    }
376
377    fn scan_clean_mainline(&self, lines: &[&str]) -> (u32, HashMap<PositionKey, Move>) {
378        let mut position = Chess::default();
379        let mut choices = HashMap::new();
380        for line in lines {
381            let stripped = line.trim();
382            if !self.parser.is_move_line(stripped)
383                || self
384                    .parser
385                    .starting_ply_for_move_line(stripped)
386                    .is_some_and(|ply| ply < position_ply(&position))
387            {
388                continue;
389            }
390            let parsed = self.parser.parse_move_line(stripped, &position);
391            if parsed.moves.is_empty() || !parsed.leftover.is_empty() {
392                continue;
393            }
394            for item in parsed.moves {
395                if self.repertoire_side.is_repertoire_turn(position.turn()) {
396                    choices.insert(PositionKey::from_position(&position), item.chess_move);
397                }
398                position.play_unchecked(item.chess_move);
399            }
400        }
401        (position_ply(&position), choices)
402    }
403
404    fn has_later_clean_move_line(&self, lines: &[&str], position: &Chess) -> bool {
405        for line in lines {
406            let stripped = line.trim();
407            if !self.parser.is_move_line(stripped)
408                || self
409                    .parser
410                    .starting_ply_for_move_line(stripped)
411                    .is_some_and(|ply| ply < position_ply(position))
412            {
413                continue;
414            }
415            let parsed = self.parser.parse_move_line(stripped, position);
416            return !parsed.moves.is_empty() && parsed.leftover.is_empty();
417        }
418        false
419    }
420
421    fn attach_comment(
422        &self,
423        tree: &mut MoveTree,
424        node: Option<NodeId>,
425        text: &str,
426    ) -> Result<(), TreeError> {
427        if text.is_empty() || node.is_none() {
428            return Ok(());
429        }
430        let node = node.expect("checked above");
431        tree.node_mut(node)
432            .ok_or(TreeError::UnknownNode(node))?
433            .add_comment(text);
434        Ok(())
435    }
436
437    fn maximum_ply(&self) -> Option<u32> {
438        let DepthLimit::RepertoireMoves(moves) = self.depth_limit else {
439            return None;
440        };
441        if moves == 0 {
442            return Some(0);
443        }
444        Some(match self.repertoire_side {
445            RepertoireSide::White => moves.saturating_mul(2).saturating_sub(1),
446            RepertoireSide::Black => moves.saturating_mul(2),
447        })
448    }
449}
450
451fn find_child(tree: &MoveTree, parent: NodeId, chess_move: Move) -> Option<NodeId> {
452    tree.node(parent)?
453        .children()
454        .iter()
455        .copied()
456        .find(|&child| {
457            tree.node(child)
458                .and_then(super::Node::chess_move)
459                .is_some_and(|candidate| candidate == chess_move)
460        })
461}
462
463fn position_ply(position: &Chess) -> u32 {
464    (position.fullmoves().get() - 1) * 2 + u32::from(position.turn().is_black())
465}
466
467fn parse_ply_comment_directive(line: &str) -> Option<(u32, &str)> {
468    let remainder = line.strip_prefix("@@PlyComment@@")?;
469    let (ply, text) = remainder.split_once("@@")?;
470    Some((ply.parse().ok()?, text))
471}
472
473#[cfg(test)]
474mod tests {
475    use shakmaty::{Chess, Position, san::SanPlus};
476
477    use crate::{
478        domain::{Annotation, DepthLimit, RepertoireSide},
479        tree::{ClassifiedRawLine, CommentReason, MoveTree, RawTreeBuilder},
480    };
481
482    fn mainline_sans(tree: &MoveTree) -> Vec<String> {
483        let mut position = Chess::default();
484        let mut node = tree.root();
485        let mut sans = Vec::new();
486        while let Some(&child) = tree.node(node).unwrap().children().first() {
487            let chess_move = tree.node(child).unwrap().chess_move().unwrap();
488            sans.push(SanPlus::from_move(position.clone(), chess_move).to_string());
489            position.play_unchecked(chess_move);
490            node = child;
491        }
492        sans
493    }
494
495    fn final_mainline_node(tree: &MoveTree) -> crate::tree::NodeId {
496        let mut node = tree.root();
497        while let Some(&child) = tree.node(node).unwrap().children().first() {
498            node = child;
499        }
500        node
501    }
502
503    fn node_after(tree: &MoveTree, sans: &[&str]) -> (crate::tree::NodeId, Chess) {
504        let mut position = Chess::default();
505        let mut node = tree.root();
506        for expected in sans {
507            let child = tree
508                .node(node)
509                .unwrap()
510                .children()
511                .iter()
512                .copied()
513                .find(|&child| {
514                    let chess_move = tree.node(child).unwrap().chess_move().unwrap();
515                    SanPlus::from_move(position.clone(), chess_move).to_string() == *expected
516                })
517                .unwrap_or_else(|| panic!("missing {expected} after {sans:?}"));
518            let chess_move = tree.node(child).unwrap().chess_move().unwrap();
519            position.play_unchecked(chess_move);
520            node = child;
521        }
522        (node, position)
523    }
524
525    fn child_sans(tree: &MoveTree, node: crate::tree::NodeId, position: &Chess) -> Vec<String> {
526        tree.node(node)
527            .unwrap()
528            .children()
529            .iter()
530            .map(|&child| {
531                SanPlus::from_move(
532                    position.clone(),
533                    tree.node(child).unwrap().chess_move().unwrap(),
534                )
535                .to_string()
536            })
537            .collect()
538    }
539
540    #[test]
541    fn builds_glued_mainline_and_preserves_annotations() {
542        let built = RawTreeBuilder::new(RepertoireSide::White)
543            .build("1. e4e5?2. Nf3?!Nc6")
544            .unwrap();
545
546        assert_eq!(mainline_sans(&built.tree), ["e4", "e5", "Nf3", "Nc6"]);
547        let ids: Vec<_> = built.tree.traverse().collect();
548        assert_eq!(
549            built.tree.node(ids[2]).unwrap().annotations(),
550            &[Annotation::Mistake].into_iter().collect()
551        );
552        assert_eq!(
553            built.tree.node(ids[3]).unwrap().annotations(),
554            &[Annotation::Dubious].into_iter().collect()
555        );
556    }
557
558    #[test]
559    fn attaches_exact_ply_comments_without_splitting_a_black_mainline() {
560        let built = RawTreeBuilder::new(RepertoireSide::Black)
561            .build(concat!(
562                "1. e4 1... c6 2. d4 d5\n",
563                "@@PlyComment@@1@@[%cal Ge2e4]\n",
564                "@@PlyComment@@2@@[%csl Rc6]"
565            ))
566            .unwrap();
567        assert_eq!(mainline_sans(&built.tree), ["e4", "c6", "d4", "d5"]);
568        let e4 = built.tree.traverse().nth(1).unwrap();
569        let c6 = built.tree.traverse().nth(2).unwrap();
570        assert_eq!(
571            built.tree.node(e4).unwrap().comments()[0].as_str(),
572            "[%cal Ge2e4]"
573        );
574        assert_eq!(
575            built.tree.node(c6).unwrap().comments()[0].as_str(),
576            "[%csl Rc6]"
577        );
578        assert!(matches!(
579            built.lines[1].classification,
580            ClassifiedRawLine::Comment {
581                reason: CommentReason::ExactPly,
582                starting_ply: Some(1),
583                ..
584            }
585        ));
586    }
587
588    #[test]
589    fn rejects_an_exact_ply_comment_beyond_the_mainline() {
590        let error = RawTreeBuilder::new(RepertoireSide::White)
591            .build("1. e4 e5\n@@PlyComment@@3@@[%cal Ge2e4]")
592            .unwrap_err();
593        assert!(matches!(
594            error,
595            crate::tree::TreeError::PlyCommentOutOfBounds {
596                line_number: 2,
597                ply: 3,
598                available_plies: 2
599            }
600        ));
601    }
602
603    #[test]
604    fn classifies_backtracked_and_partial_move_lines_as_comments() {
605        let input = concat!(
606            "1. e4c52. Nf3Nc63. d4cxd44. Nxd4e5\n",
607            "4...e65.Nc3 transposes to the Taimanov variation.\n",
608            "5. Nb5\n",
609            "plain prose"
610        );
611        let built = RawTreeBuilder::new(RepertoireSide::White)
612            .build(input)
613            .unwrap();
614
615        assert_eq!(
616            mainline_sans(&built.tree),
617            ["e4", "c5", "Nf3", "Nc6", "d4", "cxd4", "Nxd4", "e5", "Nb5"]
618        );
619        assert!(matches!(
620            &built.lines[1].classification,
621            ClassifiedRawLine::Comment {
622                reason: CommentReason::BacktrackedMove,
623                ..
624            }
625        ));
626        assert!(matches!(
627            &built.lines[3].classification,
628            ClassifiedRawLine::Comment {
629                reason: CommentReason::Prose,
630                ..
631            }
632        ));
633        let comments = built
634            .tree
635            .node(final_mainline_node(&built.tree))
636            .unwrap()
637            .comments();
638        assert_eq!(comments[0].as_str(), "plain prose");
639        let e5 = built.tree.traverse().nth(8).unwrap();
640        assert_eq!(
641            built.tree.node(e5).unwrap().comments()[0].as_str(),
642            "4... e6 5. Nc3 transposes to the Taimanov variation."
643        );
644    }
645
646    #[test]
647    fn retains_a_partial_numbered_line_as_one_normalized_comment() {
648        let input = "1. e4e52. Nf3Nc63. d4exd44. Nxd4Bc5\n4...Nf6 foo bar baz5.Nc3Bb4";
649        let built = RawTreeBuilder::new(RepertoireSide::White)
650            .build(input)
651            .unwrap();
652
653        assert!(matches!(
654            &built.lines[1].classification,
655            ClassifiedRawLine::Comment {
656                reason: CommentReason::BacktrackedMove,
657                ..
658            }
659        ));
660        let final_node = final_mainline_node(&built.tree);
661        assert_eq!(
662            built.tree.node(final_node).unwrap().comments()[0].as_str(),
663            "4... Nf6 foo bar baz 5. Nc3 Bb4"
664        );
665    }
666
667    #[test]
668    fn keeps_instructional_null_moves_out_of_the_tree() {
669        let input = concat!(
670            "1. e4c5\n",
671            "2. Nf3\n",
672            "2... --3. d4cxd44. Nxd4\n",
673            "2... e6",
674        );
675        let built = RawTreeBuilder::new(RepertoireSide::White)
676            .with_comment_variations(true)
677            .build(input)
678            .unwrap();
679
680        assert_eq!(mainline_sans(&built.tree), ["e4", "c5", "Nf3", "e6"]);
681        assert!(matches!(
682            &built.lines[2].classification,
683            ClassifiedRawLine::Comment {
684                text,
685                reason: CommentReason::InstructionalNullMove,
686                ..
687            } if text == "2... -- 3. d4 cxd4 4. Nxd4"
688        ));
689        let nf3 = built.tree.traverse().nth(3).unwrap();
690        assert!(built.tree.node(nf3).unwrap().children().len() == 1);
691    }
692
693    #[test]
694    fn depth_limit_counts_moves_by_the_repertoire_side() {
695        let input = "1. e4e52. Nf3Nc63. Bb5a64. Ba4Nf6";
696        let white = RawTreeBuilder::new(RepertoireSide::White)
697            .with_depth_limit(DepthLimit::RepertoireMoves(2))
698            .build(input)
699            .unwrap();
700        let black = RawTreeBuilder::new(RepertoireSide::Black)
701            .with_depth_limit(DepthLimit::RepertoireMoves(2))
702            .build(input)
703            .unwrap();
704
705        assert_eq!(mainline_sans(&white.tree), ["e4", "e5", "Nf3"]);
706        assert_eq!(mainline_sans(&black.tree), ["e4", "e5", "Nf3", "Nc6"]);
707    }
708
709    #[test]
710    fn zero_depth_keeps_only_root_comments_before_the_line() {
711        let input = "intro\n1. e4e5\ntrailing";
712        let built = RawTreeBuilder::new(RepertoireSide::White)
713            .with_depth_limit(DepthLimit::RepertoireMoves(0))
714            .build(input)
715            .unwrap();
716
717        assert_eq!(built.tree.len(), 1);
718        assert_eq!(
719            built.tree.node(built.tree.root()).unwrap().comments().len(),
720            1
721        );
722        assert_eq!(
723            built.tree.node(built.tree.root()).unwrap().comments()[0].as_str(),
724            "intro"
725        );
726    }
727
728    #[test]
729    fn comment_variations_are_explicitly_optional() {
730        let input = "1. e4e5\nWhite may also try 2.Nf3Nc6 here.\n2. Bc4Bc5";
731        let disabled = RawTreeBuilder::new(RepertoireSide::Black)
732            .build(input)
733            .unwrap();
734        let enabled = RawTreeBuilder::new(RepertoireSide::Black)
735            .with_comment_variations(true)
736            .build(input)
737            .unwrap();
738
739        let (disabled_e5, disabled_position) = node_after(&disabled.tree, &["e4", "e5"]);
740        let (enabled_e5, enabled_position) = node_after(&enabled.tree, &["e4", "e5"]);
741        assert_eq!(
742            child_sans(&disabled.tree, disabled_e5, &disabled_position),
743            ["Bc4"]
744        );
745        assert_eq!(
746            child_sans(&enabled.tree, enabled_e5, &enabled_position),
747            ["Bc4", "Nf3"]
748        );
749        let (nf3, nf3_position) = node_after(&enabled.tree, &["e4", "e5", "Nf3"]);
750        assert_eq!(child_sans(&enabled.tree, nf3, &nf3_position), ["Nc6"]);
751    }
752
753    #[test]
754    fn explicit_repertoire_move_rejects_comment_alternative() {
755        let input = "1. e4\n1...c52.Nf3 would be alpha beta.\n1... e5";
756        let built = RawTreeBuilder::new(RepertoireSide::Black)
757            .with_comment_variations(true)
758            .build(input)
759            .unwrap();
760
761        let (e4, position) = node_after(&built.tree, &["e4"]);
762        assert_eq!(child_sans(&built.tree, e4, &position), ["e5"]);
763    }
764
765    #[test]
766    fn bad_repertoire_annotation_rejects_the_whole_comment_line() {
767        let input = concat!(
768            "1. e4c62. d4d5\n",
769            "The line 3.e5Bf54.Nf3Nf6? is not our recommendation.\n",
770            "3. exd5"
771        );
772        let built = RawTreeBuilder::new(RepertoireSide::Black)
773            .with_comment_variations(true)
774            .build(input)
775            .unwrap();
776
777        let (d5, position) = node_after(&built.tree, &["e4", "c6", "d4", "d5"]);
778        assert_eq!(child_sans(&built.tree, d5, &position), ["exd5"]);
779    }
780
781    #[test]
782    fn bad_opponent_annotation_is_preserved_on_a_variation() {
783        let input = "1. e4\n1...c5? allows alpha beta.\n1... e5";
784        let built = RawTreeBuilder::new(RepertoireSide::White)
785            .with_comment_variations(true)
786            .build(input)
787            .unwrap();
788
789        let (e4, position) = node_after(&built.tree, &["e4"]);
790        assert_eq!(child_sans(&built.tree, e4, &position), ["e5", "c5"]);
791        let (c5, _) = node_after(&built.tree, &["e4", "c5"]);
792        assert!(
793            built
794                .tree
795                .node(c5)
796                .unwrap()
797                .annotations()
798                .contains(&Annotation::Mistake)
799        );
800    }
801
802    #[test]
803    fn final_comments_and_overlong_variations_stay_comment_only() {
804        let final_comment = RawTreeBuilder::new(RepertoireSide::White)
805            .with_comment_variations(true)
806            .build(concat!(
807                "1. d4d52. c4e6\n",
808                "This can continue with3.Nc3Nf64.Bg5, but it is just an example."
809            ))
810            .unwrap();
811        let (e6, e6_position) = node_after(&final_comment.tree, &["d4", "d5", "c4", "e6"]);
812        assert!(child_sans(&final_comment.tree, e6, &e6_position).is_empty());
813
814        let overlong = RawTreeBuilder::new(RepertoireSide::Black)
815            .with_comment_variations(true)
816            .build(concat!(
817                "1. e4e52. d4\n",
818                "This can transpose after2.Nf3Nc63.d4exd4.\n",
819                "2... exd43. c3"
820            ))
821            .unwrap();
822        let (e5, e5_position) = node_after(&overlong.tree, &["e4", "e5"]);
823        assert_eq!(child_sans(&overlong.tree, e5, &e5_position), ["d4"]);
824    }
825}