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

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

use crate::AsFea;

const FEA_KEYWORDS: [&str; 52] = [
    "anchor",
    "anchordef",
    "anon",
    "anonymous",
    "by",
    "contour",
    "cursive",
    "device",
    "enum",
    "enumerate",
    "excludedflt",
    "exclude_dflt",
    "feature",
    "from",
    "ignore",
    "ignorebaseglyphs",
    "ignoreligatures",
    "ignoremarks",
    "include",
    "includedflt",
    "include_dflt",
    "language",
    "languagesystem",
    "lookup",
    "lookupflag",
    "mark",
    "markattachmenttype",
    "markclass",
    "nameid",
    "null",
    "parameters",
    "pos",
    "position",
    "required",
    "righttoleft",
    "reversesub",
    "rsub",
    "script",
    "sub",
    "substitute",
    "subtable",
    "table",
    "usemarkfilteringset",
    "useextension",
    "valuerecorddef",
    "base",
    "gdef",
    "head",
    "hhea",
    "name",
    "vhea",
    "vmtx",
];

/// A single glyph name, such as `cedilla`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct GlyphName {
    /// The name itself as a string
    pub name: SmolStr,
}

impl std::fmt::Debug for GlyphName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "GlyphName({})", self.name)
    }
}

impl GlyphName {
    /// Creates a new `GlyphName`, representing a single named glyph.
    pub fn new(name: &str) -> Self {
        Self {
            name: SmolStr::new(name),
        }
    }

    /// Returns an iterator over the glyph names in this `GlyphName`.
    pub fn glyphset(&self) -> impl Iterator<Item = &SmolStr> {
        std::iter::once(&self.name)
    }
}
impl AsFea for GlyphName {
    fn as_fea(&self, _indent: &str) -> String {
        if FEA_KEYWORDS.contains(&self.name.as_str()) {
            format!("\\{}", self.name)
        } else {
            self.name.to_string()
        }
    }
}

/// A glyph class literal, such as `[a b c]` or `[a-z A-Z]`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GlyphClass {
    /// The glyphs in the class literal
    pub glyphs: Vec<GlyphContainer>,
    /// The location of the glyph class in the source feature file
    #[cfg_attr(
        feature = "serde",
        serde(
            default = "crate::default_range",
            skip_serializing_if = "crate::is_default_range"
        )
    )]
    pub location: Range<usize>,
}
impl GlyphClass {
    /// Creates a new `GlyphClass` with the given glyph containers and location.
    pub fn new(glyphs: Vec<GlyphContainer>, location: Range<usize>) -> Self {
        Self { glyphs, location }
    }
}
impl AsFea for GlyphClass {
    fn as_fea(&self, _indent: &str) -> String {
        let inner: Vec<String> = self.glyphs.iter().map(|g| g.as_fea("")).collect();
        format!("[{}]", inner.join(" "))
    }
}
impl From<fea_rs::typed::GlyphClass> for GlyphClass {
    fn from(val: fea_rs::typed::GlyphClass) -> Self {
        match val {
            fea_rs::typed::GlyphClass::Named(glyph_class_name) => {
                let members = vec![GlyphContainer::GlyphClassName(SmolStr::new(
                    glyph_class_name.text(),
                ))];
                GlyphClass::new(members, glyph_class_name.range())
            }
            fea_rs::typed::GlyphClass::Literal(glyph_class_literal) => glyph_class_literal.into(),
        }
    }
}
impl From<fea_rs::typed::GlyphClassLiteral> for GlyphClass {
    fn from(val: fea_rs::typed::GlyphClassLiteral) -> Self {
        let members: Vec<GlyphContainer> = val
            .node()
            .iter_children()
            .flat_map(|child| {
                if let Some(gc) = fea_rs::typed::GlyphOrClass::cast(child) {
                    Some(gc.into())
                } else if let Some(gr) = fea_rs::typed::GlyphRange::cast(child) {
                    let start = gr
                        .iter()
                        .find_map(fea_rs::typed::GlyphName::cast)
                        .map(|gn| SmolStr::new(gn.text()))
                        .unwrap();
                    let end = gr
                        .iter()
                        .skip_while(|t| t.kind() != fea_rs::Kind::Hyphen)
                        .find_map(fea_rs::typed::GlyphName::cast)
                        .map(|gn| SmolStr::new(gn.text()))
                        .unwrap();

                    Some(GlyphContainer::GlyphRange(GlyphRange::new(start, end)))
                // "GlyphNameOrRange" doesn't go into the typed AST, we have to handle it ourselves
                } else if child.kind() == fea_rs::Kind::GlyphNameOrRange {
                    Some(GlyphContainer::GlyphNameOrRange(
                        child.token_text().unwrap().into(),
                    ))
                } else {
                    None
                }
            })
            .collect();
        GlyphClass::new(members, val.node().range())
    }
}

