fea-rs-ast 0.1.4

fontTools-like AST wrapper around fea-rs parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
use std::ops::Range;

use fea_rs::{
    Kind,
    typed::{AstNode as _, GlyphOrClass},
};

use crate::{
    Anchor, AsFea, GlyphContainer, MarkClass, PotentiallyContextualStatement, ValueRecord,
    from_anchor,
};

/// A single positioning rule (GPOS type 1)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SinglePosStatement {
    /// The glyphs and their associated value records to be positioned
    pub pos: Vec<(GlyphContainer, Option<ValueRecord>)>,
    /// The prefix (backtrack) glyphs
    pub prefix: Vec<GlyphContainer>,
    /// The suffix (lookahead) glyphs
    pub suffix: Vec<GlyphContainer>,
    /// Whether to force this statement to be treated as a contextual positioning rule
    pub force_chain: bool,
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
}

impl SinglePosStatement {
    /// Create a new single positioning statement.
    pub fn new(
        prefix: Vec<GlyphContainer>,
        suffix: Vec<GlyphContainer>,
        pos: Vec<(GlyphContainer, Option<ValueRecord>)>,
        force_chain: bool,
        location: Range<usize>,
    ) -> Self {
        Self {
            prefix,
            suffix,
            pos,
            force_chain,
            location,
        }
    }
}

impl PotentiallyContextualStatement for SinglePosStatement {
    fn prefix(&self) -> &[GlyphContainer] {
        &self.prefix
    }
    fn suffix(&self) -> &[GlyphContainer] {
        &self.suffix
    }
    fn force_chain(&self) -> bool {
        self.force_chain
    }

    fn format_begin(&self, _indent: &str) -> String {
        "pos ".to_string()
    }

    fn format_contextual_parts(&self, indent: &str) -> Vec<String> {
        self.pos
            .iter()
            .map(|(p, vr)| {
                format!(
                    "{}'{}",
                    p.as_fea(""),
                    vr.as_ref()
                        .map(|v| format!(" {}", v.as_fea(indent)))
                        .unwrap_or_default()
                )
            })
            .collect()
    }

    fn format_noncontextual_parts(&self, indent: &str) -> Vec<String> {
        self.pos
            .iter()
            .map(|(p, vr)| {
                format!(
                    "{} {}",
                    p.as_fea(""),
                    vr.as_ref()
                        .map(|v| v.as_fea(indent).to_string())
                        .unwrap_or("<NULL>".to_string())
                )
            })
            .collect()
    }
}

impl From<fea_rs::typed::Gpos1> for SinglePosStatement {
    fn from(val: fea_rs::typed::Gpos1) -> Self {
        let target = val.iter().find_map(GlyphOrClass::cast).unwrap();
        let value_record = val
            .iter()
            .find_map(fea_rs::typed::ValueRecord::cast)
            .unwrap();
        Self::new(
            vec![],
            vec![],
            vec![(target.into(), Some(value_record.into()))],
            false,
            val.node().range(),
        )
    }
}

/// A pair positioning rule (GPOS type 2)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairPosStatement {
    /// The first glyph or class in the pair
    pub glyphs_1: GlyphContainer,
    /// The second glyph or class in the pair
    pub glyphs_2: GlyphContainer,
    /// The value record for the first glyph
    pub value_record_1: ValueRecord,
    /// The value record for the second glyph (if any)
    pub value_record_2: Option<ValueRecord>,
    /// Whether this is an enumerated pair positioning rule
    pub enumerated: bool,
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
}

impl PairPosStatement {
    /// Create a new pair positioning statement.
    pub fn new(
        glyphs_1: GlyphContainer,
        glyphs_2: GlyphContainer,
        value_record_1: ValueRecord,
        value_record_2: Option<ValueRecord>,
        enumerated: bool,
        location: Range<usize>,
    ) -> Self {
        Self {
            glyphs_1,
            glyphs_2,
            value_record_1,
            value_record_2,
            enumerated,
            location,
        }
    }
}

