fea-rs-ast 0.2.0

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
use std::ops::Range;

use fea_rs::typed::AstNode as _;

use crate::{AsFea, Comment, GlyphContainer, Statement};

/// A ``GDEF`` table ``Attach`` statement
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachStatement {
    /// The glyphs to which the attachment points apply
    pub glyphs: GlyphContainer,
    /// The contour point indices
    pub contour_points: Vec<usize>,
    /// The location of the statement in the source
    #[cfg_attr(feature = "serde", serde(default = "crate::default_range", skip_serializing_if = "crate::is_default_range"))]
    pub location: Range<usize>,
}
impl AttachStatement {
    /// Creates a new `Attach` statement.
    pub fn new(glyphs: GlyphContainer, contour_points: Vec<usize>, location: Range<usize>) -> Self {
        Self {
            glyphs,
            contour_points,
            location,
        }
    }
}
impl AsFea for AttachStatement {
    fn as_fea(&self, _indent: &str) -> String {
        let points = self
            .contour_points
            .iter()
            .map(|p| p.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        format!("Attach {} {};", self.glyphs.as_fea(""), points)
    }
}
impl From<fea_rs::typed::GdefAttach> for AttachStatement {
    fn from(val: fea_rs::typed::GdefAttach) -> Self {
        let glyphs = val
            .iter()
            .find_map(fea_rs::typed::GlyphOrClass::cast)
            .unwrap();
        let contour_points: Vec<usize> = val
            .iter()
            .filter(|t| t.kind() == fea_rs::Kind::Number)
            .map(|t| t.as_token().unwrap().text.parse().unwrap())
            .collect();
        AttachStatement::new(glyphs.into(), contour_points, val.node().range())
    }
}

/// A ``GDEF`` table ``GlyphClassDef`` statement
///
/// Example: ``GlyphClassDef [a b c], [f_f_i f_f_l], [acute grave], [n.sc t.sc];``
/// Or with named classes: ``GlyphClassDef @BASE, @LIGATURES, @MARKS, @COMPONENT;``
///
/// The four parameters represent base glyphs, ligature glyphs, mark glyphs,
/// and component glyphs respectively. Any parameter can be None.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlyphClassDefStatement {
    /// The base glyphs class (or None)
    pub base_glyphs: Option<GlyphContainer>,
    /// The ligature glyphs class (or None)
    pub ligature_glyphs: Option<GlyphContainer>,
    /// The mark glyphs class (or None)
    pub mark_glyphs: Option<GlyphContainer>,
    /// The component glyphs class (or None)
    pub component_glyphs: Option<GlyphContainer>,
    /// The location of the statement in the source
    #[cfg_attr(feature = "serde", serde(default = "crate::default_range", skip_serializing_if = "crate::is_default_range"))]
    pub location: Range<usize>,
}

impl GlyphClassDefStatement {
    /// Creates a new `GlyphClassDef` statement.
    pub fn new(
        base_glyphs: Option<GlyphContainer>,
        ligature_glyphs: Option<GlyphContainer>,
        mark_glyphs: Option<GlyphContainer>,
        component_glyphs: Option<GlyphContainer>,
        location: Range<usize>,
    ) -> Self {
        Self {
            base_glyphs,
            ligature_glyphs,
            mark_glyphs,
            component_glyphs,
            location,
        }
    }
}

impl AsFea for GlyphClassDefStatement {
    fn as_fea(&self, _indent: &str) -> String {
        let base = self
            .base_glyphs
            .as_ref()
            .map(|g| g.as_fea(""))
            .unwrap_or_default();
        let liga = self
            .ligature_glyphs
            .as_ref()
            .map(|g| g.as_fea(""))
            .unwrap_or_default();
        let mark = self
            .mark_glyphs
            .as_ref()
            .map(|g| g.as_fea(""))
            .unwrap_or_default();
        let comp = self
            .component_glyphs
            .as_ref()
            .map(|g| g.as_fea(""))
            .unwrap_or_default();
        format!("GlyphClassDef {}, {}, {}, {};", base, liga, mark, comp)
    }
}