/// A glyph range, such as `a-z` or `A01-A05`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GlyphRange {
    /// Start glyph name of the range
    pub start: SmolStr,
    /// End glyph name of the range
    pub end: SmolStr,
}
impl GlyphRange {
    /// Creates a new `GlyphRange` with the given start and end glyph names.
    pub fn new(start: SmolStr, end: SmolStr) -> Self {
        Self { start, end }
    }

    /// Returns an iterator over the glyph names in this `GlyphRange`.
    pub fn glyphset(&self) -> impl Iterator<Item = SmolStr> {
        // OK, the rules are:
        // <firstGlyph> and <lastGlyph> must be the same length and can differ only in one of the following ways:
        // By a single letter from A-Z, either uppercase or lowercase.
        // By up to 3 decimal digits in a contiguous run
        // So first we find a common prefix and suffix
        let start_bytes = self.start.as_bytes();
        let end_bytes = self.end.as_bytes();
        let mut prefix_len = 0;
        let mut suffix_len = 0;
        for (start_byte, end_byte) in start_bytes.iter().zip(end_bytes.iter()) {
            if start_byte == end_byte {
                prefix_len += 1;
            } else {
                break;
            }
        }
        for (start_byte, end_byte) in start_bytes.iter().rev().zip(end_bytes.iter().rev()) {
            if start_byte == end_byte {
                suffix_len += 1;
            } else {
                break;
            }
        }
        let start_core = &self.start[prefix_len..self.start.len() - suffix_len];
        let end_core = &self.end[prefix_len..self.end.len() - suffix_len];
        if start_core.len() != end_core.len() {
            // invalid range
            return vec![self.start.clone(), self.end.clone()].into_iter();
        }
        if start_core.len() == 1 {
            // Check if both cores are a single lower case or upper case letter
            let start_char = start_core.chars().next().unwrap();
            let end_char = end_core.chars().next().unwrap();
            if (start_char.is_ascii_lowercase() && end_char.is_ascii_lowercase())
                || (start_char.is_ascii_uppercase() && end_char.is_ascii_uppercase())
            {
                let range = start_char as u8..=end_char as u8;
                let glyphs: Vec<SmolStr> = range
                    .map(|b| {
                        SmolStr::new(format!(
                            "{}{}{}",
                            &self.start[..prefix_len],
                            b as char,
                            &self.start[self.start.len() - suffix_len..]
                        ))
                    })
                    .collect();
                return glyphs.into_iter();
            } else {
                // invalid range
                return vec![self.start.clone(), self.end.clone()].into_iter();
            }
        }
        // So it should be a 1 to 3 digit number
        let start_num: Option<usize> = start_core.parse().ok();
        let end_num: Option<usize> = end_core.parse().ok();
        if let (Some(start_num), Some(end_num)) = (start_num, end_num) {
            let range = start_num..=end_num;
            // Format each number to the correct width with leading zeros
            let glyphs: Vec<SmolStr> = range
                .map(|n| {
                    let mut s = String::new();
                    s.push_str(&self.start[..prefix_len]);
                    s.push_str(&format!("{:0width$}", n, width = start_core.len()));
                    s.push_str(&self.start[self.start.len() - suffix_len..]);
                    SmolStr::new(s)
                })
                .collect();
            return glyphs.into_iter();
        }
        // invalid range
        vec![self.start.clone(), self.end.clone()].into_iter()
    }
}
impl From<Range<SmolStr>> for GlyphRange {
    fn from(val: Range<SmolStr>) -> Self {
        GlyphRange::new(val.start, val.end)
    }
}
impl AsFea for GlyphRange {
    fn as_fea(&self, _indent: &str) -> String {
        format!("{} - {}", self.start.as_str(), self.end.as_str())
    }
}