impl AsFea for PairPosStatement {
    fn as_fea(&self, indent: &str) -> String {
        let mut res = String::new();
        if self.enumerated {
            res.push_str("enum ");
        }
        res.push_str("pos ");
        if let Some(vr2) = &self.value_record_2 {
            // glyphs1 valuerecord1 glyphs2 valuerecord2
            res.push_str(&format!(
                "{} {} {} {}",
                self.glyphs_1.as_fea(""),
                self.value_record_1.as_fea(indent),
                self.glyphs_2.as_fea(""),
                vr2.as_fea(indent)
            ));
        } else {
            // glyphs1 glyphs2 valuerecord1
            res.push_str(&format!(
                "{} {} {}",
                self.glyphs_1.as_fea(""),
                self.glyphs_2.as_fea(""),
                self.value_record_1.as_fea(indent),
            ));
        }
        res.push(';');
        res
    }
}

impl From<fea_rs::typed::Gpos2> for PairPosStatement {
    fn from(val: fea_rs::typed::Gpos2) -> Self {
        let enumerated = val.iter().any(|t| t.kind() == Kind::EnumKw);
        let glyphs_1 = val.iter().find_map(GlyphOrClass::cast).unwrap().into();
        let glyphs_2 = val
            .iter()
            .filter_map(GlyphOrClass::cast)
            .nth(1)
            .unwrap()
            .into();
        let value_record_1 = val
            .iter()
            .find_map(fea_rs::typed::ValueRecord::cast)
            .unwrap();
        let value_record_2 = val
            .iter()
            .filter_map(fea_rs::typed::ValueRecord::cast)
            .nth(1)
            .map(|vr| vr.into());
        Self::new(
            glyphs_1,
            glyphs_2,
            value_record_1.into(),
            value_record_2,
            enumerated,
            val.node().range(),
        )
    }
}

/// A cursive positioning rule (GPOS type 3)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CursivePosStatement {
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
    /// The glyph or class this rule applies to
    pub glyphclass: GlyphContainer,
    /// The entry anchor point
    pub entry: Option<Anchor>,
    /// The exit anchor point
    pub exit: Option<Anchor>,
}

impl CursivePosStatement {
    /// Create a new cursive positioning statement.
    pub fn new(
        glyphclass: GlyphContainer,
        entry: Option<Anchor>,
        exit: Option<Anchor>,
        location: Range<usize>,
    ) -> Self {
        Self {
            glyphclass,
            entry,
            exit,
            location,
        }
    }
}

impl AsFea for CursivePosStatement {
    fn as_fea(&self, indent: &str) -> String {
        format!(
            "pos cursive {} {} {};",
            self.glyphclass.as_fea(""),
            self.entry
                .as_ref()
                .map(|e| e.as_fea(indent))
                .unwrap_or_else(|| "<anchor NULL>".to_string()),
            self.exit
                .as_ref()
                .map(|e| e.as_fea(indent))
                .unwrap_or_else(|| "<anchor NULL>".to_string()),
        )
    }
}
impl From<fea_rs::typed::Gpos3> for CursivePosStatement {
    fn from(val: fea_rs::typed::Gpos3) -> Self {
        let glyphclass = val.iter().find_map(GlyphOrClass::cast).unwrap().into();
        let entry = val.iter().find_map(fea_rs::typed::Anchor::cast).unwrap();
        let exit = val
            .iter()
            .filter_map(fea_rs::typed::Anchor::cast)
            .nth(1)
            .unwrap();
        Self::new(
            glyphclass,
            from_anchor(entry),
            from_anchor(exit),
            val.node().range(),
        )
    }
}