impl From<fea_rs::typed::GdefClassDef> for GlyphClassDefStatement {
    fn from(val: fea_rs::typed::GdefClassDef) -> Self {
        // Extract the 4 glyph class entries in order: base, ligature, mark, component
        let mut entries = val
            .iter()
            .filter(|t| t.kind() == fea_rs::Kind::GdefClassDefEntryNode)
            .filter_map(fea_rs::typed::GdefClassDefEntry::cast);

        // Helper to extract GlyphContainer from an entry (handles both literal classes and named class references)
        let extract_container =
            |entry: fea_rs::typed::GdefClassDefEntry| -> Option<GlyphContainer> {
                entry
                    .iter()
                    .find_map(fea_rs::typed::GlyphOrClass::cast)
                    .map(Into::into)
            };

        let base_glyphs = entries.next().and_then(extract_container);
        let ligature_glyphs = entries.next().and_then(extract_container);
        let mark_glyphs = entries.next().and_then(extract_container);
        let component_glyphs = entries.next().and_then(extract_container);

        GlyphClassDefStatement::new(
            base_glyphs,
            ligature_glyphs,
            mark_glyphs,
            component_glyphs,
            val.range(),
        )
    }
}

/// A ``GDEF`` table ``LigatureCaretByIndex`` statement
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LigatureCaretByIndexStatement {
    /// The glyphs to which the caret indices apply
    pub glyphs: GlyphContainer,
    /// The caret indices
    pub carets: Vec<usize>,
    /// The location of the statement in the source
    #[cfg_attr(feature = "serde", serde(default = "crate::default_range", skip_serializing_if = "crate::is_default_range"))]
    pub location: Range<usize>,
}

impl LigatureCaretByIndexStatement {
    /// Creates a new `LigatureCaretByIndex` statement.
    pub fn new(glyphs: GlyphContainer, carets: Vec<usize>, location: Range<usize>) -> Self {
        Self {
            glyphs,
            carets,
            location,
        }
    }
}

impl AsFea for LigatureCaretByIndexStatement {
    fn as_fea(&self, _indent: &str) -> String {
        let carets = self
            .carets
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        format!(
            "LigatureCaretByIndex {} {};",
            self.glyphs.as_fea(""),
            carets
        )
    }
}

impl From<fea_rs::typed::GdefLigatureCaret> for LigatureCaretByIndexStatement {
    fn from(val: fea_rs::typed::GdefLigatureCaret) -> Self {
        let glyphs = val
            .iter()
            .find_map(fea_rs::typed::GlyphOrClass::cast)
            .unwrap();

        // Extract the caret indices as unsigned integers
        let carets: Vec<usize> = val
            .iter()
            .filter(|t| t.kind() == fea_rs::Kind::Number)
            .map(|t| t.as_token().unwrap().text.parse().unwrap())
            .collect();

        LigatureCaretByIndexStatement::new(glyphs.into(), carets, val.node().range())
    }
}

/// A ``GDEF`` table ``LigatureCaretByPos`` statement
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LigatureCaretByPosStatement {
    /// The glyphs to which the caret positions apply
    pub glyphs: GlyphContainer,
    /// The caret positions
    pub carets: Vec<i16>,
    /// The location of the statement in the source
    #[cfg_attr(feature = "serde", serde(default = "crate::default_range", skip_serializing_if = "crate::is_default_range"))]
    pub location: Range<usize>,
}

impl LigatureCaretByPosStatement {
    /// Creates a new `LigatureCaretByPos` statement.
    pub fn new(glyphs: GlyphContainer, carets: Vec<i16>, location: Range<usize>) -> Self {
        Self {
            glyphs,
            carets,
            location,
        }
    }
}

impl AsFea for LigatureCaretByPosStatement {
    fn as_fea(&self, _indent: &str) -> String {
        let carets = self
            .carets
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        format!("LigatureCaretByPos {} {};", self.glyphs.as_fea(""), carets)
    }
}

impl From<fea_rs::typed::GdefLigatureCaret> for LigatureCaretByPosStatement {
    fn from(val: fea_rs::typed::GdefLigatureCaret) -> Self {
        let glyphs = val
            .iter()
            .find_map(fea_rs::typed::GlyphOrClass::cast)
            .unwrap();

        // Extract the caret positions as signed integers
        let carets: Vec<i16> = val
            .iter()
            .filter(|t| t.kind() == fea_rs::Kind::Number)
            .map(|t| t.as_token().unwrap().text.parse().unwrap())
            .collect();

        LigatureCaretByPosStatement::new(glyphs.into(), carets, val.node().range())
    }
}