/// A container for glyphs in various forms: single glyph names, glyph classes,
/// glyph ranges, or glyph name/range literals.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GlyphContainer {
    /// A single glyph name
    GlyphName(GlyphName),
    /// A glyph class literal
    GlyphClass(GlyphClass),
    /// A named glyph class
    GlyphClassName(SmolStr),
    /// A glyph range
    GlyphRange(GlyphRange),
    /// An ambiguity: either a glyph name or range literal, up to the user to resolve
    GlyphNameOrRange(SmolStr),
}

impl AsFea for GlyphContainer {
    fn as_fea(&self, _indent: &str) -> String {
        match self {
            GlyphContainer::GlyphName(gn) => gn.as_fea(_indent),
            GlyphContainer::GlyphClass(gcs) => {
                let inner: Vec<String> = gcs.glyphs.iter().map(|g| g.as_fea("")).collect();
                format!("[{}]", inner.join(" "))
            }
            GlyphContainer::GlyphClassName(name) => {
                if FEA_KEYWORDS.contains(&name.as_str()) {
                    format!("\\{}", name)
                } else {
                    name.to_string()
                }
            }
            GlyphContainer::GlyphRange(range) => range.as_fea(""),
            GlyphContainer::GlyphNameOrRange(name_or_range) => name_or_range.to_string(),
        }
    }
}

impl From<fea_rs::typed::GlyphOrClass> for GlyphContainer {
    fn from(val: fea_rs::typed::GlyphOrClass) -> Self {
        match val {
            GlyphOrClass::Glyph(glyph) => GlyphContainer::GlyphName(GlyphName::new(glyph.text())),
            GlyphOrClass::Class(glyph_class_literal) => {
                GlyphContainer::GlyphClass(glyph_class_literal.into())
            }
            GlyphOrClass::Cid(_cid) => todo!(),
            GlyphOrClass::NamedClass(glyph_class_name) => {
                GlyphContainer::GlyphClassName(SmolStr::new(glyph_class_name.text()))
            }
            GlyphOrClass::Null(_) => GlyphContainer::GlyphName(GlyphName::new("NULL")),
        }
    }
}

impl From<fea_rs::typed::GlyphClass> for GlyphContainer {
    fn from(val: fea_rs::typed::GlyphClass) -> Self {
        match val {
            fea_rs::typed::GlyphClass::Named(glyph_class_name) => {
                GlyphContainer::GlyphClassName(SmolStr::new(glyph_class_name.text()))
            }
            fea_rs::typed::GlyphClass::Literal(glyph_class_literal) => {
                GlyphContainer::GlyphClass(glyph_class_literal.into())
            }
        }
    }
}

impl GlyphContainer {
    /// Creates a new `GlyphContainer` representing a glyph class literal
    /// containing the given glyph names.
    pub fn new_class(glyph_names: &[&str]) -> Self {
        let members: Vec<GlyphContainer> = glyph_names
            .iter()
            .map(|name| GlyphContainer::GlyphName(GlyphName::new(name)))
            .collect();
        GlyphContainer::GlyphClass(GlyphClass::new(
            members,
            0..0, // location is not relevant here
        ))
    }

    /// Returns true if this `GlyphContainer` is an empty glyph class.
    pub fn is_empty(&self) -> bool {
        match self {
            GlyphContainer::GlyphClass(gcs) => gcs.glyphs.is_empty(),
            _ => false,
        }
    }
}