/// A mark-to-base positioning rule (GPOS type 4)
///
/// Example: `pos base a <anchor 625 1800> mark @TOP_MARKS;`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkBasePosStatement {
    /// The base glyph or class
    pub base: GlyphContainer,
    /// The list of (Anchor, MarkClass) tuples for the marks
    pub marks: Vec<(Anchor, MarkClass)>,
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
}

impl MarkBasePosStatement {
    /// Create a new mark-to-base positioning statement.
    pub fn new(
        base: GlyphContainer,
        marks: Vec<(Anchor, MarkClass)>,
        location: Range<usize>,
    ) -> Self {
        Self {
            base,
            marks,
            location,
        }
    }
}

impl AsFea for MarkBasePosStatement {
    fn as_fea(&self, indent: &str) -> String {
        let mut res = format!("pos base {}", self.base.as_fea(""));
        for (anchor, mark_class) in &self.marks {
            res.push_str(&format!(
                "\n{}    {} mark @{}",
                indent,
                anchor.as_fea(""),
                mark_class.name
            ));
        }
        res.push(';');
        res
    }
}

impl From<fea_rs::typed::Gpos4> for MarkBasePosStatement {
    fn from(val: fea_rs::typed::Gpos4) -> Self {
        // Extract base glyph (it's after "pos" keyword and "base" keyword)
        let base: GlyphContainer = val
            .iter()
            .filter(|t| t.kind() != Kind::Whitespace)
            .nth(2) // Skip "pos" and "base" keywords
            .and_then(GlyphOrClass::cast)
            .unwrap()
            .into();

        // Extract all AnchorMark nodes (after the base glyph)
        let marks: Vec<(Anchor, MarkClass)> = val
            .iter()
            .filter_map(fea_rs::typed::AnchorMark::cast)
            .map(|anchor_mark| {
                // Get the anchor from the AnchorMark node
                let anchor_node = anchor_mark
                    .iter()
                    .find_map(fea_rs::typed::Anchor::cast)
                    .unwrap();
                let anchor = from_anchor(anchor_node).unwrap();

                // Get the mark class name (it's a @GlyphClass token)
                let mark_class_node = anchor_mark
                    .iter()
                    .find_map(fea_rs::typed::GlyphClassName::cast)
                    .unwrap();
                let mark_class_name = mark_class_node.text().trim_start_matches('@');
                let mark_class = MarkClass::new(mark_class_name);

                (anchor, mark_class)
            })
            .collect();

        MarkBasePosStatement::new(base, marks, val.range())
    }
}

/// A mark-to-ligature positioning rule (GPOS type 5)
///
/// The `marks` field is a list of lists: each element represents a component glyph,
/// and is made up of a list of (Anchor, MarkClass) tuples for that component.
///
/// Example: `pos ligature lam_meem_jeem <anchor 625 1800> mark @TOP_MARKS ligComponent <anchor 376 -378> mark @BOTTOM_MARKS;`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkLigPosStatement {
    /// The ligature glyph or class
    pub ligatures: GlyphContainer,
    /// The list of lists of (Anchor, MarkClass) tuples for each component
    pub marks: Vec<Vec<(Anchor, MarkClass)>>,
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
}

impl MarkLigPosStatement {
    /// Create a new mark-to-ligature positioning statement.
    pub fn new(
        ligatures: GlyphContainer,
        marks: Vec<Vec<(Anchor, MarkClass)>>,
        location: Range<usize>,
    ) -> Self {
        Self {
            ligatures,
            marks,
            location,
        }
    }
}

impl AsFea for MarkLigPosStatement {
    fn as_fea(&self, indent: &str) -> String {
        let mut res = format!("pos ligature {}", self.ligatures.as_fea(""));

        // Format each ligature component
        let mut ligs = Vec::new();
        for component in &self.marks {
            if component.is_empty() {
                // Empty component gets NULL anchor
                ligs.push(format!("\n{}    <anchor NULL>", indent));
            } else {
                let mut temp = String::new();
                for (anchor, mark_class) in component {
                    temp.push_str(&format!(
                        "\n{}    {} mark @{}",
                        indent,
                        anchor.as_fea(""),
                        mark_class.name
                    ));
                }
                ligs.push(temp);
            }
        }

        // Join components with "ligComponent" keyword (but not before first)
        res.push_str(&ligs.join(&format!("\n{}    ligComponent", indent)));
        res.push(';');
        res
    }
}