/// A statement in a `table GDEF { ... } GDEF` block
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GdefStatement {
    /// A ``GDEF`` table ``Attach`` statement
    Attach(AttachStatement),
    /// A ``GDEF`` table ``GlyphClassDef`` statement
    GlyphClassDef(GlyphClassDefStatement),
    /// A ``GDEF`` table ``LigatureCaretByIndex`` statement
    LigatureCaretByIndex(LigatureCaretByIndexStatement),
    /// A ``GDEF`` table ``LigatureCaretByPos`` statement
    LigatureCaretByPos(LigatureCaretByPosStatement),
    /// A comment
    Comment(Comment),
    // Include(IncludeStatement),
}
impl AsFea for GdefStatement {
    fn as_fea(&self, indent: &str) -> String {
        match self {
            GdefStatement::Attach(stmt) => stmt.as_fea(indent),
            GdefStatement::GlyphClassDef(stmt) => stmt.as_fea(indent),
            GdefStatement::LigatureCaretByIndex(stmt) => stmt.as_fea(indent),
            GdefStatement::LigatureCaretByPos(stmt) => stmt.as_fea(indent),
            GdefStatement::Comment(cmt) => cmt.as_fea(indent),
            // GdefStatement::Include(stmt) => stmt.as_fea(indent),
        }
    }
}
impl From<GdefStatement> for Statement {
    fn from(val: GdefStatement) -> Self {
        match val {
            GdefStatement::Attach(stmt) => Statement::GdefAttach(stmt),
            GdefStatement::GlyphClassDef(stmt) => Statement::GdefClassDef(stmt),
            GdefStatement::LigatureCaretByIndex(stmt) => Statement::GdefLigatureCaretByIndex(stmt),
            GdefStatement::LigatureCaretByPos(stmt) => Statement::GdefLigatureCaretByPos(stmt),
            GdefStatement::Comment(cmt) => Statement::Comment(cmt),
            // GdefStatement::Include(stmt) => Statement::Include(stmt),
        }
    }
}
impl TryFrom<Statement> for GdefStatement {
    type Error = crate::Error;
    fn try_from(value: Statement) -> Result<Self, Self::Error> {
        match value {
            Statement::GdefAttach(stmt) => Ok(GdefStatement::Attach(stmt)),
            Statement::GdefClassDef(stmt) => Ok(GdefStatement::GlyphClassDef(stmt)),
            Statement::GdefLigatureCaretByIndex(stmt) => {
                Ok(GdefStatement::LigatureCaretByIndex(stmt))
            }
            Statement::GdefLigatureCaretByPos(stmt) => Ok(GdefStatement::LigatureCaretByPos(stmt)),
            Statement::Comment(cmt) => Ok(GdefStatement::Comment(cmt)),
            // Statement::Include(stmt) => Ok(GdefStatement::Include(stmt)),
            _ => Err(crate::Error::CannotConvert),
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{GlyphClass, GlyphName};

    #[test]
    fn test_roundtrip_ligature_caret_by_index() {
        const FEA: &str = "table GDEF { LigatureCaretByIndex f_f_i 2 3; } GDEF;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gdef_table = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GdefTable::cast)
            .unwrap();
        let ligature_caret = gdef_table
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GdefLigatureCaret::cast)
            .unwrap();
        let stmt = LigatureCaretByIndexStatement::from(ligature_caret);
        assert_eq!(stmt.glyphs.as_fea(""), "f_f_i");
        assert_eq!(stmt.carets, vec![2, 3]);
        assert_eq!(stmt.as_fea(""), "LigatureCaretByIndex f_f_i 2 3;");
    }

    #[test]
    fn test_roundtrip_ligature_caret_by_pos() {
        const FEA: &str = "table GDEF { LigatureCaretByPos f_f_i 200 400; } GDEF;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gdef_table = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GdefTable::cast)
            .unwrap();
        let ligature_caret = gdef_table
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GdefLigatureCaret::cast)
            .unwrap();
        let stmt = LigatureCaretByPosStatement::from(ligature_caret);
        assert_eq!(stmt.glyphs.as_fea(""), "f_f_i");
        assert_eq!(stmt.carets, vec![200, 400]);
        assert_eq!(stmt.as_fea(""), "LigatureCaretByPos f_f_i 200 400;");
    }