/// Custom serde serialization for GlyphContainer that serializes GlyphName variants as plain strings
#[cfg(feature = "serde")]
mod glyph_container_serde {
    use super::*;
    use serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for super::GlyphContainer {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                super::GlyphContainer::GlyphName(gn) => {
                    // Serialize GlyphName directly as a string
                    serializer.serialize_str(&gn.name)
                }
                super::GlyphContainer::GlyphClass(gc) => gc.serialize(serializer),
                super::GlyphContainer::GlyphClassName(name) => {
                    // Serialize as { "GlyphClassName": name_str }
                    let mut map = serializer.serialize_map(Some(1))?;
                    map.serialize_entry("GlyphClassName", name)?;
                    map.end()
                }
                super::GlyphContainer::GlyphRange(gr) => gr.serialize(serializer),
                super::GlyphContainer::GlyphNameOrRange(name) => {
                    // Serialize as { "GlyphNameOrRange": name_str }
                    let mut map = serializer.serialize_map(Some(1))?;
                    map.serialize_entry("GlyphNameOrRange", name)?;
                    map.end()
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for super::GlyphContainer {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            #[derive(Deserialize)]
            #[serde(untagged)]
            enum GlyphContainerEnum {
                String(String),
                GlyphClass(GlyphClass),
                GlyphClassName {
                    #[serde(rename = "GlyphClassName")]
                    glyph_class_name: SmolStr,
                },
                GlyphRange(GlyphRange),
                GlyphNameOrRange {
                    #[serde(rename = "GlyphNameOrRange")]
                    glyph_name_or_range: SmolStr,
                },
            }

            match GlyphContainerEnum::deserialize(deserializer)? {
                GlyphContainerEnum::String(s) => {
                    Ok(super::GlyphContainer::GlyphName(GlyphName::new(&s)))
                }
                GlyphContainerEnum::GlyphClass(gc) => Ok(super::GlyphContainer::GlyphClass(gc)),
                GlyphContainerEnum::GlyphClassName {
                    glyph_class_name: cn,
                } => Ok(super::GlyphContainer::GlyphClassName(cn)),
                GlyphContainerEnum::GlyphRange(gr) => Ok(super::GlyphContainer::GlyphRange(gr)),
                GlyphContainerEnum::GlyphNameOrRange {
                    glyph_name_or_range: nor,
                } => Ok(super::GlyphContainer::GlyphNameOrRange(nor)),
            }
        }
    }
}

/// The name of a mark class
///
/// Note that this differs from the Python `fontTools` representation. In
/// Python, a `MarkClass` object contains `MarkClassDefinition` objects
/// for the glyphs in the class, and the `MarkClassDefinition` objects
/// recursively refer to the `MarkClass` they belong to. In Rust, the
/// `MarkClass` is just a name, and the relationship between the class name
/// and the glyphs and their anchor points is stored at the feature file level.
///
/// The name should not begin with `@`.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MarkClass {
    /// The name of the mark class, without the leading `@`
    pub name: SmolStr,
}
impl MarkClass {
    /// Creates a new `MarkClass` with the given name.
    pub fn new(name: &str) -> Self {
        Self {
            name: SmolStr::new(name),
        }
    }
}
impl From<fea_rs::typed::GlyphClassDef> for MarkClass {
    fn from(val: fea_rs::typed::GlyphClassDef) -> Self {
        let label = val
            .iter()
            .find_map(fea_rs::typed::GlyphClassName::cast)
            .unwrap();
        MarkClass::new(label.text().trim_start_matches('@'))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_glyphclass() {
        const FEA: &str = "@foo = [a-b c d-e @bar];";
        let (parsed, _) = fea_rs::parse::parse_string(FEA);
        let definition = parsed
            .root()
            .iter_children()
            .find_map(fea_rs::typed::GlyphClassDef::cast)
            .unwrap();
        let literal = definition
            .node()
            .iter_children()
            .find_map(fea_rs::typed::GlyphClassLiteral::cast)
            .unwrap();
        println!("{:#?}", literal);
        let glyphs: GlyphClass = literal.into();
        assert_eq!(glyphs.glyphs.len(), 4);
    }

    #[test]
    fn test_glyphrange() {
        let range = GlyphRange::new(SmolStr::new("a01"), SmolStr::new("a05"));
        let glyphs: Vec<SmolStr> = range.glyphset().collect();
        assert_eq!(
            glyphs,
            vec![
                SmolStr::new("a01"),
                SmolStr::new("a02"),
                SmolStr::new("a03"),
                SmolStr::new("a04"),
                SmolStr::new("a05"),
            ]
        );

        let range = GlyphRange::new(SmolStr::new("B"), SmolStr::new("F"));
        let glyphs: Vec<SmolStr> = range.glyphset().collect();
        assert_eq!(
            glyphs,
            vec![
                SmolStr::new("B"),
                SmolStr::new("C"),
                SmolStr::new("D"),
                SmolStr::new("E"),
                SmolStr::new("F"),
            ]
        );

        let range = GlyphRange::new(SmolStr::new("cat"), SmolStr::new("cet"));
        let glyphs: Vec<SmolStr> = range.glyphset().collect();
        assert_eq!(
            glyphs,
            vec![
                SmolStr::new("cat"),
                SmolStr::new("cbt"),
                SmolStr::new("cct"),
                SmolStr::new("cdt"),
                SmolStr::new("cet"),
            ]
        );
    }
}