impl From<fea_rs::typed::Gpos5> for MarkLigPosStatement {
    fn from(val: fea_rs::typed::Gpos5) -> Self {
        // Extract ligature glyph (it's after "pos" keyword and "ligature" keyword)
        let ligatures: GlyphContainer = val
            .iter()
            .filter(|t| t.kind() != Kind::Whitespace)
            .nth(2) // Skip "pos" and "ligature" keywords
            .and_then(GlyphOrClass::cast)
            .unwrap()
            .into();

        // Extract all LigatureComponent nodes
        let marks: Vec<Vec<(Anchor, MarkClass)>> = val
            .iter()
            .filter_map(fea_rs::typed::LigatureComponent::cast)
            .map(|lig_component| {
                // Extract all AnchorMark nodes within this component
                lig_component
                    .iter()
                    .filter_map(fea_rs::typed::AnchorMark::cast)
                    .flat_map(|anchor_mark| {
                        // Get the anchor from the AnchorMark node
                        let anchor_node = anchor_mark
                            .iter()
                            .find_map(fea_rs::typed::Anchor::cast)
                            .unwrap();
                        let anchor = from_anchor(anchor_node)?;

                        // Get the mark class name (it's a @GlyphClass token)
                        let mark_class_node = anchor_mark
                            .iter()
                            .find_map(fea_rs::typed::GlyphClassName::cast)?;
                        let mark_class_name = mark_class_node.text().trim_start_matches('@');
                        let mark_class = MarkClass::new(mark_class_name);

                        Some((anchor, mark_class))
                    })
                    .collect()
            })
            .collect();

        MarkLigPosStatement::new(ligatures, marks, val.range())
    }
}

/// A mark-to-mark positioning rule (GPOS type 6)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkMarkPosStatement {
    /// The base glyph or class to which the marks will be attached
    pub base_marks: GlyphContainer,
    /// The list of (Anchor, MarkClass) tuples for the marks
    pub marks: Vec<(Anchor, MarkClass)>,
    /// The location of the statement in the source feature file
    pub location: Range<usize>,
}

impl MarkMarkPosStatement {
    /// Create a new mark-to-mark positioning statement.
    pub fn new(
        base_marks: GlyphContainer,
        marks: Vec<(Anchor, MarkClass)>,
        location: Range<usize>,
    ) -> Self {
        Self {
            base_marks,
            marks,
            location,
        }
    }
}

impl AsFea for MarkMarkPosStatement {
    fn as_fea(&self, indent: &str) -> String {
        let mut res = format!("pos mark {}", self.base_marks.as_fea(""));
        for (anchor, mark_class) in &self.marks {
            res.push_str(&format!(
                "\n{}    {} mark @{}",
                indent,
                anchor.as_fea(""),
                mark_class.name
            ));
        }
        res.push(';');
        res
    }
}

