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

use fea_rs::{NodeOrToken, typed::AstNode};

use crate::{
    AsFea, Comment, FontRevisionStatement, GdefStatement, NameRecord, SHIFT, stat::StatStatement,
};

/// A helper for constructing tables which hold statements of a particular type.
pub trait FeaTable {
    /// The type of statement contained in this table.
    type Statement: AsFea;
    /// The corresponding fea-rs typed table.
    type FeaRsTable: AstNode;
    /// The tag of this table.
    const TAG: &'static str;
    /// Convert a child node or token into a statement of this table's type, if possible.
    fn to_statement(child: &NodeOrToken) -> Option<Self::Statement>;
    /// Extract all statements of this table's type from a fea-rs node.
    fn statements_from_node(node: &fea_rs::Node) -> Vec<Self::Statement> {
        node.iter_children()
            .filter_map(Self::to_statement)
            .collect()
    }
}

/// A table in a feature file, parameterized by the type of statements it contains.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Table<T: FeaTable> {
    /// The statements in this table.
    pub statements: Vec<T::Statement>,
}

impl<T: FeaTable> AsFea for Table<T> {
    fn as_fea(&self, indent: &str) -> String {
        let mut res = String::new();
        res.push_str(&format!("{}table {} {{\n", indent, T::TAG));
        for stmt in &self.statements {
            res.push_str(&stmt.as_fea(&(indent.to_string() + SHIFT)));
            res.push('\n');
        }
        res.push_str(&format!("{}}} {};\n", indent, T::TAG));
        res
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `GDEF` table
pub struct Gdef;
impl FeaTable for Gdef {
    type Statement = GdefStatement;
    type FeaRsTable = fea_rs::typed::GdefTable;
    const TAG: &'static str = "GDEF";
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<Self::Statement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(GdefStatement::Comment(Comment::from(
                child.token_text().unwrap(),
            )))
        } else if let Some(at) = fea_rs::typed::GdefAttach::cast(child) {
            Some(GdefStatement::Attach(at.into()))
        } else if let Some(gcd) = fea_rs::typed::GdefClassDef::cast(child) {
            Some(GdefStatement::GlyphClassDef(gcd.into()))
        } else if let Some(lc) = fea_rs::typed::GdefLigatureCaret::cast(child) {
            // Check if it's by position or by index based on the first keyword
            let is_by_pos = lc
                .iter()
                .next()
                .map(|t| t.kind() == fea_rs::Kind::LigatureCaretByPosKw)
                .unwrap_or(false);
            if is_by_pos {
                Some(GdefStatement::LigatureCaretByPos(lc.into()))
            } else {
                Some(GdefStatement::LigatureCaretByIndex(lc.into()))
            }
        } else {
            None
        }
    }
}

