-
Notifications
You must be signed in to change notification settings - Fork 447
/
ast.py
2122 lines (1731 loc) · 71.6 KB
/
ast.py
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fontTools.feaLib.error import FeatureLibError
from fontTools.feaLib.location import FeatureLibLocation
from fontTools.misc.encodingTools import getEncoding
from fontTools.misc.textTools import byteord, tobytes
from collections import OrderedDict
import itertools
SHIFT = " " * 4
__all__ = [
"Element",
"FeatureFile",
"Comment",
"GlyphName",
"GlyphClass",
"GlyphClassName",
"MarkClassName",
"AnonymousBlock",
"Block",
"FeatureBlock",
"NestedBlock",
"LookupBlock",
"GlyphClassDefinition",
"GlyphClassDefStatement",
"MarkClass",
"MarkClassDefinition",
"AlternateSubstStatement",
"Anchor",
"AnchorDefinition",
"AttachStatement",
"AxisValueLocationStatement",
"BaseAxis",
"CVParametersNameStatement",
"ChainContextPosStatement",
"ChainContextSubstStatement",
"CharacterStatement",
"ConditionsetStatement",
"CursivePosStatement",
"ElidedFallbackName",
"ElidedFallbackNameID",
"Expression",
"FeatureNameStatement",
"FeatureReferenceStatement",
"FontRevisionStatement",
"HheaField",
"IgnorePosStatement",
"IgnoreSubstStatement",
"IncludeStatement",
"LanguageStatement",
"LanguageSystemStatement",
"LigatureCaretByIndexStatement",
"LigatureCaretByPosStatement",
"LigatureSubstStatement",
"LookupFlagStatement",
"LookupReferenceStatement",
"MarkBasePosStatement",
"MarkLigPosStatement",
"MarkMarkPosStatement",
"MultipleSubstStatement",
"NameRecord",
"OS2Field",
"PairPosStatement",
"ReverseChainSingleSubstStatement",
"ScriptStatement",
"SinglePosStatement",
"SingleSubstStatement",
"SizeParameters",
"Statement",
"STATAxisValueStatement",
"STATDesignAxisStatement",
"STATNameStatement",
"SubtableStatement",
"TableBlock",
"ValueRecord",
"ValueRecordDefinition",
"VheaField",
]
def deviceToString(device):
if device is None:
return "<device NULL>"
else:
return "<device %s>" % ", ".join("%d %d" % t for t in device)
fea_keywords = set(
[
"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",
]
)
def asFea(g):
if hasattr(g, "asFea"):
return g.asFea()
elif isinstance(g, tuple) and len(g) == 2:
return asFea(g[0]) + " - " + asFea(g[1]) # a range
elif g.lower() in fea_keywords:
return "\\" + g
else:
return g
class Element(object):
"""A base class representing "something" in a feature file."""
def __init__(self, location=None):
#: location of this element as a `FeatureLibLocation` object.
if location and not isinstance(location, FeatureLibLocation):
location = FeatureLibLocation(*location)
self.location = location
def build(self, builder):
pass
def asFea(self, indent=""):
"""Returns this element as a string of feature code. For block-type
elements (such as :class:`FeatureBlock`), the `indent` string is
added to the start of each line in the output."""
raise NotImplementedError
def __str__(self):
return self.asFea()
class Statement(Element):
pass
class Expression(Element):
pass
class Comment(Element):
"""A comment in a feature file."""
def __init__(self, text, location=None):
super(Comment, self).__init__(location)
#: Text of the comment
self.text = text
def asFea(self, indent=""):
return self.text
class NullGlyph(Expression):
"""The NULL glyph, used in glyph deletion substitutions."""
def __init__(self, location=None):
Expression.__init__(self, location)
#: The name itself as a string
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return ()
def asFea(self, indent=""):
return "NULL"
class GlyphName(Expression):
"""A single glyph name, such as ``cedilla``."""
def __init__(self, glyph, location=None):
Expression.__init__(self, location)
#: The name itself as a string
self.glyph = glyph
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return (self.glyph,)
def asFea(self, indent=""):
return asFea(self.glyph)
class GlyphClass(Expression):
"""A glyph class, such as ``[acute cedilla grave]``."""
def __init__(self, glyphs=None, location=None):
Expression.__init__(self, location)
#: The list of glyphs in this class, as :class:`GlyphName` objects.
self.glyphs = glyphs if glyphs is not None else []
self.original = []
self.curr = 0
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return tuple(self.glyphs)
def asFea(self, indent=""):
if len(self.original):
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.curr = len(self.glyphs)
return "[" + " ".join(map(asFea, self.original)) + "]"
else:
return "[" + " ".join(map(asFea, self.glyphs)) + "]"
def extend(self, glyphs):
"""Add a list of :class:`GlyphName` objects to the class."""
self.glyphs.extend(glyphs)
def append(self, glyph):
"""Add a single :class:`GlyphName` object to the class."""
self.glyphs.append(glyph)
def add_range(self, start, end, glyphs):
"""Add a range (e.g. ``A-Z``) to the class. ``start`` and ``end``
are either :class:`GlyphName` objects or strings representing the
start and end glyphs in the class, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append((start, end))
self.glyphs.extend(glyphs)
self.curr = len(self.glyphs)
def add_cid_range(self, start, end, glyphs):
"""Add a range to the class by glyph ID. ``start`` and ``end`` are the
initial and final IDs, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append(("\\{}".format(start), "\\{}".format(end)))
self.glyphs.extend(glyphs)
self.curr = len(self.glyphs)
def add_class(self, gc):
"""Add glyphs from the given :class:`GlyphClassName` object to the
class."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append(gc)
self.glyphs.extend(gc.glyphSet())
self.curr = len(self.glyphs)
class GlyphClassName(Expression):
"""A glyph class name, such as ``@FRENCH_MARKS``. This must be instantiated
with a :class:`GlyphClassDefinition` object."""
def __init__(self, glyphclass, location=None):
Expression.__init__(self, location)
assert isinstance(glyphclass, GlyphClassDefinition)
self.glyphclass = glyphclass
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return tuple(self.glyphclass.glyphSet())
def asFea(self, indent=""):
return "@" + self.glyphclass.name
class MarkClassName(Expression):
"""A mark class name, such as ``@FRENCH_MARKS`` defined with ``markClass``.
This must be instantiated with a :class:`MarkClass` object."""
def __init__(self, markClass, location=None):
Expression.__init__(self, location)
assert isinstance(markClass, MarkClass)
self.markClass = markClass
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return self.markClass.glyphSet()
def asFea(self, indent=""):
return "@" + self.markClass.name
class AnonymousBlock(Statement):
"""An anonymous data block."""
def __init__(self, tag, content, location=None):
Statement.__init__(self, location)
self.tag = tag #: string containing the block's "tag"
self.content = content #: block data as string
def asFea(self, indent=""):
res = "anon {} {{\n".format(self.tag)
res += self.content
res += "}} {};\n\n".format(self.tag)
return res
class Block(Statement):
"""A block of statements: feature, lookup, etc."""
def __init__(self, location=None):
Statement.__init__(self, location)
self.statements = [] #: Statements contained in the block
def build(self, builder):
"""When handed a 'builder' object of comparable interface to
:class:`fontTools.feaLib.builder`, walks the statements in this
block, calling the builder callbacks."""
for s in self.statements:
s.build(builder)
def asFea(self, indent=""):
indent += SHIFT
return (
indent
+ ("\n" + indent).join([s.asFea(indent=indent) for s in self.statements])
+ "\n"
)
class FeatureFile(Block):
"""The top-level element of the syntax tree, containing the whole feature
file in its ``statements`` attribute."""
def __init__(self):
Block.__init__(self, location=None)
self.markClasses = {} # name --> ast.MarkClass
def asFea(self, indent=""):
return "\n".join(s.asFea(indent=indent) for s in self.statements)
class FeatureBlock(Block):
"""A named feature block."""
def __init__(self, name, use_extension=False, location=None):
Block.__init__(self, location)
self.name, self.use_extension = name, use_extension
def build(self, builder):
"""Call the ``start_feature`` callback on the builder object, visit
all the statements in this feature, and then call ``end_feature``."""
# TODO(sascha): Handle use_extension.
builder.start_feature(self.location, self.name)
# language exclude_dflt statements modify builder.features_
# limit them to this block with temporary builder.features_
features = builder.features_
builder.features_ = {}
Block.build(self, builder)
for key, value in builder.features_.items():
features.setdefault(key, []).extend(value)
builder.features_ = features
builder.end_feature()
def asFea(self, indent=""):
res = indent + "feature %s " % self.name.strip()
if self.use_extension:
res += "useExtension "
res += "{\n"
res += Block.asFea(self, indent=indent)
res += indent + "} %s;\n" % self.name.strip()
return res
class NestedBlock(Block):
"""A block inside another block, for example when found inside a
``cvParameters`` block."""
def __init__(self, tag, block_name, location=None):
Block.__init__(self, location)
self.tag = tag
self.block_name = block_name
def build(self, builder):
Block.build(self, builder)
if self.block_name == "ParamUILabelNameID":
builder.add_to_cv_num_named_params(self.tag)
def asFea(self, indent=""):
res = "{}{} {{\n".format(indent, self.block_name)
res += Block.asFea(self, indent=indent)
res += "{}}};\n".format(indent)
return res
class LookupBlock(Block):
"""A named lookup, containing ``statements``."""
def __init__(self, name, use_extension=False, location=None):
Block.__init__(self, location)
self.name, self.use_extension = name, use_extension
def build(self, builder):
# TODO(sascha): Handle use_extension.
builder.start_lookup_block(self.location, self.name)
Block.build(self, builder)
builder.end_lookup_block()
def asFea(self, indent=""):
res = "lookup {} ".format(self.name)
if self.use_extension:
res += "useExtension "
res += "{\n"
res += Block.asFea(self, indent=indent)
res += "{}}} {};\n".format(indent, self.name)
return res
class TableBlock(Block):
"""A ``table ... { }`` block."""
def __init__(self, name, location=None):
Block.__init__(self, location)
self.name = name
def asFea(self, indent=""):
res = "table {} {{\n".format(self.name.strip())
res += super(TableBlock, self).asFea(indent=indent)
res += "}} {};\n".format(self.name.strip())
return res
class GlyphClassDefinition(Statement):
"""Example: ``@UPPERCASE = [A-Z];``."""
def __init__(self, name, glyphs, location=None):
Statement.__init__(self, location)
self.name = name #: class name as a string, without initial ``@``
self.glyphs = glyphs #: a :class:`GlyphClass` object
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return tuple(self.glyphs.glyphSet())
def asFea(self, indent=""):
return "@" + self.name + " = " + self.glyphs.asFea() + ";"
class GlyphClassDefStatement(Statement):
"""Example: ``GlyphClassDef @UPPERCASE, [B], [C], [D];``. The parameters
must be either :class:`GlyphClass` or :class:`GlyphClassName` objects, or
``None``."""
def __init__(
self, baseGlyphs, markGlyphs, ligatureGlyphs, componentGlyphs, location=None
):
Statement.__init__(self, location)
self.baseGlyphs, self.markGlyphs = (baseGlyphs, markGlyphs)
self.ligatureGlyphs = ligatureGlyphs
self.componentGlyphs = componentGlyphs
def build(self, builder):
"""Calls the builder's ``add_glyphClassDef`` callback."""
base = self.baseGlyphs.glyphSet() if self.baseGlyphs else tuple()
liga = self.ligatureGlyphs.glyphSet() if self.ligatureGlyphs else tuple()
mark = self.markGlyphs.glyphSet() if self.markGlyphs else tuple()
comp = self.componentGlyphs.glyphSet() if self.componentGlyphs else tuple()
builder.add_glyphClassDef(self.location, base, liga, mark, comp)
def asFea(self, indent=""):
return "GlyphClassDef {}, {}, {}, {};".format(
self.baseGlyphs.asFea() if self.baseGlyphs else "",
self.ligatureGlyphs.asFea() if self.ligatureGlyphs else "",
self.markGlyphs.asFea() if self.markGlyphs else "",
self.componentGlyphs.asFea() if self.componentGlyphs else "",
)
class MarkClass(object):
"""One `or more` ``markClass`` statements for the same mark class.
While glyph classes can be defined only once, the feature file format
allows expanding mark classes with multiple definitions, each using
different glyphs and anchors. The following are two ``MarkClassDefinitions``
for the same ``MarkClass``::
markClass [acute grave] <anchor 350 800> @FRENCH_ACCENTS;
markClass [cedilla] <anchor 350 -200> @FRENCH_ACCENTS;
The ``MarkClass`` object is therefore just a container for a list of
:class:`MarkClassDefinition` statements.
"""
def __init__(self, name):
self.name = name
self.definitions = []
self.glyphs = OrderedDict() # glyph --> ast.MarkClassDefinitions
def addDefinition(self, definition):
"""Add a :class:`MarkClassDefinition` statement to this mark class."""
assert isinstance(definition, MarkClassDefinition)
self.definitions.append(definition)
for glyph in definition.glyphSet():
if glyph in self.glyphs:
otherLoc = self.glyphs[glyph].location
if otherLoc is None:
end = ""
else:
end = f" at {otherLoc}"
raise FeatureLibError(
"Glyph %s already defined%s" % (glyph, end), definition.location
)
self.glyphs[glyph] = definition
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return tuple(self.glyphs.keys())
def asFea(self, indent=""):
res = "\n".join(d.asFea() for d in self.definitions)
return res
class MarkClassDefinition(Statement):
"""A single ``markClass`` statement. The ``markClass`` should be a
:class:`MarkClass` object, the ``anchor`` an :class:`Anchor` object,
and the ``glyphs`` parameter should be a `glyph-containing object`_ .
Example:
.. code:: python
mc = MarkClass("FRENCH_ACCENTS")
mc.addDefinition( MarkClassDefinition(mc, Anchor(350, 800),
GlyphClass([ GlyphName("acute"), GlyphName("grave") ])
) )
mc.addDefinition( MarkClassDefinition(mc, Anchor(350, -200),
GlyphClass([ GlyphName("cedilla") ])
) )
mc.asFea()
# markClass [acute grave] <anchor 350 800> @FRENCH_ACCENTS;
# markClass [cedilla] <anchor 350 -200> @FRENCH_ACCENTS;
"""
def __init__(self, markClass, anchor, glyphs, location=None):
Statement.__init__(self, location)
assert isinstance(markClass, MarkClass)
assert isinstance(anchor, Anchor) and isinstance(glyphs, Expression)
self.markClass, self.anchor, self.glyphs = markClass, anchor, glyphs
def glyphSet(self):
"""The glyphs in this class as a tuple of :class:`GlyphName` objects."""
return self.glyphs.glyphSet()
def asFea(self, indent=""):
return "markClass {} {} @{};".format(
self.glyphs.asFea(), self.anchor.asFea(), self.markClass.name
)
class AlternateSubstStatement(Statement):
"""A ``sub ... from ...`` statement.
``prefix``, ``glyph``, ``suffix`` and ``replacement`` should be lists of
`glyph-containing objects`_. ``glyph`` should be a `one element list`."""
def __init__(self, prefix, glyph, suffix, replacement, location=None):
Statement.__init__(self, location)
self.prefix, self.glyph, self.suffix = (prefix, glyph, suffix)
self.replacement = replacement
def build(self, builder):
"""Calls the builder's ``add_alternate_subst`` callback."""
glyph = self.glyph.glyphSet()
assert len(glyph) == 1, glyph
glyph = list(glyph)[0]
prefix = [p.glyphSet() for p in self.prefix]
suffix = [s.glyphSet() for s in self.suffix]
replacement = self.replacement.glyphSet()
builder.add_alternate_subst(self.location, prefix, glyph, suffix, replacement)
def asFea(self, indent=""):
res = "sub "
if len(self.prefix) or len(self.suffix):
if len(self.prefix):
res += " ".join(map(asFea, self.prefix)) + " "
res += asFea(self.glyph) + "'" # even though we really only use 1
if len(self.suffix):
res += " " + " ".join(map(asFea, self.suffix))
else:
res += asFea(self.glyph)
res += " from "
res += asFea(self.replacement)
res += ";"
return res
class Anchor(Expression):
"""An ``Anchor`` element, used inside a ``pos`` rule.
If a ``name`` is given, this will be used in preference to the coordinates.
Other values should be integer.
"""
def __init__(
self,
x,
y,
name=None,
contourpoint=None,
xDeviceTable=None,
yDeviceTable=None,
location=None,
):
Expression.__init__(self, location)
self.name = name
self.x, self.y, self.contourpoint = x, y, contourpoint
self.xDeviceTable, self.yDeviceTable = xDeviceTable, yDeviceTable
def asFea(self, indent=""):
if self.name is not None:
return "<anchor {}>".format(self.name)
res = "<anchor {} {}".format(self.x, self.y)
if self.contourpoint:
res += " contourpoint {}".format(self.contourpoint)
if self.xDeviceTable or self.yDeviceTable:
res += " "
res += deviceToString(self.xDeviceTable)
res += " "
res += deviceToString(self.yDeviceTable)
res += ">"
return res
class AnchorDefinition(Statement):
"""A named anchor definition. (2.e.viii). ``name`` should be a string."""
def __init__(self, name, x, y, contourpoint=None, location=None):
Statement.__init__(self, location)
self.name, self.x, self.y, self.contourpoint = name, x, y, contourpoint
def asFea(self, indent=""):
res = "anchorDef {} {}".format(self.x, self.y)
if self.contourpoint:
res += " contourpoint {}".format(self.contourpoint)
res += " {};".format(self.name)
return res
class AttachStatement(Statement):
"""A ``GDEF`` table ``Attach`` statement."""
def __init__(self, glyphs, contourPoints, location=None):
Statement.__init__(self, location)
self.glyphs = glyphs #: A `glyph-containing object`_
self.contourPoints = contourPoints #: A list of integer contour points
def build(self, builder):
"""Calls the builder's ``add_attach_points`` callback."""
glyphs = self.glyphs.glyphSet()
builder.add_attach_points(self.location, glyphs, self.contourPoints)
def asFea(self, indent=""):
return "Attach {} {};".format(
self.glyphs.asFea(), " ".join(str(c) for c in self.contourPoints)
)
class ChainContextPosStatement(Statement):
r"""A chained contextual positioning statement.
``prefix``, ``glyphs``, and ``suffix`` should be lists of
`glyph-containing objects`_ .
``lookups`` should be a list of elements representing what lookups
to apply at each glyph position. Each element should be a
:class:`LookupBlock` to apply a single chaining lookup at the given
position, a list of :class:`LookupBlock`\ s to apply multiple
lookups, or ``None`` to apply no lookup. The length of the outer
list should equal the length of ``glyphs``; the inner lists can be
of variable length."""
def __init__(self, prefix, glyphs, suffix, lookups, location=None):
Statement.__init__(self, location)
self.prefix, self.glyphs, self.suffix = prefix, glyphs, suffix
self.lookups = list(lookups)
for i, lookup in enumerate(lookups):
if lookup:
try:
(_ for _ in lookup)
except TypeError:
self.lookups[i] = [lookup]
def build(self, builder):
"""Calls the builder's ``add_chain_context_pos`` callback."""
prefix = [p.glyphSet() for p in self.prefix]
glyphs = [g.glyphSet() for g in self.glyphs]
suffix = [s.glyphSet() for s in self.suffix]
builder.add_chain_context_pos(
self.location, prefix, glyphs, suffix, self.lookups
)
def asFea(self, indent=""):
res = "pos "
if (
len(self.prefix)
or len(self.suffix)
or any([x is not None for x in self.lookups])
):
if len(self.prefix):
res += " ".join(g.asFea() for g in self.prefix) + " "
for i, g in enumerate(self.glyphs):
res += g.asFea() + "'"
if self.lookups[i]:
for lu in self.lookups[i]:
res += " lookup " + lu.name
if i < len(self.glyphs) - 1:
res += " "
if len(self.suffix):
res += " " + " ".join(map(asFea, self.suffix))
else:
res += " ".join(map(asFea, self.glyph))
res += ";"
return res
class ChainContextSubstStatement(Statement):
r"""A chained contextual substitution statement.
``prefix``, ``glyphs``, and ``suffix`` should be lists of
`glyph-containing objects`_ .
``lookups`` should be a list of elements representing what lookups
to apply at each glyph position. Each element should be a
:class:`LookupBlock` to apply a single chaining lookup at the given
position, a list of :class:`LookupBlock`\ s to apply multiple
lookups, or ``None`` to apply no lookup. The length of the outer
list should equal the length of ``glyphs``; the inner lists can be
of variable length."""
def __init__(self, prefix, glyphs, suffix, lookups, location=None):
Statement.__init__(self, location)
self.prefix, self.glyphs, self.suffix = prefix, glyphs, suffix
self.lookups = list(lookups)
for i, lookup in enumerate(lookups):
if lookup:
try:
(_ for _ in lookup)
except TypeError:
self.lookups[i] = [lookup]
def build(self, builder):
"""Calls the builder's ``add_chain_context_subst`` callback."""
prefix = [p.glyphSet() for p in self.prefix]
glyphs = [g.glyphSet() for g in self.glyphs]
suffix = [s.glyphSet() for s in self.suffix]
builder.add_chain_context_subst(
self.location, prefix, glyphs, suffix, self.lookups
)
def asFea(self, indent=""):
res = "sub "
if (
len(self.prefix)
or len(self.suffix)
or any([x is not None for x in self.lookups])
):
if len(self.prefix):
res += " ".join(g.asFea() for g in self.prefix) + " "
for i, g in enumerate(self.glyphs):
res += g.asFea() + "'"
if self.lookups[i]:
for lu in self.lookups[i]:
res += " lookup " + lu.name
if i < len(self.glyphs) - 1:
res += " "
if len(self.suffix):
res += " " + " ".join(map(asFea, self.suffix))
else:
res += " ".join(map(asFea, self.glyph))
res += ";"
return res
class CursivePosStatement(Statement):
"""A cursive positioning statement. Entry and exit anchors can either
be :class:`Anchor` objects or ``None``."""
def __init__(self, glyphclass, entryAnchor, exitAnchor, location=None):
Statement.__init__(self, location)
self.glyphclass = glyphclass
self.entryAnchor, self.exitAnchor = entryAnchor, exitAnchor
def build(self, builder):
"""Calls the builder object's ``add_cursive_pos`` callback."""
builder.add_cursive_pos(
self.location, self.glyphclass.glyphSet(), self.entryAnchor, self.exitAnchor
)
def asFea(self, indent=""):
entry = self.entryAnchor.asFea() if self.entryAnchor else "<anchor NULL>"
exit = self.exitAnchor.asFea() if self.exitAnchor else "<anchor NULL>"
return "pos cursive {} {} {};".format(self.glyphclass.asFea(), entry, exit)
class FeatureReferenceStatement(Statement):
"""Example: ``feature salt;``"""
def __init__(self, featureName, location=None):
Statement.__init__(self, location)
self.location, self.featureName = (location, featureName)
def build(self, builder):
"""Calls the builder object's ``add_feature_reference`` callback."""
builder.add_feature_reference(self.location, self.featureName)
def asFea(self, indent=""):
return "feature {};".format(self.featureName)
class IgnorePosStatement(Statement):
"""An ``ignore pos`` statement, containing `one or more` contexts to ignore.
``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples,
with each of ``prefix``, ``glyphs`` and ``suffix`` being
`glyph-containing objects`_ ."""
def __init__(self, chainContexts, location=None):
Statement.__init__(self, location)
self.chainContexts = chainContexts
def build(self, builder):
"""Calls the builder object's ``add_chain_context_pos`` callback on each
rule context."""
for prefix, glyphs, suffix in self.chainContexts:
prefix = [p.glyphSet() for p in prefix]
glyphs = [g.glyphSet() for g in glyphs]
suffix = [s.glyphSet() for s in suffix]
builder.add_chain_context_pos(self.location, prefix, glyphs, suffix, [])
def asFea(self, indent=""):
contexts = []
for prefix, glyphs, suffix in self.chainContexts:
res = ""
if len(prefix) or len(suffix):
if len(prefix):
res += " ".join(map(asFea, prefix)) + " "
res += " ".join(g.asFea() + "'" for g in glyphs)
if len(suffix):
res += " " + " ".join(map(asFea, suffix))
else:
res += " ".join(map(asFea, glyphs))
contexts.append(res)
return "ignore pos " + ", ".join(contexts) + ";"
class IgnoreSubstStatement(Statement):
"""An ``ignore sub`` statement, containing `one or more` contexts to ignore.
``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples,
with each of ``prefix``, ``glyphs`` and ``suffix`` being
`glyph-containing objects`_ ."""
def __init__(self, chainContexts, location=None):
Statement.__init__(self, location)
self.chainContexts = chainContexts
def build(self, builder):
"""Calls the builder object's ``add_chain_context_subst`` callback on
each rule context."""
for prefix, glyphs, suffix in self.chainContexts:
prefix = [p.glyphSet() for p in prefix]
glyphs = [g.glyphSet() for g in glyphs]
suffix = [s.glyphSet() for s in suffix]
builder.add_chain_context_subst(self.location, prefix, glyphs, suffix, [])
def asFea(self, indent=""):
contexts = []
for prefix, glyphs, suffix in self.chainContexts:
res = ""
if len(prefix) or len(suffix):
if len(prefix):
res += " ".join(map(asFea, prefix)) + " "
res += " ".join(g.asFea() + "'" for g in glyphs)
if len(suffix):
res += " " + " ".join(map(asFea, suffix))
else:
res += " ".join(map(asFea, glyphs))
contexts.append(res)
return "ignore sub " + ", ".join(contexts) + ";"
class IncludeStatement(Statement):
"""An ``include()`` statement."""
def __init__(self, filename, location=None):
super(IncludeStatement, self).__init__(location)
self.filename = filename #: String containing name of file to include
def build(self):
# TODO: consider lazy-loading the including parser/lexer?
raise FeatureLibError(
"Building an include statement is not implemented yet. "
"Instead, use Parser(..., followIncludes=True) for building.",
self.location,
)
def asFea(self, indent=""):
return indent + "include(%s);" % self.filename
class LanguageStatement(Statement):
"""A ``language`` statement within a feature."""
def __init__(self, language, include_default=True, required=False, location=None):
Statement.__init__(self, location)
assert len(language) == 4
self.language = language #: A four-character language tag
self.include_default = include_default #: If false, "exclude_dflt"
self.required = required
def build(self, builder):
"""Call the builder object's ``set_language`` callback."""
builder.set_language(
location=self.location,
language=self.language,
include_default=self.include_default,
required=self.required,
)
def asFea(self, indent=""):
res = "language {}".format(self.language.strip())
if not self.include_default:
res += " exclude_dflt"
if self.required:
res += " required"
res += ";"
return res
class LanguageSystemStatement(Statement):
"""A top-level ``languagesystem`` statement."""
def __init__(self, script, language, location=None):
Statement.__init__(self, location)
self.script, self.language = (script, language)
def build(self, builder):
"""Calls the builder object's ``add_language_system`` callback."""
builder.add_language_system(self.location, self.script, self.language)
def asFea(self, indent=""):
return "languagesystem {} {};".format(self.script, self.language.strip())
class FontRevisionStatement(Statement):
"""A ``head`` table ``FontRevision`` statement. ``revision`` should be a
number, and will be formatted to three significant decimal places."""
def __init__(self, revision, location=None):
Statement.__init__(self, location)
self.revision = revision
def build(self, builder):
builder.set_font_revision(self.location, self.revision)