    #[test]
    fn test_generate_ligature_caret_by_index() {
        let stmt = LigatureCaretByIndexStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("f_f_i")),
            vec![2, 3],
            0..0,
        );
        assert_eq!(stmt.as_fea(""), "LigatureCaretByIndex f_f_i 2 3;");
    }

    #[test]
    fn test_generate_ligature_caret_by_pos() {
        let stmt = LigatureCaretByPosStatement::new(
            GlyphContainer::GlyphClass(GlyphClass::new(
                vec![
                    GlyphContainer::GlyphName(GlyphName::new("f_f_i")),
                    GlyphContainer::GlyphName(GlyphName::new("f_f_l")),
                ],
                0..0,
            )),
            vec![200, 400],
            0..0,
        );
        assert_eq!(stmt.as_fea(""), "LigatureCaretByPos [f_f_i f_f_l] 200 400;");
    }

    #[test]
    fn test_roundtrip_attach() {
        const FEA: &str = "table GDEF { Attach [a e o] 1 2; } GDEF;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gdef_table = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GdefTable::cast)
            .unwrap();
        let attach = gdef_table
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GdefAttach::cast)
            .unwrap();
        let stmt = AttachStatement::from(attach);
        assert_eq!(stmt.as_fea(""), "Attach [a e o] 1 2;");
    }

    #[test]
    fn test_generation_attach() {
        let stmt = AttachStatement::new(
            GlyphContainer::GlyphName(GlyphName::new("acutecomb")),
            vec![3, 5, 7],
            0..0,
        );
        assert_eq!(stmt.as_fea(""), "Attach acutecomb 3 5 7;");
    }

    #[test]
    fn test_roundtrip_glyphclassdef() {
        const FEA: &str = "table GDEF { GlyphClassDef [a b c], [f_f_i], [acute grave], ; } GDEF;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gdef_table = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GdefTable::cast)
            .unwrap();
        let class_def = gdef_table
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GdefClassDef::cast)
            .unwrap();

        let stmt = GlyphClassDefStatement::from(class_def);
        assert!(stmt.base_glyphs.is_some());
        assert!(stmt.ligature_glyphs.is_some());
        assert!(stmt.mark_glyphs.is_some());
        assert!(stmt.component_glyphs.is_none());
        assert_eq!(
            stmt.as_fea(""),
            "GlyphClassDef [a b c], [f_f_i], [acute grave], ;"
        );
    }

    #[test]
    fn test_generation_glyphclassdef() {
        let stmt = GlyphClassDefStatement::new(
            Some(GlyphContainer::GlyphClass(GlyphClass::new(
                vec![GlyphContainer::GlyphName(GlyphName::new("a"))],
                0..0,
            ))),
            None,
            Some(GlyphContainer::GlyphClass(GlyphClass::new(
                vec![GlyphContainer::GlyphName(GlyphName::new("acutecomb"))],
                0..0,
            ))),
            None,
            0..0,
        );
        assert_eq!(stmt.as_fea(""), "GlyphClassDef [a], , [acutecomb], ;");
    }

    #[test]
    fn test_roundtrip_glyphclassdef_named_classes() {
        const FEA: &str =
            "table GDEF { GlyphClassDef @BASE, @LIGATURES, @MARKS, @COMPONENT; } GDEF;";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let gdef_table = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GdefTable::cast)
            .unwrap();
        let class_def = gdef_table
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GdefClassDef::cast)
            .unwrap();

        let stmt = GlyphClassDefStatement::from(class_def);
        assert!(stmt.base_glyphs.is_some());
        assert!(stmt.ligature_glyphs.is_some());
        assert!(stmt.mark_glyphs.is_some());
        assert!(stmt.component_glyphs.is_some());
        assert_eq!(
            stmt.as_fea(""),
            "GlyphClassDef @BASE, @LIGATURES, @MARKS, @COMPONENT;"
        );
    }
}