impl From<fea_rs::typed::GdefTable> for Table<Gdef> {
    fn from(val: fea_rs::typed::GdefTable) -> Self {
        Self {
            statements: Gdef::statements_from_node(val.node()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `head` table
pub struct Head;
impl FeaTable for Head {
    type Statement = HeadStatement;
    const TAG: &'static str = "head";
    type FeaRsTable = fea_rs::typed::HeadTable;
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<HeadStatement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(HeadStatement::Comment(Comment::from(
                child.token_text().unwrap(),
            )))
        } else if let Some(fr) = fea_rs::typed::HeadFontRevision::cast(child) {
            Some(HeadStatement::FontRevision(fr.into()))
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A statement in the `head` table
pub enum HeadStatement {
    /// A comment
    Comment(Comment),
    /// a `FontRevision` statement
    FontRevision(FontRevisionStatement),
}
impl AsFea for HeadStatement {
    fn as_fea(&self, indent: &str) -> String {
        match self {
            HeadStatement::Comment(cmt) => cmt.as_fea(indent),
            HeadStatement::FontRevision(stmt) => stmt.as_fea(indent),
        }
    }
}

impl From<fea_rs::typed::HeadTable> for Table<Head> {
    fn from(val: fea_rs::typed::HeadTable) -> Self {
        Self {
            statements: Head::statements_from_node(val.node()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `name` table
pub struct Name;
impl FeaTable for Name {
    type Statement = NameStatement;
    const TAG: &'static str = "name";
    type FeaRsTable = fea_rs::typed::NameTable;
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<NameStatement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(NameStatement::Comment(Comment::from(
                child.token_text().unwrap(),
            )))
        } else if let Some(fr) = fea_rs::typed::NameRecord::cast(child) {
            Some(NameStatement::NameRecord(fr.into()))
        } else {
            None
        }
    }
}

/// A statement in the `name` table
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NameStatement {
    /// A comment
    Comment(Comment),
    /// a `NameRecord` statement
    NameRecord(NameRecord),
}
impl AsFea for NameStatement {
    fn as_fea(&self, indent: &str) -> String {
        match self {
            NameStatement::Comment(cmt) => cmt.as_fea(indent),
            NameStatement::NameRecord(stmt) => stmt.as_fea(indent),
        }
    }
}

impl From<fea_rs::typed::NameTable> for Table<Name> {
    fn from(val: fea_rs::typed::NameTable) -> Self {
        Self {
            statements: Name::statements_from_node(val.node()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `STAT` table
pub struct Stat;
impl FeaTable for Stat {
    type Statement = StatStatement;
    const TAG: &'static str = "STAT";
    type FeaRsTable = fea_rs::typed::StatTable;
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<StatStatement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(StatStatement::Comment(Comment::from(
                child.token_text().unwrap(),
            )))
        } else if let Some(da) = fea_rs::typed::StatDesignAxis::cast(child) {
            Some(StatStatement::DesignAxis(da.into()))
        } else if let Some(efn) = fea_rs::typed::StatElidedFallbackName::cast(child) {
            Some(StatStatement::from(efn))
        } else if let Some(efn) = fea_rs::typed::StatAxisValue::cast(child) {
            Some(StatStatement::AxisValue(efn.into()))
        } else {
            None
        }
    }
}

impl From<fea_rs::typed::StatTable> for Table<Stat> {
    fn from(val: fea_rs::typed::StatTable) -> Self {
        Self {
            statements: Stat::statements_from_node(val.node()),
        }
    }
}

// hhea

#[derive(Debug, Clone, PartialEq, Eq)]
/// Fields in the `hhea` table
pub enum HheaField {
    /// A comment
    Comment(Comment),
    /// A `CaretOffset` statement
    CaretOffset(i16),
    /// An `Ascender` statement
    Ascender(i16),
    /// A `Descender` statement
    Descender(i16),
    /// A `LineGap` statement
    LineGap(i16),
}
impl AsFea for HheaField {
    fn as_fea(&self, indent: &str) -> String {
        match self {
            HheaField::Comment(cmt) => cmt.as_fea(indent),
            HheaField::CaretOffset(x) => format!("{}CaretOffset {};", indent, x),
            HheaField::Ascender(x) => format!("{}Ascender {};", indent, x),
            HheaField::Descender(x) => format!("{}Descender {};", indent, x),
            HheaField::LineGap(x) => format!("{}LineGap {};", indent, x),
        }
    }
}

/// A statement in the `hhea` table
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HheaStatement {
    /// The field of this statement
    pub field: HheaField,
    /// The location of this statement in the source
    pub location: Range<usize>,
}
impl AsFea for HheaStatement {
    fn as_fea(&self, indent: &str) -> String {
        self.field.as_fea(indent)
    }
}
impl From<fea_rs::typed::MetricRecord> for HheaStatement {
    fn from(val: fea_rs::typed::MetricRecord) -> Self {
        let keyword = val
            .node()
            .iter_children()
            .next()
            .and_then(|t| t.as_token())
            .unwrap();
        let metric = val
            .node()
            .iter_children()
            .find_map(fea_rs::typed::Metric::cast)
            .unwrap();
        let value = match metric {
            fea_rs::typed::Metric::Scalar(number) => number.text().parse::<i16>().unwrap(),
            _ => unimplemented!(),
        };
        HheaStatement {
            field: match keyword.kind {
                fea_rs::Kind::CaretOffsetKw => HheaField::CaretOffset(value),
                fea_rs::Kind::AscenderKw => HheaField::Ascender(value),
                fea_rs::Kind::DescenderKw => HheaField::Descender(value),
                fea_rs::Kind::LineGapKw => HheaField::LineGap(value),
                _ => panic!("Unexpected keyword in HHEA metric record"),
            },
            location: val.range(),
        }
    }
}

impl From<fea_rs::typed::HheaTable> for Table<Hhea> {
    fn from(val: fea_rs::typed::HheaTable) -> Self {
        Self {
            statements: Hhea::statements_from_node(val.node()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `hhea` table
pub struct Hhea;
impl FeaTable for Hhea {
    type Statement = HheaStatement;
    const TAG: &'static str = "hhea";
    type FeaRsTable = fea_rs::typed::HheaTable;
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<HheaStatement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(HheaStatement {
                field: HheaField::Comment(Comment::from(child.token_text().unwrap())),
                location: child.range(),
            })
        } else if let Some(fr) = fea_rs::typed::MetricRecord::cast(child) {
            Some(fr.into())
        } else {
            None
        }
    }
}

// vhea

/// A field in the `vhea` table
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VheaField {
    /// A comment
    Comment(Comment),
    /// A `VertTypoAscender` statement
    VertTypoAscender(i16),
    /// A `VertTypoDescender` statement
    VertTypoDescender(i16),
    /// A `VertTypoLineGap` statement
    VertTypoLineGap(i16),
}
impl AsFea for VheaField {
    fn as_fea(&self, indent: &str) -> String {
        match self {
            VheaField::Comment(cmt) => cmt.as_fea(indent),
            VheaField::VertTypoAscender(x) => format!("{}VertTypoAscender {};", indent, x),
            VheaField::VertTypoDescender(x) => format!("{}VertTypoDescender {};", indent, x),
            VheaField::VertTypoLineGap(x) => format!("{}VertTypoLineGap {};", indent, x),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// A statement in the `vhea` table
pub struct VheaStatement {
    field: VheaField,
    location: Range<usize>,
}
impl AsFea for VheaStatement {
    fn as_fea(&self, indent: &str) -> String {
        self.field.as_fea(indent)
    }
}
impl From<fea_rs::typed::MetricRecord> for VheaStatement {
    fn from(val: fea_rs::typed::MetricRecord) -> Self {
        let keyword = val
            .node()
            .iter_children()
            .next()
            .and_then(|t| t.as_token())
            .unwrap();
        let metric = val
            .node()
            .iter_children()
            .find_map(fea_rs::typed::Metric::cast)
            .unwrap();
        let value = match metric {
            fea_rs::typed::Metric::Scalar(number) => number.text().parse::<i16>().unwrap(),
            _ => unimplemented!(),
        };
        VheaStatement {
            field: match keyword.kind {
                fea_rs::Kind::VertTypoAscenderKw => VheaField::VertTypoAscender(value),
                fea_rs::Kind::VertTypoDescenderKw => VheaField::VertTypoDescender(value),
                fea_rs::Kind::VertTypoLineGapKw => VheaField::VertTypoLineGap(value),
                _ => panic!("Unexpected keyword in Vhea metric record"),
            },
            location: val.range(),
        }
    }
}

impl From<fea_rs::typed::VheaTable> for Table<Vhea> {
    fn from(val: fea_rs::typed::VheaTable) -> Self {
        Self {
            statements: Vhea::statements_from_node(val.node()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The `vhea` table
pub struct Vhea;
impl FeaTable for Vhea {
    type Statement = VheaStatement;
    const TAG: &'static str = "vhea";
    type FeaRsTable = fea_rs::typed::VheaTable;
    #[allow(clippy::manual_map)]
    fn to_statement(child: &NodeOrToken) -> Option<VheaStatement> {
        if child.kind() == fea_rs::Kind::Comment {
            Some(VheaStatement {
                field: VheaField::Comment(Comment::from(child.token_text().unwrap())),
                location: child.range(),
            })
        } else if let Some(fr) = fea_rs::typed::MetricRecord::cast(child) {
            Some(fr.into())
        } else {
            None
        }
    }
}