impl From<fea_rs::typed::Gpos6> for MarkMarkPosStatement {
    fn from(val: fea_rs::typed::Gpos6) -> Self {
        // Extract base mark glyph (it's after "pos" keyword and "mark" keyword)
        let base_marks: GlyphContainer = val
            .iter()
            .filter(|t| t.kind() != Kind::Whitespace)
            .nth(2) // Skip "pos" and "mark" keywords
            .and_then(GlyphOrClass::cast)
            .unwrap()
            .into();

        // Extract all AnchorMark nodes (after the base mark glyph)
        let marks: Vec<(Anchor, MarkClass)> = val
            .iter()
            .filter_map(fea_rs::typed::AnchorMark::cast)
            .map(|anchor_mark| {
                // Get the anchor from the AnchorMark node
                let anchor_node = anchor_mark
                    .iter()
                    .find_map(fea_rs::typed::Anchor::cast)
                    .unwrap();
                let anchor = from_anchor(anchor_node).unwrap();

                // Get the mark class name (it's a @GlyphClass token)
                let mark_class_node = anchor_mark
                    .iter()
                    .find_map(fea_rs::typed::GlyphClassName::cast)
                    .unwrap();
                let mark_class_name = mark_class_node.text().trim_start_matches('@');
                let mark_class = MarkClass::new(mark_class_name);

                (anchor, mark_class)
            })
            .collect();

        MarkMarkPosStatement::new(base_marks, marks, val.node().range())
    }
}

#[cfg(test)]
mod tests {
    use crate::GlyphName;

    use super::*;

    #[test]
    fn test_generate_gpos1() {
        let gpos1 = SinglePosStatement::new(
            vec![GlyphContainer::GlyphName(GlyphName::new("x"))],
            vec![],
            vec![(
                GlyphContainer::GlyphName(GlyphName::new("A")),
                Some(ValueRecord {
                    x_advance: Some(50.into()),
                    y_advance: None,
                    x_placement: None,
                    y_placement: None,
                    x_placement_device: None,
                    y_placement_device: None,
                    x_advance_device: None,
                    y_advance_device: None,
                    vertical: false,
                    location: 0..0,
                    name: None,
                }),
            )],
            false,
            0..10,
        );
        let fea_str = gpos1.as_fea("");
        assert_eq!(fea_str, "pos x A' 50;");
    }

    #[test]
    fn test_roundtrip_gpos1() {
        const FEA: &str = "feature foo { pos A 50; } foo;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gpos1 = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::Feature::cast)
            .and_then(|feature| {
                feature
                    .node()
                    .iter_children()
                    .find_map(fea_rs::typed::Gpos1::cast)
            })
            .unwrap();
        let gpos1_stmt: SinglePosStatement = gpos1.into();
        let fea_str_roundtrip = gpos1_stmt.as_fea("");
        assert_eq!(fea_str_roundtrip, "pos A 50;");
    }

    #[test]
    fn test_generate_gpos2() {
        let gpos2 = PairPosStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("A")),
            GlyphContainer::GlyphName(GlyphName::new("B")),
            ValueRecord {
                x_advance: Some(50.into()),
                y_advance: None,
                x_placement: None,
                y_placement: None,
                x_placement_device: None,
                y_placement_device: None,
                x_advance_device: None,
                y_advance_device: None,
                vertical: false,
                location: 0..0,
                name: None,
            },
            Some(ValueRecord {
                x_advance: Some(30.into()),
                y_advance: None,
                x_placement: None,
                y_placement: None,
                x_placement_device: None,
                y_placement_device: None,
                x_advance_device: None,
                y_advance_device: None,
                vertical: false,
                location: 0..0,
                name: None,
            }),
            false,
            0..10,
        );
        let fea_str = gpos2.as_fea("");
        assert_eq!(fea_str, "pos A 50 B 30;");
    }

    #[test]
    fn test_generate_gpos3() {
        let gpos3 = CursivePosStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("A")),
            Some(Anchor::new_simple(100, 200, 0..0)),
            Some(Anchor::new_simple(150, 250, 0..0)),
            0..10,
        );
        let fea_str = gpos3.as_fea("");
        assert_eq!(fea_str, "pos cursive A <anchor 100 200> <anchor 150 250>;");

        // Try with some NULL anchors
        let gpos3_null = CursivePosStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("A")),
            None,
            Some(Anchor::new_simple(150, 250, 0..10)),
            0..10,
        );
        let fea_str_null = gpos3_null.as_fea("");
        assert_eq!(
            fea_str_null,
            "pos cursive A <anchor NULL> <anchor 150 250>;"
        );
    }

    #[test]
    fn test_roundtrip_gpos3() {
        const FEA: &str = "feature foo { pos cursive A <anchor 100 200> <anchor 150 250>; } foo;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gpos3 = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::Feature::cast)
            .and_then(|feature| {
                feature
                    .node()
                    .iter_children()
                    .find_map(fea_rs::typed::Gpos3::cast)
            })
            .unwrap();
        let gpos3_stmt: CursivePosStatement = gpos3.into();
        let fea_str_roundtrip = gpos3_stmt.as_fea("");
        assert_eq!(
            fea_str_roundtrip,
            "pos cursive A <anchor 100 200> <anchor 150 250>;"
        );
    }

    #[test]
    fn test_roundtrip_gpos4() {
        const FEA: &str = "feature mark { pos base a <anchor 625 1800> mark @TOP_MARKS; } mark;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gpos4 = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::Feature::cast)
            .and_then(|feature| {
                feature
                    .node()
                    .iter_children()
                    .find_map(fea_rs::typed::Gpos4::cast)
            })
            .unwrap();
        let stmt = MarkBasePosStatement::from(gpos4);
        assert_eq!(stmt.base.as_fea(""), "a");
        assert_eq!(stmt.marks.len(), 1);
        assert_eq!(stmt.marks[0].1.name, "TOP_MARKS");
        assert_eq!(
            stmt.as_fea(""),
            "pos base a\n    <anchor 625 1800> mark @TOP_MARKS;"
        );
    }

    #[test]
    fn test_generation_gpos4() {
        let stmt = MarkBasePosStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("a")),
            vec![
                (
                    Anchor::new_simple(300, 450, 0..0),
                    MarkClass::new("TOP_MARKS"),
                ),
                (
                    Anchor::new_simple(300, -100, 0..0),
                    MarkClass::new("BOTTOM_MARKS"),
                ),
            ],
            0..0,
        );
        assert_eq!(
            stmt.as_fea(""),
            "pos base a\n    <anchor 300 450> mark @TOP_MARKS\n    <anchor 300 -100> mark @BOTTOM_MARKS;"
        );
    }

    #[test]
    fn test_roundtrip_gpos5() {
        const FEA: &str = "feature test { pos ligature lam_meem_jeem <anchor 625 1800> mark @TOP_MARKS ligComponent <anchor 376 -378> mark @BOTTOM_MARKS; } test;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gpos5 = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::Feature::cast)
            .and_then(|feature| {
                feature
                    .node()
                    .iter_children()
                    .find_map(fea_rs::typed::Gpos5::cast)
            })
            .unwrap();
        let gpos5_stmt: MarkLigPosStatement = gpos5.into();
        let fea_str_roundtrip = gpos5_stmt.as_fea("");
        assert_eq!(
            fea_str_roundtrip,
            "pos ligature lam_meem_jeem\n    <anchor 625 1800> mark @TOP_MARKS\n    ligComponent\n    <anchor 376 -378> mark @BOTTOM_MARKS;"
        );
    }

    #[test]
    fn test_generate_gpos5() {
        let stmt = MarkLigPosStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("lam_meem_jeem")),
            vec![
                vec![(
                    Anchor::new_simple(625, 1800, 0..0),
                    MarkClass::new("TOP_MARKS"),
                )],
                vec![(
                    Anchor::new_simple(376, -378, 0..0),
                    MarkClass::new("BOTTOM_MARKS"),
                )],
                vec![], // Empty component (NULL anchor)
            ],
            0..0,
        );
        assert_eq!(
            stmt.as_fea(""),
            "pos ligature lam_meem_jeem\n    <anchor 625 1800> mark @TOP_MARKS\n    ligComponent\n    <anchor 376 -378> mark @BOTTOM_MARKS\n    ligComponent\n    <anchor NULL>;"
        );
    }
}