fonttools 4.59.1__cp314-cp314t-musllinux_1_2_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fonttools might be problematic. Click here for more details.

Files changed (346) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +233 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3694 -0
  8. fontTools/cffLib/specializer.py +927 -0
  9. fontTools/cffLib/transforms.py +495 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +90 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +15560 -0
  23. fontTools/cu2qu/cu2qu.cpython-314t-x86_64-linux-musl.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +260 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2143 -0
  39. fontTools/feaLib/builder.py +1802 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17351 -0
  42. fontTools/feaLib/lexer.cpython-314t-x86_64-linux-musl.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2379 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1014 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +173 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +352 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +40151 -0
  62. fontTools/misc/bezierTools.cpython-314t-x86_64-linux-musl.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +456 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/filesystem/__init__.py +68 -0
  74. fontTools/misc/filesystem/_base.py +134 -0
  75. fontTools/misc/filesystem/_copy.py +45 -0
  76. fontTools/misc/filesystem/_errors.py +54 -0
  77. fontTools/misc/filesystem/_info.py +75 -0
  78. fontTools/misc/filesystem/_osfs.py +164 -0
  79. fontTools/misc/filesystem/_path.py +67 -0
  80. fontTools/misc/filesystem/_subfs.py +92 -0
  81. fontTools/misc/filesystem/_tempfs.py +34 -0
  82. fontTools/misc/filesystem/_tools.py +34 -0
  83. fontTools/misc/filesystem/_walk.py +55 -0
  84. fontTools/misc/filesystem/_zipfs.py +204 -0
  85. fontTools/misc/fixedTools.py +253 -0
  86. fontTools/misc/intTools.py +25 -0
  87. fontTools/misc/iterTools.py +12 -0
  88. fontTools/misc/lazyTools.py +42 -0
  89. fontTools/misc/loggingTools.py +543 -0
  90. fontTools/misc/macCreatorType.py +56 -0
  91. fontTools/misc/macRes.py +261 -0
  92. fontTools/misc/plistlib/__init__.py +681 -0
  93. fontTools/misc/plistlib/py.typed +0 -0
  94. fontTools/misc/psCharStrings.py +1511 -0
  95. fontTools/misc/psLib.py +398 -0
  96. fontTools/misc/psOperators.py +572 -0
  97. fontTools/misc/py23.py +96 -0
  98. fontTools/misc/roundTools.py +110 -0
  99. fontTools/misc/sstruct.py +227 -0
  100. fontTools/misc/symfont.py +242 -0
  101. fontTools/misc/testTools.py +233 -0
  102. fontTools/misc/textTools.py +154 -0
  103. fontTools/misc/timeTools.py +88 -0
  104. fontTools/misc/transform.py +516 -0
  105. fontTools/misc/treeTools.py +45 -0
  106. fontTools/misc/vector.py +147 -0
  107. fontTools/misc/visitor.py +150 -0
  108. fontTools/misc/xmlReader.py +188 -0
  109. fontTools/misc/xmlWriter.py +231 -0
  110. fontTools/mtiLib/__init__.py +1400 -0
  111. fontTools/mtiLib/__main__.py +5 -0
  112. fontTools/otlLib/__init__.py +1 -0
  113. fontTools/otlLib/builder.py +3465 -0
  114. fontTools/otlLib/error.py +11 -0
  115. fontTools/otlLib/maxContextCalc.py +96 -0
  116. fontTools/otlLib/optimize/__init__.py +53 -0
  117. fontTools/otlLib/optimize/__main__.py +6 -0
  118. fontTools/otlLib/optimize/gpos.py +439 -0
  119. fontTools/pens/__init__.py +1 -0
  120. fontTools/pens/areaPen.py +52 -0
  121. fontTools/pens/basePen.py +475 -0
  122. fontTools/pens/boundsPen.py +98 -0
  123. fontTools/pens/cairoPen.py +26 -0
  124. fontTools/pens/cocoaPen.py +26 -0
  125. fontTools/pens/cu2quPen.py +325 -0
  126. fontTools/pens/explicitClosingLinePen.py +101 -0
  127. fontTools/pens/filterPen.py +241 -0
  128. fontTools/pens/freetypePen.py +462 -0
  129. fontTools/pens/hashPointPen.py +89 -0
  130. fontTools/pens/momentsPen.c +13466 -0
  131. fontTools/pens/momentsPen.cpython-314t-x86_64-linux-musl.so +0 -0
  132. fontTools/pens/momentsPen.py +879 -0
  133. fontTools/pens/perimeterPen.py +69 -0
  134. fontTools/pens/pointInsidePen.py +192 -0
  135. fontTools/pens/pointPen.py +609 -0
  136. fontTools/pens/qtPen.py +29 -0
  137. fontTools/pens/qu2cuPen.py +105 -0
  138. fontTools/pens/quartzPen.py +43 -0
  139. fontTools/pens/recordingPen.py +335 -0
  140. fontTools/pens/reportLabPen.py +79 -0
  141. fontTools/pens/reverseContourPen.py +96 -0
  142. fontTools/pens/roundingPen.py +130 -0
  143. fontTools/pens/statisticsPen.py +312 -0
  144. fontTools/pens/svgPathPen.py +310 -0
  145. fontTools/pens/t2CharStringPen.py +88 -0
  146. fontTools/pens/teePen.py +55 -0
  147. fontTools/pens/transformPen.py +115 -0
  148. fontTools/pens/ttGlyphPen.py +335 -0
  149. fontTools/pens/wxPen.py +29 -0
  150. fontTools/qu2cu/__init__.py +15 -0
  151. fontTools/qu2cu/__main__.py +7 -0
  152. fontTools/qu2cu/benchmark.py +56 -0
  153. fontTools/qu2cu/cli.py +125 -0
  154. fontTools/qu2cu/qu2cu.c +16753 -0
  155. fontTools/qu2cu/qu2cu.cpython-314t-x86_64-linux-musl.so +0 -0
  156. fontTools/qu2cu/qu2cu.py +405 -0
  157. fontTools/subset/__init__.py +3929 -0
  158. fontTools/subset/__main__.py +6 -0
  159. fontTools/subset/cff.py +184 -0
  160. fontTools/subset/svg.py +253 -0
  161. fontTools/subset/util.py +25 -0
  162. fontTools/svgLib/__init__.py +3 -0
  163. fontTools/svgLib/path/__init__.py +65 -0
  164. fontTools/svgLib/path/arc.py +154 -0
  165. fontTools/svgLib/path/parser.py +322 -0
  166. fontTools/svgLib/path/shapes.py +183 -0
  167. fontTools/t1Lib/__init__.py +648 -0
  168. fontTools/tfmLib.py +460 -0
  169. fontTools/ttLib/__init__.py +30 -0
  170. fontTools/ttLib/__main__.py +148 -0
  171. fontTools/ttLib/macUtils.py +54 -0
  172. fontTools/ttLib/removeOverlaps.py +393 -0
  173. fontTools/ttLib/reorderGlyphs.py +285 -0
  174. fontTools/ttLib/scaleUpem.py +436 -0
  175. fontTools/ttLib/sfnt.py +661 -0
  176. fontTools/ttLib/standardGlyphOrder.py +271 -0
  177. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  178. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  179. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  180. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  181. fontTools/ttLib/tables/C_F_F_.py +61 -0
  182. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  183. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  184. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  185. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  186. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  187. fontTools/ttLib/tables/DefaultTable.py +49 -0
  188. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  189. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  190. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  191. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  192. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  193. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  194. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  195. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  196. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  197. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  198. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  199. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  200. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  201. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  202. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  203. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  204. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  205. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  206. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  207. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  208. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  209. fontTools/ttLib/tables/S_V_G_.py +223 -0
  210. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  211. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  212. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  213. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  214. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  216. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  219. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  220. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  221. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  222. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  223. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  224. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  225. fontTools/ttLib/tables/TupleVariation.py +884 -0
  226. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  227. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  228. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  229. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  230. fontTools/ttLib/tables/__init__.py +98 -0
  231. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  232. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  233. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  234. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  235. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  236. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  237. fontTools/ttLib/tables/_c_v_t.py +56 -0
  238. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  239. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  240. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  241. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  242. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  243. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  244. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  245. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  246. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  247. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  248. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  249. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  250. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  251. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  252. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  253. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  254. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  255. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  256. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  257. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  258. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  259. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  260. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  261. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  262. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  263. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  264. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  265. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  266. fontTools/ttLib/tables/asciiTable.py +20 -0
  267. fontTools/ttLib/tables/grUtils.py +92 -0
  268. fontTools/ttLib/tables/otBase.py +1464 -0
  269. fontTools/ttLib/tables/otConverters.py +2068 -0
  270. fontTools/ttLib/tables/otData.py +6400 -0
  271. fontTools/ttLib/tables/otTables.py +2703 -0
  272. fontTools/ttLib/tables/otTraverse.py +163 -0
  273. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  274. fontTools/ttLib/tables/sbixStrike.py +177 -0
  275. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  276. fontTools/ttLib/tables/ttProgram.py +594 -0
  277. fontTools/ttLib/ttCollection.py +125 -0
  278. fontTools/ttLib/ttFont.py +1148 -0
  279. fontTools/ttLib/ttGlyphSet.py +490 -0
  280. fontTools/ttLib/ttVisitor.py +32 -0
  281. fontTools/ttLib/woff2.py +1680 -0
  282. fontTools/ttx.py +479 -0
  283. fontTools/ufoLib/__init__.py +2472 -0
  284. fontTools/ufoLib/converters.py +398 -0
  285. fontTools/ufoLib/errors.py +30 -0
  286. fontTools/ufoLib/etree.py +6 -0
  287. fontTools/ufoLib/filenames.py +346 -0
  288. fontTools/ufoLib/glifLib.py +2024 -0
  289. fontTools/ufoLib/kerning.py +121 -0
  290. fontTools/ufoLib/plistlib.py +47 -0
  291. fontTools/ufoLib/pointPen.py +6 -0
  292. fontTools/ufoLib/utils.py +79 -0
  293. fontTools/ufoLib/validators.py +1184 -0
  294. fontTools/unicode.py +50 -0
  295. fontTools/unicodedata/Blocks.py +801 -0
  296. fontTools/unicodedata/Mirrored.py +446 -0
  297. fontTools/unicodedata/OTTags.py +50 -0
  298. fontTools/unicodedata/ScriptExtensions.py +826 -0
  299. fontTools/unicodedata/Scripts.py +3617 -0
  300. fontTools/unicodedata/__init__.py +304 -0
  301. fontTools/varLib/__init__.py +1517 -0
  302. fontTools/varLib/__main__.py +6 -0
  303. fontTools/varLib/avar.py +260 -0
  304. fontTools/varLib/avarPlanner.py +1004 -0
  305. fontTools/varLib/builder.py +215 -0
  306. fontTools/varLib/cff.py +631 -0
  307. fontTools/varLib/errors.py +219 -0
  308. fontTools/varLib/featureVars.py +703 -0
  309. fontTools/varLib/hvar.py +113 -0
  310. fontTools/varLib/instancer/__init__.py +2014 -0
  311. fontTools/varLib/instancer/__main__.py +5 -0
  312. fontTools/varLib/instancer/featureVars.py +190 -0
  313. fontTools/varLib/instancer/names.py +388 -0
  314. fontTools/varLib/instancer/solver.py +309 -0
  315. fontTools/varLib/interpolatable.py +1209 -0
  316. fontTools/varLib/interpolatableHelpers.py +396 -0
  317. fontTools/varLib/interpolatablePlot.py +1269 -0
  318. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  319. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  320. fontTools/varLib/interpolate_layout.py +124 -0
  321. fontTools/varLib/iup.c +19845 -0
  322. fontTools/varLib/iup.cpython-314t-x86_64-linux-musl.so +0 -0
  323. fontTools/varLib/iup.py +490 -0
  324. fontTools/varLib/merger.py +1717 -0
  325. fontTools/varLib/models.py +642 -0
  326. fontTools/varLib/multiVarStore.py +253 -0
  327. fontTools/varLib/mutator.py +529 -0
  328. fontTools/varLib/mvar.py +40 -0
  329. fontTools/varLib/plot.py +238 -0
  330. fontTools/varLib/stat.py +149 -0
  331. fontTools/varLib/varStore.py +739 -0
  332. fontTools/voltLib/__init__.py +5 -0
  333. fontTools/voltLib/__main__.py +206 -0
  334. fontTools/voltLib/ast.py +452 -0
  335. fontTools/voltLib/error.py +12 -0
  336. fontTools/voltLib/lexer.py +99 -0
  337. fontTools/voltLib/parser.py +664 -0
  338. fontTools/voltLib/voltToFea.py +911 -0
  339. fonttools-4.59.1.data/data/share/man/man1/ttx.1 +225 -0
  340. fonttools-4.59.1.dist-info/METADATA +2175 -0
  341. fonttools-4.59.1.dist-info/RECORD +346 -0
  342. fonttools-4.59.1.dist-info/WHEEL +5 -0
  343. fonttools-4.59.1.dist-info/entry_points.txt +5 -0
  344. fonttools-4.59.1.dist-info/licenses/LICENSE +21 -0
  345. fonttools-4.59.1.dist-info/licenses/LICENSE.external +388 -0
  346. fonttools-4.59.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2379 @@
1
+ from fontTools.feaLib.error import FeatureLibError
2
+ from fontTools.feaLib.lexer import Lexer, IncludingLexer, NonIncludingLexer
3
+ from fontTools.feaLib.variableScalar import VariableScalar
4
+ from fontTools.misc.encodingTools import getEncoding
5
+ from fontTools.misc.textTools import bytechr, tobytes, tostr
6
+ import fontTools.feaLib.ast as ast
7
+ import logging
8
+ import os
9
+ import re
10
+
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ class Parser(object):
16
+ """Initializes a Parser object.
17
+
18
+ Example:
19
+
20
+ .. code:: python
21
+
22
+ from fontTools.feaLib.parser import Parser
23
+ parser = Parser(file, font.getReverseGlyphMap())
24
+ parsetree = parser.parse()
25
+
26
+ Note: the ``glyphNames`` iterable serves a double role to help distinguish
27
+ glyph names from ranges in the presence of hyphens and to ensure that glyph
28
+ names referenced in a feature file are actually part of a font's glyph set.
29
+ If the iterable is left empty, no glyph name in glyph set checking takes
30
+ place, and all glyph tokens containing hyphens are treated as literal glyph
31
+ names, not as ranges. (Adding a space around the hyphen can, in any case,
32
+ help to disambiguate ranges from glyph names containing hyphens.)
33
+
34
+ By default, the parser will follow ``include()`` statements in the feature
35
+ file. To turn this off, pass ``followIncludes=False``. Pass a directory string as
36
+ ``includeDir`` to explicitly declare a directory to search included feature files
37
+ in.
38
+ """
39
+
40
+ extensions = {}
41
+ ast = ast
42
+ SS_FEATURE_TAGS = {"ss%02d" % i for i in range(1, 20 + 1)}
43
+ CV_FEATURE_TAGS = {"cv%02d" % i for i in range(1, 99 + 1)}
44
+
45
+ def __init__(
46
+ self, featurefile, glyphNames=(), followIncludes=True, includeDir=None, **kwargs
47
+ ):
48
+ if "glyphMap" in kwargs:
49
+ from fontTools.misc.loggingTools import deprecateArgument
50
+
51
+ deprecateArgument("glyphMap", "use 'glyphNames' (iterable) instead")
52
+ if glyphNames:
53
+ raise TypeError(
54
+ "'glyphNames' and (deprecated) 'glyphMap' are " "mutually exclusive"
55
+ )
56
+ glyphNames = kwargs.pop("glyphMap")
57
+ if kwargs:
58
+ raise TypeError(
59
+ "unsupported keyword argument%s: %s"
60
+ % ("" if len(kwargs) == 1 else "s", ", ".join(repr(k) for k in kwargs))
61
+ )
62
+
63
+ self.glyphNames_ = set(glyphNames)
64
+ self.doc_ = self.ast.FeatureFile()
65
+ self.anchors_ = SymbolTable()
66
+ self.glyphclasses_ = SymbolTable()
67
+ self.lookups_ = SymbolTable()
68
+ self.valuerecords_ = SymbolTable()
69
+ self.symbol_tables_ = {self.anchors_, self.valuerecords_}
70
+ self.next_token_type_, self.next_token_ = (None, None)
71
+ self.cur_comments_ = []
72
+ self.next_token_location_ = None
73
+ lexerClass = IncludingLexer if followIncludes else NonIncludingLexer
74
+ self.lexer_ = lexerClass(featurefile, includeDir=includeDir)
75
+ self.missing = {}
76
+ self.advance_lexer_(comments=True)
77
+
78
+ def parse(self):
79
+ """Parse the file, and return a :class:`fontTools.feaLib.ast.FeatureFile`
80
+ object representing the root of the abstract syntax tree containing the
81
+ parsed contents of the file."""
82
+ statements = self.doc_.statements
83
+ while self.next_token_type_ is not None or self.cur_comments_:
84
+ self.advance_lexer_(comments=True)
85
+ if self.cur_token_type_ is Lexer.COMMENT:
86
+ statements.append(
87
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
88
+ )
89
+ elif self.is_cur_keyword_("include"):
90
+ statements.append(self.parse_include_())
91
+ elif self.cur_token_type_ is Lexer.GLYPHCLASS:
92
+ statements.append(self.parse_glyphclass_definition_())
93
+ elif self.is_cur_keyword_(("anon", "anonymous")):
94
+ statements.append(self.parse_anonymous_())
95
+ elif self.is_cur_keyword_("anchorDef"):
96
+ statements.append(self.parse_anchordef_())
97
+ elif self.is_cur_keyword_("languagesystem"):
98
+ statements.append(self.parse_languagesystem_())
99
+ elif self.is_cur_keyword_("lookup"):
100
+ statements.append(self.parse_lookup_(vertical=False))
101
+ elif self.is_cur_keyword_("markClass"):
102
+ statements.append(self.parse_markClass_())
103
+ elif self.is_cur_keyword_("feature"):
104
+ statements.append(self.parse_feature_block_())
105
+ elif self.is_cur_keyword_("conditionset"):
106
+ statements.append(self.parse_conditionset_())
107
+ elif self.is_cur_keyword_("variation"):
108
+ statements.append(self.parse_feature_block_(variation=True))
109
+ elif self.is_cur_keyword_("table"):
110
+ statements.append(self.parse_table_())
111
+ elif self.is_cur_keyword_("valueRecordDef"):
112
+ statements.append(self.parse_valuerecord_definition_(vertical=False))
113
+ elif (
114
+ self.cur_token_type_ is Lexer.NAME
115
+ and self.cur_token_ in self.extensions
116
+ ):
117
+ statements.append(self.extensions[self.cur_token_](self))
118
+ elif self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == ";":
119
+ continue
120
+ else:
121
+ raise FeatureLibError(
122
+ "Expected feature, languagesystem, lookup, markClass, "
123
+ 'table, or glyph class definition, got {} "{}"'.format(
124
+ self.cur_token_type_, self.cur_token_
125
+ ),
126
+ self.cur_token_location_,
127
+ )
128
+ # Report any missing glyphs at the end of parsing
129
+ if self.missing:
130
+ error = [
131
+ " %s (first found at %s)" % (name, loc)
132
+ for name, loc in self.missing.items()
133
+ ]
134
+ raise FeatureLibError(
135
+ "The following glyph names are referenced but are missing from the "
136
+ "glyph set:\n" + ("\n".join(error)),
137
+ None,
138
+ )
139
+ return self.doc_
140
+
141
+ def parse_anchor_(self):
142
+ # Parses an anchor in any of the four formats given in the feature
143
+ # file specification (2.e.vii).
144
+ self.expect_symbol_("<")
145
+ self.expect_keyword_("anchor")
146
+ location = self.cur_token_location_
147
+
148
+ if self.next_token_ == "NULL": # Format D
149
+ self.expect_keyword_("NULL")
150
+ self.expect_symbol_(">")
151
+ return None
152
+
153
+ if self.next_token_type_ == Lexer.NAME: # Format E
154
+ name = self.expect_name_()
155
+ anchordef = self.anchors_.resolve(name)
156
+ if anchordef is None:
157
+ raise FeatureLibError(
158
+ 'Unknown anchor "%s"' % name, self.cur_token_location_
159
+ )
160
+ self.expect_symbol_(">")
161
+ return self.ast.Anchor(
162
+ anchordef.x,
163
+ anchordef.y,
164
+ name=name,
165
+ contourpoint=anchordef.contourpoint,
166
+ xDeviceTable=None,
167
+ yDeviceTable=None,
168
+ location=location,
169
+ )
170
+
171
+ x, y = self.expect_number_(variable=True), self.expect_number_(variable=True)
172
+
173
+ contourpoint = None
174
+ if self.next_token_ == "contourpoint": # Format B
175
+ self.expect_keyword_("contourpoint")
176
+ contourpoint = self.expect_number_()
177
+
178
+ if self.next_token_ == "<": # Format C
179
+ xDeviceTable = self.parse_device_()
180
+ yDeviceTable = self.parse_device_()
181
+ else:
182
+ xDeviceTable, yDeviceTable = None, None
183
+
184
+ self.expect_symbol_(">")
185
+ return self.ast.Anchor(
186
+ x,
187
+ y,
188
+ name=None,
189
+ contourpoint=contourpoint,
190
+ xDeviceTable=xDeviceTable,
191
+ yDeviceTable=yDeviceTable,
192
+ location=location,
193
+ )
194
+
195
+ def parse_anchor_marks_(self):
196
+ # Parses a sequence of ``[<anchor> mark @MARKCLASS]*.``
197
+ anchorMarks = [] # [(self.ast.Anchor, markClassName)*]
198
+ while self.next_token_ == "<":
199
+ anchor = self.parse_anchor_()
200
+ if anchor is None and self.next_token_ != "mark":
201
+ continue # <anchor NULL> without mark, eg. in GPOS type 5
202
+ self.expect_keyword_("mark")
203
+ markClass = self.expect_markClass_reference_()
204
+ anchorMarks.append((anchor, markClass))
205
+ return anchorMarks
206
+
207
+ def parse_anchordef_(self):
208
+ # Parses a named anchor definition (`section 2.e.viii <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#2.e.vii>`_).
209
+ assert self.is_cur_keyword_("anchorDef")
210
+ location = self.cur_token_location_
211
+ x, y = self.expect_number_(), self.expect_number_()
212
+ contourpoint = None
213
+ if self.next_token_ == "contourpoint":
214
+ self.expect_keyword_("contourpoint")
215
+ contourpoint = self.expect_number_()
216
+ name = self.expect_name_()
217
+ self.expect_symbol_(";")
218
+ anchordef = self.ast.AnchorDefinition(
219
+ name, x, y, contourpoint=contourpoint, location=location
220
+ )
221
+ self.anchors_.define(name, anchordef)
222
+ return anchordef
223
+
224
+ def parse_anonymous_(self):
225
+ # Parses an anonymous data block (`section 10 <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#10>`_).
226
+ assert self.is_cur_keyword_(("anon", "anonymous"))
227
+ tag = self.expect_tag_()
228
+ _, content, location = self.lexer_.scan_anonymous_block(tag)
229
+ self.advance_lexer_()
230
+ self.expect_symbol_("}")
231
+ end_tag = self.expect_tag_()
232
+ assert tag == end_tag, "bad splitting in Lexer.scan_anonymous_block()"
233
+ self.expect_symbol_(";")
234
+ return self.ast.AnonymousBlock(tag, content, location=location)
235
+
236
+ def parse_attach_(self):
237
+ # Parses a GDEF Attach statement (`section 9.b <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.b>`_)
238
+ assert self.is_cur_keyword_("Attach")
239
+ location = self.cur_token_location_
240
+ glyphs = self.parse_glyphclass_(accept_glyphname=True)
241
+ contourPoints = {self.expect_number_()}
242
+ while self.next_token_ != ";":
243
+ contourPoints.add(self.expect_number_())
244
+ self.expect_symbol_(";")
245
+ return self.ast.AttachStatement(glyphs, contourPoints, location=location)
246
+
247
+ def parse_enumerate_(self, vertical):
248
+ # Parse an enumerated pair positioning rule (`section 6.b.ii <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#6.b.ii>`_).
249
+ assert self.cur_token_ in {"enumerate", "enum"}
250
+ self.advance_lexer_()
251
+ return self.parse_position_(enumerated=True, vertical=vertical)
252
+
253
+ def parse_GlyphClassDef_(self):
254
+ # Parses 'GlyphClassDef @BASE, @LIGATURES, @MARKS, @COMPONENTS;'
255
+ assert self.is_cur_keyword_("GlyphClassDef")
256
+ location = self.cur_token_location_
257
+ if self.next_token_ != ",":
258
+ baseGlyphs = self.parse_glyphclass_(accept_glyphname=False)
259
+ else:
260
+ baseGlyphs = None
261
+ self.expect_symbol_(",")
262
+ if self.next_token_ != ",":
263
+ ligatureGlyphs = self.parse_glyphclass_(accept_glyphname=False)
264
+ else:
265
+ ligatureGlyphs = None
266
+ self.expect_symbol_(",")
267
+ if self.next_token_ != ",":
268
+ markGlyphs = self.parse_glyphclass_(accept_glyphname=False)
269
+ else:
270
+ markGlyphs = None
271
+ self.expect_symbol_(",")
272
+ if self.next_token_ != ";":
273
+ componentGlyphs = self.parse_glyphclass_(accept_glyphname=False)
274
+ else:
275
+ componentGlyphs = None
276
+ self.expect_symbol_(";")
277
+ return self.ast.GlyphClassDefStatement(
278
+ baseGlyphs, markGlyphs, ligatureGlyphs, componentGlyphs, location=location
279
+ )
280
+
281
+ def parse_glyphclass_definition_(self):
282
+ # Parses glyph class definitions such as '@UPPERCASE = [A-Z];'
283
+ location, name = self.cur_token_location_, self.cur_token_
284
+ self.expect_symbol_("=")
285
+ glyphs = self.parse_glyphclass_(accept_glyphname=False)
286
+ self.expect_symbol_(";")
287
+ glyphclass = self.ast.GlyphClassDefinition(name, glyphs, location=location)
288
+ self.glyphclasses_.define(name, glyphclass)
289
+ return glyphclass
290
+
291
+ def split_glyph_range_(self, name, location):
292
+ # Since v1.20, the OpenType Feature File specification allows
293
+ # for dashes in glyph names. A sequence like "a-b-c-d" could
294
+ # therefore mean a single glyph whose name happens to be
295
+ # "a-b-c-d", or it could mean a range from glyph "a" to glyph
296
+ # "b-c-d", or a range from glyph "a-b" to glyph "c-d", or a
297
+ # range from glyph "a-b-c" to glyph "d".Technically, this
298
+ # example could be resolved because the (pretty complex)
299
+ # definition of glyph ranges renders most of these splits
300
+ # invalid. But the specification does not say that a compiler
301
+ # should try to apply such fancy heuristics. To encourage
302
+ # unambiguous feature files, we therefore try all possible
303
+ # splits and reject the feature file if there are multiple
304
+ # splits possible. It is intentional that we don't just emit a
305
+ # warning; warnings tend to get ignored. To fix the problem,
306
+ # font designers can trivially add spaces around the intended
307
+ # split point, and we emit a compiler error that suggests
308
+ # how exactly the source should be rewritten to make things
309
+ # unambiguous.
310
+ parts = name.split("-")
311
+ solutions = []
312
+ for i in range(len(parts)):
313
+ start, limit = "-".join(parts[0:i]), "-".join(parts[i:])
314
+ if start in self.glyphNames_ and limit in self.glyphNames_:
315
+ solutions.append((start, limit))
316
+ if len(solutions) == 1:
317
+ start, limit = solutions[0]
318
+ return start, limit
319
+ elif len(solutions) == 0:
320
+ raise FeatureLibError(
321
+ '"%s" is not a glyph in the font, and it can not be split '
322
+ "into a range of known glyphs" % name,
323
+ location,
324
+ )
325
+ else:
326
+ ranges = " or ".join(['"%s - %s"' % (s, l) for s, l in solutions])
327
+ raise FeatureLibError(
328
+ 'Ambiguous glyph range "%s"; '
329
+ "please use %s to clarify what you mean" % (name, ranges),
330
+ location,
331
+ )
332
+
333
+ def parse_glyphclass_(self, accept_glyphname, accept_null=False):
334
+ # Parses a glyph class, either named or anonymous, or (if
335
+ # ``bool(accept_glyphname)``) a glyph name. If ``bool(accept_null)`` then
336
+ # also accept the special NULL glyph.
337
+ if accept_glyphname and self.next_token_type_ in (Lexer.NAME, Lexer.CID):
338
+ if accept_null and self.next_token_ == "NULL":
339
+ # If you want a glyph called NULL, you should escape it.
340
+ self.advance_lexer_()
341
+ return self.ast.NullGlyph(location=self.cur_token_location_)
342
+ glyph = self.expect_glyph_()
343
+ self.check_glyph_name_in_glyph_set(glyph)
344
+ return self.ast.GlyphName(glyph, location=self.cur_token_location_)
345
+ if self.next_token_type_ is Lexer.GLYPHCLASS:
346
+ self.advance_lexer_()
347
+ gc = self.glyphclasses_.resolve(self.cur_token_)
348
+ if gc is None:
349
+ raise FeatureLibError(
350
+ "Unknown glyph class @%s" % self.cur_token_,
351
+ self.cur_token_location_,
352
+ )
353
+ if isinstance(gc, self.ast.MarkClass):
354
+ return self.ast.MarkClassName(gc, location=self.cur_token_location_)
355
+ else:
356
+ return self.ast.GlyphClassName(gc, location=self.cur_token_location_)
357
+
358
+ self.expect_symbol_("[")
359
+ location = self.cur_token_location_
360
+ glyphs = self.ast.GlyphClass(location=location)
361
+ while self.next_token_ != "]":
362
+ if self.next_token_type_ is Lexer.NAME:
363
+ glyph = self.expect_glyph_()
364
+ location = self.cur_token_location_
365
+ if "-" in glyph and self.glyphNames_ and glyph not in self.glyphNames_:
366
+ start, limit = self.split_glyph_range_(glyph, location)
367
+ self.check_glyph_name_in_glyph_set(start, limit)
368
+ glyphs.add_range(
369
+ start, limit, self.make_glyph_range_(location, start, limit)
370
+ )
371
+ elif self.next_token_ == "-":
372
+ start = glyph
373
+ self.expect_symbol_("-")
374
+ limit = self.expect_glyph_()
375
+ self.check_glyph_name_in_glyph_set(start, limit)
376
+ glyphs.add_range(
377
+ start, limit, self.make_glyph_range_(location, start, limit)
378
+ )
379
+ else:
380
+ if "-" in glyph and not self.glyphNames_:
381
+ log.warning(
382
+ str(
383
+ FeatureLibError(
384
+ f"Ambiguous glyph name that looks like a range: {glyph!r}",
385
+ location,
386
+ )
387
+ )
388
+ )
389
+ self.check_glyph_name_in_glyph_set(glyph)
390
+ glyphs.append(glyph)
391
+ elif self.next_token_type_ is Lexer.CID:
392
+ glyph = self.expect_glyph_()
393
+ if self.next_token_ == "-":
394
+ range_location = self.cur_token_location_
395
+ range_start = self.cur_token_
396
+ self.expect_symbol_("-")
397
+ range_end = self.expect_cid_()
398
+ self.check_glyph_name_in_glyph_set(
399
+ f"cid{range_start:05d}",
400
+ f"cid{range_end:05d}",
401
+ )
402
+ glyphs.add_cid_range(
403
+ range_start,
404
+ range_end,
405
+ self.make_cid_range_(range_location, range_start, range_end),
406
+ )
407
+ else:
408
+ glyph_name = f"cid{self.cur_token_:05d}"
409
+ self.check_glyph_name_in_glyph_set(glyph_name)
410
+ glyphs.append(glyph_name)
411
+ elif self.next_token_type_ is Lexer.GLYPHCLASS:
412
+ self.advance_lexer_()
413
+ gc = self.glyphclasses_.resolve(self.cur_token_)
414
+ if gc is None:
415
+ raise FeatureLibError(
416
+ "Unknown glyph class @%s" % self.cur_token_,
417
+ self.cur_token_location_,
418
+ )
419
+ if isinstance(gc, self.ast.MarkClass):
420
+ gc = self.ast.MarkClassName(gc, location=self.cur_token_location_)
421
+ else:
422
+ gc = self.ast.GlyphClassName(gc, location=self.cur_token_location_)
423
+ glyphs.add_class(gc)
424
+ else:
425
+ raise FeatureLibError(
426
+ "Expected glyph name, glyph range, "
427
+ f"or glyph class reference, found {self.next_token_!r}",
428
+ self.next_token_location_,
429
+ )
430
+ self.expect_symbol_("]")
431
+ return glyphs
432
+
433
+ def parse_glyph_pattern_(self, vertical):
434
+ # Parses a glyph pattern, including lookups and context, e.g.::
435
+ #
436
+ # a b
437
+ # a b c' d e
438
+ # a b c' lookup ChangeC d e
439
+ prefix, glyphs, lookups, values, suffix = ([], [], [], [], [])
440
+ hasMarks = False
441
+ while self.next_token_ not in {"by", "from", ";", ","}:
442
+ gc = self.parse_glyphclass_(accept_glyphname=True)
443
+ marked = False
444
+ if self.next_token_ == "'":
445
+ self.expect_symbol_("'")
446
+ hasMarks = marked = True
447
+ if marked:
448
+ if suffix:
449
+ # makeotf also reports this as an error, while FontForge
450
+ # silently inserts ' in all the intervening glyphs.
451
+ # https://github.com/fonttools/fonttools/pull/1096
452
+ raise FeatureLibError(
453
+ "Unsupported contextual target sequence: at most "
454
+ "one run of marked (') glyph/class names allowed",
455
+ self.cur_token_location_,
456
+ )
457
+ glyphs.append(gc)
458
+ elif glyphs:
459
+ suffix.append(gc)
460
+ else:
461
+ prefix.append(gc)
462
+
463
+ if self.is_next_value_():
464
+ values.append(self.parse_valuerecord_(vertical))
465
+ else:
466
+ values.append(None)
467
+
468
+ lookuplist = None
469
+ while self.next_token_ == "lookup":
470
+ if lookuplist is None:
471
+ lookuplist = []
472
+ self.expect_keyword_("lookup")
473
+ if not marked:
474
+ raise FeatureLibError(
475
+ "Lookups can only follow marked glyphs",
476
+ self.cur_token_location_,
477
+ )
478
+ lookup_name = self.expect_name_()
479
+ lookup = self.lookups_.resolve(lookup_name)
480
+ if lookup is None:
481
+ raise FeatureLibError(
482
+ 'Unknown lookup "%s"' % lookup_name, self.cur_token_location_
483
+ )
484
+ lookuplist.append(lookup)
485
+ if marked:
486
+ lookups.append(lookuplist)
487
+
488
+ if not glyphs and not suffix: # eg., "sub f f i by"
489
+ assert lookups == []
490
+ return ([], prefix, [None] * len(prefix), values, [], hasMarks)
491
+ else:
492
+ if any(values[: len(prefix)]):
493
+ raise FeatureLibError(
494
+ "Positioning cannot be applied in the bactrack glyph sequence, "
495
+ "before the marked glyph sequence.",
496
+ self.cur_token_location_,
497
+ )
498
+ marked_values = values[len(prefix) : len(prefix) + len(glyphs)]
499
+ if any(marked_values):
500
+ if any(values[len(prefix) + len(glyphs) :]):
501
+ raise FeatureLibError(
502
+ "Positioning values are allowed only in the marked glyph "
503
+ "sequence, or after the final glyph node when only one glyph "
504
+ "node is marked.",
505
+ self.cur_token_location_,
506
+ )
507
+ values = marked_values
508
+ elif values and values[-1]:
509
+ if len(glyphs) > 1 or any(values[:-1]):
510
+ raise FeatureLibError(
511
+ "Positioning values are allowed only in the marked glyph "
512
+ "sequence, or after the final glyph node when only one glyph "
513
+ "node is marked.",
514
+ self.cur_token_location_,
515
+ )
516
+ values = values[-1:]
517
+ elif any(values):
518
+ raise FeatureLibError(
519
+ "Positioning values are allowed only in the marked glyph "
520
+ "sequence, or after the final glyph node when only one glyph "
521
+ "node is marked.",
522
+ self.cur_token_location_,
523
+ )
524
+ return (prefix, glyphs, lookups, values, suffix, hasMarks)
525
+
526
+ def parse_ignore_glyph_pattern_(self, sub):
527
+ location = self.cur_token_location_
528
+ prefix, glyphs, lookups, values, suffix, hasMarks = self.parse_glyph_pattern_(
529
+ vertical=False
530
+ )
531
+ if any(lookups):
532
+ raise FeatureLibError(
533
+ f'No lookups can be specified for "ignore {sub}"', location
534
+ )
535
+ if not hasMarks:
536
+ error = FeatureLibError(
537
+ f'Ambiguous "ignore {sub}", there should be least one marked glyph',
538
+ location,
539
+ )
540
+ log.warning(str(error))
541
+ suffix, glyphs = glyphs[1:], glyphs[0:1]
542
+ chainContext = (prefix, glyphs, suffix)
543
+ return chainContext
544
+
545
+ def parse_ignore_context_(self, sub):
546
+ location = self.cur_token_location_
547
+ chainContext = [self.parse_ignore_glyph_pattern_(sub)]
548
+ while self.next_token_ == ",":
549
+ self.expect_symbol_(",")
550
+ chainContext.append(self.parse_ignore_glyph_pattern_(sub))
551
+ self.expect_symbol_(";")
552
+ return chainContext
553
+
554
+ def parse_ignore_(self):
555
+ # Parses an ignore sub/pos rule.
556
+ assert self.is_cur_keyword_("ignore")
557
+ location = self.cur_token_location_
558
+ self.advance_lexer_()
559
+ if self.cur_token_ in ["substitute", "sub"]:
560
+ chainContext = self.parse_ignore_context_("sub")
561
+ return self.ast.IgnoreSubstStatement(chainContext, location=location)
562
+ if self.cur_token_ in ["position", "pos"]:
563
+ chainContext = self.parse_ignore_context_("pos")
564
+ return self.ast.IgnorePosStatement(chainContext, location=location)
565
+ raise FeatureLibError(
566
+ 'Expected "substitute" or "position"', self.cur_token_location_
567
+ )
568
+
569
+ def parse_include_(self):
570
+ assert self.cur_token_ == "include"
571
+ location = self.cur_token_location_
572
+ filename = self.expect_filename_()
573
+ # self.expect_symbol_(";")
574
+ return ast.IncludeStatement(filename, location=location)
575
+
576
+ def parse_language_(self):
577
+ assert self.is_cur_keyword_("language")
578
+ location = self.cur_token_location_
579
+ language = self.expect_language_tag_()
580
+ include_default, required = (True, False)
581
+ if self.next_token_ in {"exclude_dflt", "include_dflt"}:
582
+ include_default = self.expect_name_() == "include_dflt"
583
+ if self.next_token_ == "required":
584
+ self.expect_keyword_("required")
585
+ required = True
586
+ self.expect_symbol_(";")
587
+ return self.ast.LanguageStatement(
588
+ language, include_default, required, location=location
589
+ )
590
+
591
+ def parse_ligatureCaretByIndex_(self):
592
+ assert self.is_cur_keyword_("LigatureCaretByIndex")
593
+ location = self.cur_token_location_
594
+ glyphs = self.parse_glyphclass_(accept_glyphname=True)
595
+ carets = [self.expect_number_()]
596
+ while self.next_token_ != ";":
597
+ carets.append(self.expect_number_())
598
+ self.expect_symbol_(";")
599
+ return self.ast.LigatureCaretByIndexStatement(glyphs, carets, location=location)
600
+
601
+ def parse_ligatureCaretByPos_(self):
602
+ assert self.is_cur_keyword_("LigatureCaretByPos")
603
+ location = self.cur_token_location_
604
+ glyphs = self.parse_glyphclass_(accept_glyphname=True)
605
+ carets = [self.expect_number_(variable=True)]
606
+ while self.next_token_ != ";":
607
+ carets.append(self.expect_number_(variable=True))
608
+ self.expect_symbol_(";")
609
+ return self.ast.LigatureCaretByPosStatement(glyphs, carets, location=location)
610
+
611
+ def parse_lookup_(self, vertical):
612
+ # Parses a ``lookup`` - either a lookup block, or a lookup reference
613
+ # inside a feature.
614
+ assert self.is_cur_keyword_("lookup")
615
+ location, name = self.cur_token_location_, self.expect_name_()
616
+
617
+ if self.next_token_ == ";":
618
+ lookup = self.lookups_.resolve(name)
619
+ if lookup is None:
620
+ raise FeatureLibError(
621
+ 'Unknown lookup "%s"' % name, self.cur_token_location_
622
+ )
623
+ self.expect_symbol_(";")
624
+ return self.ast.LookupReferenceStatement(lookup, location=location)
625
+
626
+ use_extension = False
627
+ if self.next_token_ == "useExtension":
628
+ self.expect_keyword_("useExtension")
629
+ use_extension = True
630
+
631
+ block = self.ast.LookupBlock(name, use_extension, location=location)
632
+ self.parse_block_(block, vertical)
633
+ self.lookups_.define(name, block)
634
+ return block
635
+
636
+ def parse_lookupflag_(self):
637
+ # Parses a ``lookupflag`` statement, either specified by number or
638
+ # in words.
639
+ assert self.is_cur_keyword_("lookupflag")
640
+ location = self.cur_token_location_
641
+
642
+ # format B: "lookupflag 6;"
643
+ if self.next_token_type_ == Lexer.NUMBER:
644
+ value = self.expect_number_()
645
+ self.expect_symbol_(";")
646
+ return self.ast.LookupFlagStatement(value, location=location)
647
+
648
+ # format A: "lookupflag RightToLeft MarkAttachmentType @M;"
649
+ value_seen = False
650
+ value, markAttachment, markFilteringSet = 0, None, None
651
+ flags = {
652
+ "RightToLeft": 1,
653
+ "IgnoreBaseGlyphs": 2,
654
+ "IgnoreLigatures": 4,
655
+ "IgnoreMarks": 8,
656
+ }
657
+ seen = set()
658
+ while self.next_token_ != ";":
659
+ if self.next_token_ in seen:
660
+ raise FeatureLibError(
661
+ "%s can be specified only once" % self.next_token_,
662
+ self.next_token_location_,
663
+ )
664
+ seen.add(self.next_token_)
665
+ if self.next_token_ == "MarkAttachmentType":
666
+ self.expect_keyword_("MarkAttachmentType")
667
+ markAttachment = self.parse_glyphclass_(accept_glyphname=False)
668
+ elif self.next_token_ == "UseMarkFilteringSet":
669
+ self.expect_keyword_("UseMarkFilteringSet")
670
+ markFilteringSet = self.parse_glyphclass_(accept_glyphname=False)
671
+ elif self.next_token_ in flags:
672
+ value_seen = True
673
+ value = value | flags[self.expect_name_()]
674
+ else:
675
+ raise FeatureLibError(
676
+ '"%s" is not a recognized lookupflag' % self.next_token_,
677
+ self.next_token_location_,
678
+ )
679
+ self.expect_symbol_(";")
680
+
681
+ if not any([value_seen, markAttachment, markFilteringSet]):
682
+ raise FeatureLibError(
683
+ "lookupflag must have a value", self.next_token_location_
684
+ )
685
+
686
+ return self.ast.LookupFlagStatement(
687
+ value,
688
+ markAttachment=markAttachment,
689
+ markFilteringSet=markFilteringSet,
690
+ location=location,
691
+ )
692
+
693
+ def parse_markClass_(self):
694
+ assert self.is_cur_keyword_("markClass")
695
+ location = self.cur_token_location_
696
+ glyphs = self.parse_glyphclass_(accept_glyphname=True)
697
+ if not glyphs.glyphSet():
698
+ raise FeatureLibError(
699
+ "Empty glyph class in mark class definition", location
700
+ )
701
+ anchor = self.parse_anchor_()
702
+ name = self.expect_class_name_()
703
+ self.expect_symbol_(";")
704
+ markClass = self.doc_.markClasses.get(name)
705
+ if markClass is None:
706
+ markClass = self.ast.MarkClass(name)
707
+ self.doc_.markClasses[name] = markClass
708
+ self.glyphclasses_.define(name, markClass)
709
+ mcdef = self.ast.MarkClassDefinition(
710
+ markClass, anchor, glyphs, location=location
711
+ )
712
+ markClass.addDefinition(mcdef)
713
+ return mcdef
714
+
715
+ def parse_position_(self, enumerated, vertical):
716
+ assert self.cur_token_ in {"position", "pos"}
717
+ if self.next_token_ == "cursive": # GPOS type 3
718
+ return self.parse_position_cursive_(enumerated, vertical)
719
+ elif self.next_token_ == "base": # GPOS type 4
720
+ return self.parse_position_base_(enumerated, vertical)
721
+ elif self.next_token_ == "ligature": # GPOS type 5
722
+ return self.parse_position_ligature_(enumerated, vertical)
723
+ elif self.next_token_ == "mark": # GPOS type 6
724
+ return self.parse_position_mark_(enumerated, vertical)
725
+
726
+ location = self.cur_token_location_
727
+ prefix, glyphs, lookups, values, suffix, hasMarks = self.parse_glyph_pattern_(
728
+ vertical
729
+ )
730
+ self.expect_symbol_(";")
731
+
732
+ if any(lookups):
733
+ # GPOS type 8: Chaining contextual positioning; explicit lookups
734
+ if any(values):
735
+ raise FeatureLibError(
736
+ 'If "lookup" is present, no values must be specified', location
737
+ )
738
+ return self.ast.ChainContextPosStatement(
739
+ prefix, glyphs, suffix, lookups, location=location
740
+ )
741
+
742
+ # Pair positioning, format A: "pos V 10 A -10;"
743
+ # Pair positioning, format B: "pos V A -20;"
744
+ if not prefix and not suffix and len(glyphs) == 2 and not hasMarks:
745
+ if values[0] is None: # Format B: "pos V A -20;"
746
+ values.reverse()
747
+ return self.ast.PairPosStatement(
748
+ glyphs[0],
749
+ values[0],
750
+ glyphs[1],
751
+ values[1],
752
+ enumerated=enumerated,
753
+ location=location,
754
+ )
755
+
756
+ if enumerated:
757
+ raise FeatureLibError(
758
+ '"enumerate" is only allowed with pair positionings', location
759
+ )
760
+ return self.ast.SinglePosStatement(
761
+ list(zip(glyphs, values)),
762
+ prefix,
763
+ suffix,
764
+ forceChain=hasMarks,
765
+ location=location,
766
+ )
767
+
768
+ def parse_position_cursive_(self, enumerated, vertical):
769
+ location = self.cur_token_location_
770
+ self.expect_keyword_("cursive")
771
+ if enumerated:
772
+ raise FeatureLibError(
773
+ '"enumerate" is not allowed with ' "cursive attachment positioning",
774
+ location,
775
+ )
776
+ glyphclass = self.parse_glyphclass_(accept_glyphname=True)
777
+ entryAnchor = self.parse_anchor_()
778
+ exitAnchor = self.parse_anchor_()
779
+ self.expect_symbol_(";")
780
+ return self.ast.CursivePosStatement(
781
+ glyphclass, entryAnchor, exitAnchor, location=location
782
+ )
783
+
784
+ def parse_position_base_(self, enumerated, vertical):
785
+ location = self.cur_token_location_
786
+ self.expect_keyword_("base")
787
+ if enumerated:
788
+ raise FeatureLibError(
789
+ '"enumerate" is not allowed with '
790
+ "mark-to-base attachment positioning",
791
+ location,
792
+ )
793
+ base = self.parse_glyphclass_(accept_glyphname=True)
794
+ marks = self.parse_anchor_marks_()
795
+ self.expect_symbol_(";")
796
+ return self.ast.MarkBasePosStatement(base, marks, location=location)
797
+
798
+ def parse_position_ligature_(self, enumerated, vertical):
799
+ location = self.cur_token_location_
800
+ self.expect_keyword_("ligature")
801
+ if enumerated:
802
+ raise FeatureLibError(
803
+ '"enumerate" is not allowed with '
804
+ "mark-to-ligature attachment positioning",
805
+ location,
806
+ )
807
+ ligatures = self.parse_glyphclass_(accept_glyphname=True)
808
+ marks = [self.parse_anchor_marks_()]
809
+ while self.next_token_ == "ligComponent":
810
+ self.expect_keyword_("ligComponent")
811
+ marks.append(self.parse_anchor_marks_())
812
+ self.expect_symbol_(";")
813
+ return self.ast.MarkLigPosStatement(ligatures, marks, location=location)
814
+
815
+ def parse_position_mark_(self, enumerated, vertical):
816
+ location = self.cur_token_location_
817
+ self.expect_keyword_("mark")
818
+ if enumerated:
819
+ raise FeatureLibError(
820
+ '"enumerate" is not allowed with '
821
+ "mark-to-mark attachment positioning",
822
+ location,
823
+ )
824
+ baseMarks = self.parse_glyphclass_(accept_glyphname=True)
825
+ marks = self.parse_anchor_marks_()
826
+ self.expect_symbol_(";")
827
+ return self.ast.MarkMarkPosStatement(baseMarks, marks, location=location)
828
+
829
+ def parse_script_(self):
830
+ assert self.is_cur_keyword_("script")
831
+ location, script = self.cur_token_location_, self.expect_script_tag_()
832
+ self.expect_symbol_(";")
833
+ return self.ast.ScriptStatement(script, location=location)
834
+
835
+ def parse_substitute_(self):
836
+ assert self.cur_token_ in {"substitute", "sub", "reversesub", "rsub"}
837
+ location = self.cur_token_location_
838
+ reverse = self.cur_token_ in {"reversesub", "rsub"}
839
+ (
840
+ old_prefix,
841
+ old,
842
+ lookups,
843
+ values,
844
+ old_suffix,
845
+ hasMarks,
846
+ ) = self.parse_glyph_pattern_(vertical=False)
847
+ if any(values):
848
+ raise FeatureLibError(
849
+ "Substitution statements cannot contain values", location
850
+ )
851
+ new = []
852
+ if self.next_token_ == "by":
853
+ keyword = self.expect_keyword_("by")
854
+ while self.next_token_ != ";":
855
+ gc = self.parse_glyphclass_(accept_glyphname=True, accept_null=True)
856
+ new.append(gc)
857
+ elif self.next_token_ == "from":
858
+ keyword = self.expect_keyword_("from")
859
+ new = [self.parse_glyphclass_(accept_glyphname=False)]
860
+ else:
861
+ keyword = None
862
+ self.expect_symbol_(";")
863
+ if len(new) == 0 and not any(lookups):
864
+ raise FeatureLibError(
865
+ 'Expected "by", "from" or explicit lookup references',
866
+ self.cur_token_location_,
867
+ )
868
+
869
+ # GSUB lookup type 3: Alternate substitution.
870
+ # Format: "substitute a from [a.1 a.2 a.3];"
871
+ if keyword == "from":
872
+ if reverse:
873
+ raise FeatureLibError(
874
+ 'Reverse chaining substitutions do not support "from"', location
875
+ )
876
+ if len(old) != 1 or len(old[0].glyphSet()) != 1:
877
+ raise FeatureLibError('Expected a single glyph before "from"', location)
878
+ if len(new) != 1:
879
+ raise FeatureLibError(
880
+ 'Expected a single glyphclass after "from"', location
881
+ )
882
+ return self.ast.AlternateSubstStatement(
883
+ old_prefix, old[0], old_suffix, new[0], location=location
884
+ )
885
+
886
+ num_lookups = len([l for l in lookups if l is not None])
887
+
888
+ is_deletion = False
889
+ if len(new) == 1 and isinstance(new[0], ast.NullGlyph):
890
+ new = [] # Deletion
891
+ is_deletion = True
892
+
893
+ # GSUB lookup type 1: Single substitution.
894
+ # Format A: "substitute a by a.sc;"
895
+ # Format B: "substitute [one.fitted one.oldstyle] by one;"
896
+ # Format C: "substitute [a-d] by [A.sc-D.sc];"
897
+ if not reverse and len(old) == 1 and len(new) == 1 and num_lookups == 0:
898
+ glyphs = list(old[0].glyphSet())
899
+ replacements = list(new[0].glyphSet())
900
+ if len(replacements) == 1:
901
+ replacements = replacements * len(glyphs)
902
+ if len(glyphs) != len(replacements):
903
+ raise FeatureLibError(
904
+ 'Expected a glyph class with %d elements after "by", '
905
+ "but found a glyph class with %d elements"
906
+ % (len(glyphs), len(replacements)),
907
+ location,
908
+ )
909
+ return self.ast.SingleSubstStatement(
910
+ old, new, old_prefix, old_suffix, forceChain=hasMarks, location=location
911
+ )
912
+
913
+ # Glyph deletion, built as GSUB lookup type 2: Multiple substitution
914
+ # with empty replacement.
915
+ if is_deletion and len(old) == 1 and num_lookups == 0:
916
+ return self.ast.MultipleSubstStatement(
917
+ old_prefix,
918
+ old[0],
919
+ old_suffix,
920
+ (),
921
+ forceChain=hasMarks,
922
+ location=location,
923
+ )
924
+
925
+ # GSUB lookup type 2: Multiple substitution.
926
+ # Format: "substitute f_f_i by f f i;"
927
+ #
928
+ # GlyphsApp introduces two additional formats:
929
+ # Format 1: "substitute [f_i f_l] by [f f] [i l];"
930
+ # Format 2: "substitute [f_i f_l] by f [i l];"
931
+ # http://handbook.glyphsapp.com/en/layout/multiple-substitution-with-classes/
932
+ if not reverse and len(old) == 1 and len(new) > 1 and num_lookups == 0:
933
+ count = len(old[0].glyphSet())
934
+ for n in new:
935
+ if not list(n.glyphSet()):
936
+ raise FeatureLibError("Empty class in replacement", location)
937
+ if len(n.glyphSet()) != 1 and len(n.glyphSet()) != count:
938
+ raise FeatureLibError(
939
+ f'Expected a glyph class with 1 or {count} elements after "by", '
940
+ f"but found a glyph class with {len(n.glyphSet())} elements",
941
+ location,
942
+ )
943
+ return self.ast.MultipleSubstStatement(
944
+ old_prefix,
945
+ old[0],
946
+ old_suffix,
947
+ new,
948
+ forceChain=hasMarks,
949
+ location=location,
950
+ )
951
+
952
+ # GSUB lookup type 4: Ligature substitution.
953
+ # Format: "substitute f f i by f_f_i;"
954
+ if (
955
+ not reverse
956
+ and len(old) > 1
957
+ and len(new) == 1
958
+ and len(new[0].glyphSet()) == 1
959
+ and num_lookups == 0
960
+ ):
961
+ return self.ast.LigatureSubstStatement(
962
+ old_prefix,
963
+ old,
964
+ old_suffix,
965
+ list(new[0].glyphSet())[0],
966
+ forceChain=hasMarks,
967
+ location=location,
968
+ )
969
+
970
+ # GSUB lookup type 8: Reverse chaining substitution.
971
+ if reverse:
972
+ if len(old) != 1:
973
+ raise FeatureLibError(
974
+ "In reverse chaining single substitutions, "
975
+ "only a single glyph or glyph class can be replaced",
976
+ location,
977
+ )
978
+ if len(new) != 1:
979
+ raise FeatureLibError(
980
+ "In reverse chaining single substitutions, "
981
+ 'the replacement (after "by") must be a single glyph '
982
+ "or glyph class",
983
+ location,
984
+ )
985
+ if num_lookups != 0:
986
+ raise FeatureLibError(
987
+ "Reverse chaining substitutions cannot call named lookups", location
988
+ )
989
+ glyphs = sorted(list(old[0].glyphSet()))
990
+ replacements = sorted(list(new[0].glyphSet()))
991
+ if len(replacements) == 1:
992
+ replacements = replacements * len(glyphs)
993
+ if len(glyphs) != len(replacements):
994
+ raise FeatureLibError(
995
+ 'Expected a glyph class with %d elements after "by", '
996
+ "but found a glyph class with %d elements"
997
+ % (len(glyphs), len(replacements)),
998
+ location,
999
+ )
1000
+ return self.ast.ReverseChainSingleSubstStatement(
1001
+ old_prefix, old_suffix, old, new, location=location
1002
+ )
1003
+
1004
+ if len(old) > 1 and len(new) > 1:
1005
+ raise FeatureLibError(
1006
+ "Direct substitution of multiple glyphs by multiple glyphs "
1007
+ "is not supported",
1008
+ location,
1009
+ )
1010
+
1011
+ # If there are remaining glyphs to parse, this is an invalid GSUB statement
1012
+ if len(new) != 0 or is_deletion:
1013
+ raise FeatureLibError("Invalid substitution statement", location)
1014
+
1015
+ # GSUB lookup type 6: Chaining contextual substitution.
1016
+ rule = self.ast.ChainContextSubstStatement(
1017
+ old_prefix, old, old_suffix, lookups, location=location
1018
+ )
1019
+ return rule
1020
+
1021
+ def parse_subtable_(self):
1022
+ assert self.is_cur_keyword_("subtable")
1023
+ location = self.cur_token_location_
1024
+ self.expect_symbol_(";")
1025
+ return self.ast.SubtableStatement(location=location)
1026
+
1027
+ def parse_size_parameters_(self):
1028
+ # Parses a ``parameters`` statement used in ``size`` features. See
1029
+ # `section 8.b <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#8.b>`_.
1030
+ assert self.is_cur_keyword_("parameters")
1031
+ location = self.cur_token_location_
1032
+ DesignSize = self.expect_decipoint_()
1033
+ SubfamilyID = self.expect_number_()
1034
+ RangeStart = 0.0
1035
+ RangeEnd = 0.0
1036
+ if self.next_token_type_ in (Lexer.NUMBER, Lexer.FLOAT) or SubfamilyID != 0:
1037
+ RangeStart = self.expect_decipoint_()
1038
+ RangeEnd = self.expect_decipoint_()
1039
+
1040
+ self.expect_symbol_(";")
1041
+ return self.ast.SizeParameters(
1042
+ DesignSize, SubfamilyID, RangeStart, RangeEnd, location=location
1043
+ )
1044
+
1045
+ def parse_size_menuname_(self):
1046
+ assert self.is_cur_keyword_("sizemenuname")
1047
+ location = self.cur_token_location_
1048
+ platformID, platEncID, langID, string = self.parse_name_()
1049
+ return self.ast.FeatureNameStatement(
1050
+ "size", platformID, platEncID, langID, string, location=location
1051
+ )
1052
+
1053
+ def parse_table_(self):
1054
+ assert self.is_cur_keyword_("table")
1055
+ location, name = self.cur_token_location_, self.expect_tag_()
1056
+ table = self.ast.TableBlock(name, location=location)
1057
+ self.expect_symbol_("{")
1058
+ handler = {
1059
+ "GDEF": self.parse_table_GDEF_,
1060
+ "head": self.parse_table_head_,
1061
+ "hhea": self.parse_table_hhea_,
1062
+ "vhea": self.parse_table_vhea_,
1063
+ "name": self.parse_table_name_,
1064
+ "BASE": self.parse_table_BASE_,
1065
+ "OS/2": self.parse_table_OS_2_,
1066
+ "STAT": self.parse_table_STAT_,
1067
+ }.get(name)
1068
+ if handler:
1069
+ handler(table)
1070
+ else:
1071
+ raise FeatureLibError(
1072
+ '"table %s" is not supported' % name.strip(), location
1073
+ )
1074
+ self.expect_symbol_("}")
1075
+ end_tag = self.expect_tag_()
1076
+ if end_tag != name:
1077
+ raise FeatureLibError(
1078
+ 'Expected "%s"' % name.strip(), self.cur_token_location_
1079
+ )
1080
+ self.expect_symbol_(";")
1081
+ return table
1082
+
1083
+ def parse_table_GDEF_(self, table):
1084
+ statements = table.statements
1085
+ while self.next_token_ != "}" or self.cur_comments_:
1086
+ self.advance_lexer_(comments=True)
1087
+ if self.cur_token_type_ is Lexer.COMMENT:
1088
+ statements.append(
1089
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1090
+ )
1091
+ elif self.is_cur_keyword_("Attach"):
1092
+ statements.append(self.parse_attach_())
1093
+ elif self.is_cur_keyword_("GlyphClassDef"):
1094
+ statements.append(self.parse_GlyphClassDef_())
1095
+ elif self.is_cur_keyword_("LigatureCaretByIndex"):
1096
+ statements.append(self.parse_ligatureCaretByIndex_())
1097
+ elif self.is_cur_keyword_("LigatureCaretByPos"):
1098
+ statements.append(self.parse_ligatureCaretByPos_())
1099
+ elif self.cur_token_ == ";":
1100
+ continue
1101
+ else:
1102
+ raise FeatureLibError(
1103
+ "Expected Attach, LigatureCaretByIndex, " "or LigatureCaretByPos",
1104
+ self.cur_token_location_,
1105
+ )
1106
+
1107
+ def parse_table_head_(self, table):
1108
+ statements = table.statements
1109
+ while self.next_token_ != "}" or self.cur_comments_:
1110
+ self.advance_lexer_(comments=True)
1111
+ if self.cur_token_type_ is Lexer.COMMENT:
1112
+ statements.append(
1113
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1114
+ )
1115
+ elif self.is_cur_keyword_("FontRevision"):
1116
+ statements.append(self.parse_FontRevision_())
1117
+ elif self.cur_token_ == ";":
1118
+ continue
1119
+ else:
1120
+ raise FeatureLibError("Expected FontRevision", self.cur_token_location_)
1121
+
1122
+ def parse_table_hhea_(self, table):
1123
+ statements = table.statements
1124
+ fields = ("CaretOffset", "Ascender", "Descender", "LineGap")
1125
+ while self.next_token_ != "}" or self.cur_comments_:
1126
+ self.advance_lexer_(comments=True)
1127
+ if self.cur_token_type_ is Lexer.COMMENT:
1128
+ statements.append(
1129
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1130
+ )
1131
+ elif self.cur_token_type_ is Lexer.NAME and self.cur_token_ in fields:
1132
+ key = self.cur_token_.lower()
1133
+ value = self.expect_number_()
1134
+ statements.append(
1135
+ self.ast.HheaField(key, value, location=self.cur_token_location_)
1136
+ )
1137
+ if self.next_token_ != ";":
1138
+ raise FeatureLibError(
1139
+ "Incomplete statement", self.next_token_location_
1140
+ )
1141
+ elif self.cur_token_ == ";":
1142
+ continue
1143
+ else:
1144
+ raise FeatureLibError(
1145
+ "Expected CaretOffset, Ascender, " "Descender or LineGap",
1146
+ self.cur_token_location_,
1147
+ )
1148
+
1149
+ def parse_table_vhea_(self, table):
1150
+ statements = table.statements
1151
+ fields = ("VertTypoAscender", "VertTypoDescender", "VertTypoLineGap")
1152
+ while self.next_token_ != "}" or self.cur_comments_:
1153
+ self.advance_lexer_(comments=True)
1154
+ if self.cur_token_type_ is Lexer.COMMENT:
1155
+ statements.append(
1156
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1157
+ )
1158
+ elif self.cur_token_type_ is Lexer.NAME and self.cur_token_ in fields:
1159
+ key = self.cur_token_.lower()
1160
+ value = self.expect_number_()
1161
+ statements.append(
1162
+ self.ast.VheaField(key, value, location=self.cur_token_location_)
1163
+ )
1164
+ if self.next_token_ != ";":
1165
+ raise FeatureLibError(
1166
+ "Incomplete statement", self.next_token_location_
1167
+ )
1168
+ elif self.cur_token_ == ";":
1169
+ continue
1170
+ else:
1171
+ raise FeatureLibError(
1172
+ "Expected VertTypoAscender, "
1173
+ "VertTypoDescender or VertTypoLineGap",
1174
+ self.cur_token_location_,
1175
+ )
1176
+
1177
+ def parse_table_name_(self, table):
1178
+ statements = table.statements
1179
+ while self.next_token_ != "}" or self.cur_comments_:
1180
+ self.advance_lexer_(comments=True)
1181
+ if self.cur_token_type_ is Lexer.COMMENT:
1182
+ statements.append(
1183
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1184
+ )
1185
+ elif self.is_cur_keyword_("nameid"):
1186
+ statement = self.parse_nameid_()
1187
+ if statement:
1188
+ statements.append(statement)
1189
+ elif self.cur_token_ == ";":
1190
+ continue
1191
+ else:
1192
+ raise FeatureLibError("Expected nameid", self.cur_token_location_)
1193
+
1194
+ def parse_name_(self):
1195
+ """Parses a name record. See `section 9.e <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.e>`_."""
1196
+ platEncID = None
1197
+ langID = None
1198
+ if self.next_token_type_ in Lexer.NUMBERS:
1199
+ platformID = self.expect_any_number_()
1200
+ location = self.cur_token_location_
1201
+ if platformID not in (1, 3):
1202
+ raise FeatureLibError("Expected platform id 1 or 3", location)
1203
+ if self.next_token_type_ in Lexer.NUMBERS:
1204
+ platEncID = self.expect_any_number_()
1205
+ langID = self.expect_any_number_()
1206
+ else:
1207
+ platformID = 3
1208
+ location = self.cur_token_location_
1209
+
1210
+ if platformID == 1: # Macintosh
1211
+ platEncID = platEncID or 0 # Roman
1212
+ langID = langID or 0 # English
1213
+ else: # 3, Windows
1214
+ platEncID = platEncID or 1 # Unicode
1215
+ langID = langID or 0x0409 # English
1216
+
1217
+ string = self.expect_string_()
1218
+ self.expect_symbol_(";")
1219
+
1220
+ encoding = getEncoding(platformID, platEncID, langID)
1221
+ if encoding is None:
1222
+ raise FeatureLibError("Unsupported encoding", location)
1223
+ unescaped = self.unescape_string_(string, encoding)
1224
+ return platformID, platEncID, langID, unescaped
1225
+
1226
+ def parse_stat_name_(self):
1227
+ platEncID = None
1228
+ langID = None
1229
+ if self.next_token_type_ in Lexer.NUMBERS:
1230
+ platformID = self.expect_any_number_()
1231
+ location = self.cur_token_location_
1232
+ if platformID not in (1, 3):
1233
+ raise FeatureLibError("Expected platform id 1 or 3", location)
1234
+ if self.next_token_type_ in Lexer.NUMBERS:
1235
+ platEncID = self.expect_any_number_()
1236
+ langID = self.expect_any_number_()
1237
+ else:
1238
+ platformID = 3
1239
+ location = self.cur_token_location_
1240
+
1241
+ if platformID == 1: # Macintosh
1242
+ platEncID = platEncID or 0 # Roman
1243
+ langID = langID or 0 # English
1244
+ else: # 3, Windows
1245
+ platEncID = platEncID or 1 # Unicode
1246
+ langID = langID or 0x0409 # English
1247
+
1248
+ string = self.expect_string_()
1249
+ encoding = getEncoding(platformID, platEncID, langID)
1250
+ if encoding is None:
1251
+ raise FeatureLibError("Unsupported encoding", location)
1252
+ unescaped = self.unescape_string_(string, encoding)
1253
+ return platformID, platEncID, langID, unescaped
1254
+
1255
+ def parse_nameid_(self):
1256
+ assert self.cur_token_ == "nameid", self.cur_token_
1257
+ location, nameID = self.cur_token_location_, self.expect_any_number_()
1258
+ if nameID > 32767:
1259
+ raise FeatureLibError(
1260
+ "Name id value cannot be greater than 32767", self.cur_token_location_
1261
+ )
1262
+ platformID, platEncID, langID, string = self.parse_name_()
1263
+ return self.ast.NameRecord(
1264
+ nameID, platformID, platEncID, langID, string, location=location
1265
+ )
1266
+
1267
+ def unescape_string_(self, string, encoding):
1268
+ if encoding == "utf_16_be":
1269
+ s = re.sub(r"\\[0-9a-fA-F]{4}", self.unescape_unichr_, string)
1270
+ else:
1271
+ unescape = lambda m: self.unescape_byte_(m, encoding)
1272
+ s = re.sub(r"\\[0-9a-fA-F]{2}", unescape, string)
1273
+ # We now have a Unicode string, but it might contain surrogate pairs.
1274
+ # We convert surrogates to actual Unicode by round-tripping through
1275
+ # Python's UTF-16 codec in a special mode.
1276
+ utf16 = tobytes(s, "utf_16_be", "surrogatepass")
1277
+ return tostr(utf16, "utf_16_be")
1278
+
1279
+ @staticmethod
1280
+ def unescape_unichr_(match):
1281
+ n = match.group(0)[1:]
1282
+ return chr(int(n, 16))
1283
+
1284
+ @staticmethod
1285
+ def unescape_byte_(match, encoding):
1286
+ n = match.group(0)[1:]
1287
+ return bytechr(int(n, 16)).decode(encoding)
1288
+
1289
+ def find_previous(self, statements, class_):
1290
+ for previous in reversed(statements):
1291
+ if isinstance(previous, self.ast.Comment):
1292
+ continue
1293
+ elif isinstance(previous, class_):
1294
+ return previous
1295
+ else:
1296
+ # If we find something that doesn't match what we're looking
1297
+ # for, and isn't a comment, fail
1298
+ return None
1299
+ # Out of statements to look at
1300
+ return None
1301
+
1302
+ def parse_table_BASE_(self, table):
1303
+ statements = table.statements
1304
+ while self.next_token_ != "}" or self.cur_comments_:
1305
+ self.advance_lexer_(comments=True)
1306
+ if self.cur_token_type_ is Lexer.COMMENT:
1307
+ statements.append(
1308
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1309
+ )
1310
+ elif self.is_cur_keyword_("HorizAxis.BaseTagList"):
1311
+ horiz_bases = self.parse_base_tag_list_()
1312
+ elif self.is_cur_keyword_("HorizAxis.BaseScriptList"):
1313
+ horiz_scripts = self.parse_base_script_list_(len(horiz_bases))
1314
+ statements.append(
1315
+ self.ast.BaseAxis(
1316
+ horiz_bases,
1317
+ horiz_scripts,
1318
+ False,
1319
+ location=self.cur_token_location_,
1320
+ )
1321
+ )
1322
+ elif self.is_cur_keyword_("HorizAxis.MinMax"):
1323
+ base_script_list = self.find_previous(statements, ast.BaseAxis)
1324
+ if base_script_list is None:
1325
+ raise FeatureLibError(
1326
+ "MinMax must be preceded by BaseScriptList",
1327
+ self.cur_token_location_,
1328
+ )
1329
+ if base_script_list.vertical:
1330
+ raise FeatureLibError(
1331
+ "HorizAxis.MinMax must be preceded by HorizAxis statements",
1332
+ self.cur_token_location_,
1333
+ )
1334
+ base_script_list.minmax.append(self.parse_base_minmax_())
1335
+ elif self.is_cur_keyword_("VertAxis.BaseTagList"):
1336
+ vert_bases = self.parse_base_tag_list_()
1337
+ elif self.is_cur_keyword_("VertAxis.BaseScriptList"):
1338
+ vert_scripts = self.parse_base_script_list_(len(vert_bases))
1339
+ statements.append(
1340
+ self.ast.BaseAxis(
1341
+ vert_bases,
1342
+ vert_scripts,
1343
+ True,
1344
+ location=self.cur_token_location_,
1345
+ )
1346
+ )
1347
+ elif self.is_cur_keyword_("VertAxis.MinMax"):
1348
+ base_script_list = self.find_previous(statements, ast.BaseAxis)
1349
+ if base_script_list is None:
1350
+ raise FeatureLibError(
1351
+ "MinMax must be preceded by BaseScriptList",
1352
+ self.cur_token_location_,
1353
+ )
1354
+ if not base_script_list.vertical:
1355
+ raise FeatureLibError(
1356
+ "VertAxis.MinMax must be preceded by VertAxis statements",
1357
+ self.cur_token_location_,
1358
+ )
1359
+ base_script_list.minmax.append(self.parse_base_minmax_())
1360
+ elif self.cur_token_ == ";":
1361
+ continue
1362
+
1363
+ def parse_table_OS_2_(self, table):
1364
+ statements = table.statements
1365
+ numbers = (
1366
+ "FSType",
1367
+ "TypoAscender",
1368
+ "TypoDescender",
1369
+ "TypoLineGap",
1370
+ "winAscent",
1371
+ "winDescent",
1372
+ "XHeight",
1373
+ "CapHeight",
1374
+ "WeightClass",
1375
+ "WidthClass",
1376
+ "LowerOpSize",
1377
+ "UpperOpSize",
1378
+ )
1379
+ ranges = ("UnicodeRange", "CodePageRange")
1380
+ while self.next_token_ != "}" or self.cur_comments_:
1381
+ self.advance_lexer_(comments=True)
1382
+ if self.cur_token_type_ is Lexer.COMMENT:
1383
+ statements.append(
1384
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1385
+ )
1386
+ elif self.cur_token_type_ is Lexer.NAME:
1387
+ key = self.cur_token_.lower()
1388
+ value = None
1389
+ if self.cur_token_ in numbers:
1390
+ value = self.expect_number_()
1391
+ elif self.is_cur_keyword_("Panose"):
1392
+ value = []
1393
+ for i in range(10):
1394
+ value.append(self.expect_number_())
1395
+ elif self.cur_token_ in ranges:
1396
+ value = []
1397
+ while self.next_token_ != ";":
1398
+ value.append(self.expect_number_())
1399
+ elif self.is_cur_keyword_("Vendor"):
1400
+ value = self.expect_string_()
1401
+ statements.append(
1402
+ self.ast.OS2Field(key, value, location=self.cur_token_location_)
1403
+ )
1404
+ elif self.cur_token_ == ";":
1405
+ continue
1406
+
1407
+ def parse_STAT_ElidedFallbackName(self):
1408
+ assert self.is_cur_keyword_("ElidedFallbackName")
1409
+ self.expect_symbol_("{")
1410
+ names = []
1411
+ while self.next_token_ != "}" or self.cur_comments_:
1412
+ self.advance_lexer_()
1413
+ if self.is_cur_keyword_("name"):
1414
+ platformID, platEncID, langID, string = self.parse_stat_name_()
1415
+ nameRecord = self.ast.STATNameStatement(
1416
+ "stat",
1417
+ platformID,
1418
+ platEncID,
1419
+ langID,
1420
+ string,
1421
+ location=self.cur_token_location_,
1422
+ )
1423
+ names.append(nameRecord)
1424
+ else:
1425
+ if self.cur_token_ != ";":
1426
+ raise FeatureLibError(
1427
+ f"Unexpected token {self.cur_token_} " f"in ElidedFallbackName",
1428
+ self.cur_token_location_,
1429
+ )
1430
+ self.expect_symbol_("}")
1431
+ if not names:
1432
+ raise FeatureLibError('Expected "name"', self.cur_token_location_)
1433
+ return names
1434
+
1435
+ def parse_STAT_design_axis(self):
1436
+ assert self.is_cur_keyword_("DesignAxis")
1437
+ names = []
1438
+ axisTag = self.expect_tag_()
1439
+ if (
1440
+ axisTag not in ("ital", "opsz", "slnt", "wdth", "wght")
1441
+ and not axisTag.isupper()
1442
+ ):
1443
+ log.warning(f"Unregistered axis tag {axisTag} should be uppercase.")
1444
+ axisOrder = self.expect_number_()
1445
+ self.expect_symbol_("{")
1446
+ while self.next_token_ != "}" or self.cur_comments_:
1447
+ self.advance_lexer_()
1448
+ if self.cur_token_type_ is Lexer.COMMENT:
1449
+ continue
1450
+ elif self.is_cur_keyword_("name"):
1451
+ location = self.cur_token_location_
1452
+ platformID, platEncID, langID, string = self.parse_stat_name_()
1453
+ name = self.ast.STATNameStatement(
1454
+ "stat", platformID, platEncID, langID, string, location=location
1455
+ )
1456
+ names.append(name)
1457
+ elif self.cur_token_ == ";":
1458
+ continue
1459
+ else:
1460
+ raise FeatureLibError(
1461
+ f'Expected "name", got {self.cur_token_}', self.cur_token_location_
1462
+ )
1463
+
1464
+ self.expect_symbol_("}")
1465
+ return self.ast.STATDesignAxisStatement(
1466
+ axisTag, axisOrder, names, self.cur_token_location_
1467
+ )
1468
+
1469
+ def parse_STAT_axis_value_(self):
1470
+ assert self.is_cur_keyword_("AxisValue")
1471
+ self.expect_symbol_("{")
1472
+ locations = []
1473
+ names = []
1474
+ flags = 0
1475
+ while self.next_token_ != "}" or self.cur_comments_:
1476
+ self.advance_lexer_(comments=True)
1477
+ if self.cur_token_type_ is Lexer.COMMENT:
1478
+ continue
1479
+ elif self.is_cur_keyword_("name"):
1480
+ location = self.cur_token_location_
1481
+ platformID, platEncID, langID, string = self.parse_stat_name_()
1482
+ name = self.ast.STATNameStatement(
1483
+ "stat", platformID, platEncID, langID, string, location=location
1484
+ )
1485
+ names.append(name)
1486
+ elif self.is_cur_keyword_("location"):
1487
+ location = self.parse_STAT_location()
1488
+ locations.append(location)
1489
+ elif self.is_cur_keyword_("flag"):
1490
+ flags = self.expect_stat_flags()
1491
+ elif self.cur_token_ == ";":
1492
+ continue
1493
+ else:
1494
+ raise FeatureLibError(
1495
+ f"Unexpected token {self.cur_token_} " f"in AxisValue",
1496
+ self.cur_token_location_,
1497
+ )
1498
+ self.expect_symbol_("}")
1499
+ if not names:
1500
+ raise FeatureLibError('Expected "Axis Name"', self.cur_token_location_)
1501
+ if not locations:
1502
+ raise FeatureLibError('Expected "Axis location"', self.cur_token_location_)
1503
+ if len(locations) > 1:
1504
+ for location in locations:
1505
+ if len(location.values) > 1:
1506
+ raise FeatureLibError(
1507
+ "Only one value is allowed in a "
1508
+ "Format 4 Axis Value Record, but "
1509
+ f"{len(location.values)} were found.",
1510
+ self.cur_token_location_,
1511
+ )
1512
+ format4_tags = []
1513
+ for location in locations:
1514
+ tag = location.tag
1515
+ if tag in format4_tags:
1516
+ raise FeatureLibError(
1517
+ f"Axis tag {tag} already " "defined.", self.cur_token_location_
1518
+ )
1519
+ format4_tags.append(tag)
1520
+
1521
+ return self.ast.STATAxisValueStatement(
1522
+ names, locations, flags, self.cur_token_location_
1523
+ )
1524
+
1525
+ def parse_STAT_location(self):
1526
+ values = []
1527
+ tag = self.expect_tag_()
1528
+ if len(tag.strip()) != 4:
1529
+ raise FeatureLibError(
1530
+ f"Axis tag {self.cur_token_} must be 4 " "characters",
1531
+ self.cur_token_location_,
1532
+ )
1533
+
1534
+ while self.next_token_ != ";":
1535
+ if self.next_token_type_ is Lexer.FLOAT:
1536
+ value = self.expect_float_()
1537
+ values.append(value)
1538
+ elif self.next_token_type_ is Lexer.NUMBER:
1539
+ value = self.expect_number_()
1540
+ values.append(value)
1541
+ else:
1542
+ raise FeatureLibError(
1543
+ f'Unexpected value "{self.next_token_}". '
1544
+ "Expected integer or float.",
1545
+ self.next_token_location_,
1546
+ )
1547
+ if len(values) == 3:
1548
+ nominal, min_val, max_val = values
1549
+ if nominal < min_val or nominal > max_val:
1550
+ raise FeatureLibError(
1551
+ f"Default value {nominal} is outside "
1552
+ f"of specified range "
1553
+ f"{min_val}-{max_val}.",
1554
+ self.next_token_location_,
1555
+ )
1556
+ return self.ast.AxisValueLocationStatement(tag, values)
1557
+
1558
+ def parse_table_STAT_(self, table):
1559
+ statements = table.statements
1560
+ design_axes = []
1561
+ while self.next_token_ != "}" or self.cur_comments_:
1562
+ self.advance_lexer_(comments=True)
1563
+ if self.cur_token_type_ is Lexer.COMMENT:
1564
+ statements.append(
1565
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1566
+ )
1567
+ elif self.cur_token_type_ is Lexer.NAME:
1568
+ if self.is_cur_keyword_("ElidedFallbackName"):
1569
+ names = self.parse_STAT_ElidedFallbackName()
1570
+ statements.append(self.ast.ElidedFallbackName(names))
1571
+ elif self.is_cur_keyword_("ElidedFallbackNameID"):
1572
+ value = self.expect_number_()
1573
+ statements.append(self.ast.ElidedFallbackNameID(value))
1574
+ self.expect_symbol_(";")
1575
+ elif self.is_cur_keyword_("DesignAxis"):
1576
+ designAxis = self.parse_STAT_design_axis()
1577
+ design_axes.append(designAxis.tag)
1578
+ statements.append(designAxis)
1579
+ self.expect_symbol_(";")
1580
+ elif self.is_cur_keyword_("AxisValue"):
1581
+ axisValueRecord = self.parse_STAT_axis_value_()
1582
+ for location in axisValueRecord.locations:
1583
+ if location.tag not in design_axes:
1584
+ # Tag must be defined in a DesignAxis before it
1585
+ # can be referenced
1586
+ raise FeatureLibError(
1587
+ "DesignAxis not defined for " f"{location.tag}.",
1588
+ self.cur_token_location_,
1589
+ )
1590
+ statements.append(axisValueRecord)
1591
+ self.expect_symbol_(";")
1592
+ else:
1593
+ raise FeatureLibError(
1594
+ f"Unexpected token {self.cur_token_}", self.cur_token_location_
1595
+ )
1596
+ elif self.cur_token_ == ";":
1597
+ continue
1598
+
1599
+ def parse_base_tag_list_(self):
1600
+ # Parses BASE table entries. (See `section 9.a <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.a>`_)
1601
+ assert self.cur_token_ in (
1602
+ "HorizAxis.BaseTagList",
1603
+ "VertAxis.BaseTagList",
1604
+ ), self.cur_token_
1605
+ bases = []
1606
+ while self.next_token_ != ";":
1607
+ bases.append(self.expect_script_tag_())
1608
+ self.expect_symbol_(";")
1609
+ return bases
1610
+
1611
+ def parse_base_script_list_(self, count):
1612
+ assert self.cur_token_ in (
1613
+ "HorizAxis.BaseScriptList",
1614
+ "VertAxis.BaseScriptList",
1615
+ ), self.cur_token_
1616
+ scripts = [self.parse_base_script_record_(count)]
1617
+ while self.next_token_ == ",":
1618
+ self.expect_symbol_(",")
1619
+ scripts.append(self.parse_base_script_record_(count))
1620
+ self.expect_symbol_(";")
1621
+ return scripts
1622
+
1623
+ def parse_base_script_record_(self, count):
1624
+ script_tag = self.expect_script_tag_()
1625
+ base_tag = self.expect_script_tag_()
1626
+ coords = [self.expect_number_() for i in range(count)]
1627
+ return script_tag, base_tag, coords
1628
+
1629
+ def parse_base_minmax_(self):
1630
+ script_tag = self.expect_script_tag_()
1631
+ language = self.expect_language_tag_()
1632
+ min_coord = self.expect_number_()
1633
+ self.advance_lexer_()
1634
+ if not (self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == ","):
1635
+ raise FeatureLibError(
1636
+ "Expected a comma between min and max coordinates",
1637
+ self.cur_token_location_,
1638
+ )
1639
+ max_coord = self.expect_number_()
1640
+ if self.next_token_ == ",": # feature tag...
1641
+ raise FeatureLibError(
1642
+ "Feature tags are not yet supported in BASE table",
1643
+ self.cur_token_location_,
1644
+ )
1645
+
1646
+ return script_tag, language, min_coord, max_coord
1647
+
1648
+ def parse_device_(self):
1649
+ result = None
1650
+ self.expect_symbol_("<")
1651
+ self.expect_keyword_("device")
1652
+ if self.next_token_ == "NULL":
1653
+ self.expect_keyword_("NULL")
1654
+ else:
1655
+ result = [(self.expect_number_(), self.expect_number_())]
1656
+ while self.next_token_ == ",":
1657
+ self.expect_symbol_(",")
1658
+ result.append((self.expect_number_(), self.expect_number_()))
1659
+ result = tuple(result) # make it hashable
1660
+ self.expect_symbol_(">")
1661
+ return result
1662
+
1663
+ def is_next_value_(self):
1664
+ return (
1665
+ self.next_token_type_ is Lexer.NUMBER
1666
+ or self.next_token_ == "<"
1667
+ or self.next_token_ == "("
1668
+ )
1669
+
1670
+ def parse_valuerecord_(self, vertical):
1671
+ if (
1672
+ self.next_token_type_ is Lexer.SYMBOL and self.next_token_ == "("
1673
+ ) or self.next_token_type_ is Lexer.NUMBER:
1674
+ number, location = (
1675
+ self.expect_number_(variable=True),
1676
+ self.cur_token_location_,
1677
+ )
1678
+ if vertical:
1679
+ val = self.ast.ValueRecord(
1680
+ yAdvance=number, vertical=vertical, location=location
1681
+ )
1682
+ else:
1683
+ val = self.ast.ValueRecord(
1684
+ xAdvance=number, vertical=vertical, location=location
1685
+ )
1686
+ return val
1687
+ self.expect_symbol_("<")
1688
+ location = self.cur_token_location_
1689
+ if self.next_token_type_ is Lexer.NAME:
1690
+ name = self.expect_name_()
1691
+ if name == "NULL":
1692
+ self.expect_symbol_(">")
1693
+ return self.ast.ValueRecord()
1694
+ vrd = self.valuerecords_.resolve(name)
1695
+ if vrd is None:
1696
+ raise FeatureLibError(
1697
+ 'Unknown valueRecordDef "%s"' % name, self.cur_token_location_
1698
+ )
1699
+ value = vrd.value
1700
+ xPlacement, yPlacement = (value.xPlacement, value.yPlacement)
1701
+ xAdvance, yAdvance = (value.xAdvance, value.yAdvance)
1702
+ else:
1703
+ xPlacement, yPlacement, xAdvance, yAdvance = (
1704
+ self.expect_number_(variable=True),
1705
+ self.expect_number_(variable=True),
1706
+ self.expect_number_(variable=True),
1707
+ self.expect_number_(variable=True),
1708
+ )
1709
+
1710
+ if self.next_token_ == "<":
1711
+ xPlaDevice, yPlaDevice, xAdvDevice, yAdvDevice = (
1712
+ self.parse_device_(),
1713
+ self.parse_device_(),
1714
+ self.parse_device_(),
1715
+ self.parse_device_(),
1716
+ )
1717
+ allDeltas = sorted(
1718
+ [
1719
+ delta
1720
+ for size, delta in (xPlaDevice if xPlaDevice else ())
1721
+ + (yPlaDevice if yPlaDevice else ())
1722
+ + (xAdvDevice if xAdvDevice else ())
1723
+ + (yAdvDevice if yAdvDevice else ())
1724
+ ]
1725
+ )
1726
+ if allDeltas[0] < -128 or allDeltas[-1] > 127:
1727
+ raise FeatureLibError(
1728
+ "Device value out of valid range (-128..127)",
1729
+ self.cur_token_location_,
1730
+ )
1731
+ else:
1732
+ xPlaDevice, yPlaDevice, xAdvDevice, yAdvDevice = (None, None, None, None)
1733
+
1734
+ self.expect_symbol_(">")
1735
+ return self.ast.ValueRecord(
1736
+ xPlacement,
1737
+ yPlacement,
1738
+ xAdvance,
1739
+ yAdvance,
1740
+ xPlaDevice,
1741
+ yPlaDevice,
1742
+ xAdvDevice,
1743
+ yAdvDevice,
1744
+ vertical=vertical,
1745
+ location=location,
1746
+ )
1747
+
1748
+ def parse_valuerecord_definition_(self, vertical):
1749
+ # Parses a named value record definition. (See section `2.e.v <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#2.e.v>`_)
1750
+ assert self.is_cur_keyword_("valueRecordDef")
1751
+ location = self.cur_token_location_
1752
+ value = self.parse_valuerecord_(vertical)
1753
+ name = self.expect_name_()
1754
+ self.expect_symbol_(";")
1755
+ vrd = self.ast.ValueRecordDefinition(name, value, location=location)
1756
+ self.valuerecords_.define(name, vrd)
1757
+ return vrd
1758
+
1759
+ def parse_languagesystem_(self):
1760
+ assert self.cur_token_ == "languagesystem"
1761
+ location = self.cur_token_location_
1762
+ script = self.expect_script_tag_()
1763
+ language = self.expect_language_tag_()
1764
+ self.expect_symbol_(";")
1765
+ return self.ast.LanguageSystemStatement(script, language, location=location)
1766
+
1767
+ def parse_feature_block_(self, variation=False):
1768
+ if variation:
1769
+ assert self.cur_token_ == "variation"
1770
+ else:
1771
+ assert self.cur_token_ == "feature"
1772
+ location = self.cur_token_location_
1773
+ tag = self.expect_tag_()
1774
+ vertical = tag in {"vkrn", "vpal", "vhal", "valt"}
1775
+
1776
+ stylisticset = None
1777
+ cv_feature = None
1778
+ size_feature = False
1779
+ if tag in self.SS_FEATURE_TAGS:
1780
+ stylisticset = tag
1781
+ elif tag in self.CV_FEATURE_TAGS:
1782
+ cv_feature = tag
1783
+ elif tag == "size":
1784
+ size_feature = True
1785
+
1786
+ if variation:
1787
+ conditionset = self.expect_name_()
1788
+
1789
+ use_extension = False
1790
+ if self.next_token_ == "useExtension":
1791
+ self.expect_keyword_("useExtension")
1792
+ use_extension = True
1793
+
1794
+ if variation:
1795
+ block = self.ast.VariationBlock(
1796
+ tag, conditionset, use_extension=use_extension, location=location
1797
+ )
1798
+ else:
1799
+ block = self.ast.FeatureBlock(
1800
+ tag, use_extension=use_extension, location=location
1801
+ )
1802
+ self.parse_block_(block, vertical, stylisticset, size_feature, cv_feature)
1803
+ return block
1804
+
1805
+ def parse_feature_reference_(self):
1806
+ assert self.cur_token_ == "feature", self.cur_token_
1807
+ location = self.cur_token_location_
1808
+ featureName = self.expect_tag_()
1809
+ self.expect_symbol_(";")
1810
+ return self.ast.FeatureReferenceStatement(featureName, location=location)
1811
+
1812
+ def parse_featureNames_(self, tag):
1813
+ """Parses a ``featureNames`` statement found in stylistic set features.
1814
+ See section `8.c <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#8.c>`_.
1815
+ """
1816
+ assert self.cur_token_ == "featureNames", self.cur_token_
1817
+ block = self.ast.NestedBlock(
1818
+ tag, self.cur_token_, location=self.cur_token_location_
1819
+ )
1820
+ self.expect_symbol_("{")
1821
+ for symtab in self.symbol_tables_:
1822
+ symtab.enter_scope()
1823
+ while self.next_token_ != "}" or self.cur_comments_:
1824
+ self.advance_lexer_(comments=True)
1825
+ if self.cur_token_type_ is Lexer.COMMENT:
1826
+ block.statements.append(
1827
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1828
+ )
1829
+ elif self.is_cur_keyword_("name"):
1830
+ location = self.cur_token_location_
1831
+ platformID, platEncID, langID, string = self.parse_name_()
1832
+ block.statements.append(
1833
+ self.ast.FeatureNameStatement(
1834
+ tag, platformID, platEncID, langID, string, location=location
1835
+ )
1836
+ )
1837
+ elif self.cur_token_ == ";":
1838
+ continue
1839
+ else:
1840
+ raise FeatureLibError('Expected "name"', self.cur_token_location_)
1841
+ self.expect_symbol_("}")
1842
+ for symtab in self.symbol_tables_:
1843
+ symtab.exit_scope()
1844
+ self.expect_symbol_(";")
1845
+ return block
1846
+
1847
+ def parse_cvParameters_(self, tag):
1848
+ # Parses a ``cvParameters`` block found in Character Variant features.
1849
+ # See section `8.d <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#8.d>`_.
1850
+ assert self.cur_token_ == "cvParameters", self.cur_token_
1851
+ block = self.ast.NestedBlock(
1852
+ tag, self.cur_token_, location=self.cur_token_location_
1853
+ )
1854
+ self.expect_symbol_("{")
1855
+ for symtab in self.symbol_tables_:
1856
+ symtab.enter_scope()
1857
+
1858
+ statements = block.statements
1859
+ while self.next_token_ != "}" or self.cur_comments_:
1860
+ self.advance_lexer_(comments=True)
1861
+ if self.cur_token_type_ is Lexer.COMMENT:
1862
+ statements.append(
1863
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1864
+ )
1865
+ elif self.is_cur_keyword_(
1866
+ {
1867
+ "FeatUILabelNameID",
1868
+ "FeatUITooltipTextNameID",
1869
+ "SampleTextNameID",
1870
+ "ParamUILabelNameID",
1871
+ }
1872
+ ):
1873
+ statements.append(self.parse_cvNameIDs_(tag, self.cur_token_))
1874
+ elif self.is_cur_keyword_("Character"):
1875
+ statements.append(self.parse_cvCharacter_(tag))
1876
+ elif self.cur_token_ == ";":
1877
+ continue
1878
+ else:
1879
+ raise FeatureLibError(
1880
+ "Expected statement: got {} {}".format(
1881
+ self.cur_token_type_, self.cur_token_
1882
+ ),
1883
+ self.cur_token_location_,
1884
+ )
1885
+
1886
+ self.expect_symbol_("}")
1887
+ for symtab in self.symbol_tables_:
1888
+ symtab.exit_scope()
1889
+ self.expect_symbol_(";")
1890
+ return block
1891
+
1892
+ def parse_cvNameIDs_(self, tag, block_name):
1893
+ assert self.cur_token_ == block_name, self.cur_token_
1894
+ block = self.ast.NestedBlock(tag, block_name, location=self.cur_token_location_)
1895
+ self.expect_symbol_("{")
1896
+ for symtab in self.symbol_tables_:
1897
+ symtab.enter_scope()
1898
+ while self.next_token_ != "}" or self.cur_comments_:
1899
+ self.advance_lexer_(comments=True)
1900
+ if self.cur_token_type_ is Lexer.COMMENT:
1901
+ block.statements.append(
1902
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
1903
+ )
1904
+ elif self.is_cur_keyword_("name"):
1905
+ location = self.cur_token_location_
1906
+ platformID, platEncID, langID, string = self.parse_name_()
1907
+ block.statements.append(
1908
+ self.ast.CVParametersNameStatement(
1909
+ tag,
1910
+ platformID,
1911
+ platEncID,
1912
+ langID,
1913
+ string,
1914
+ block_name,
1915
+ location=location,
1916
+ )
1917
+ )
1918
+ elif self.cur_token_ == ";":
1919
+ continue
1920
+ else:
1921
+ raise FeatureLibError('Expected "name"', self.cur_token_location_)
1922
+ self.expect_symbol_("}")
1923
+ for symtab in self.symbol_tables_:
1924
+ symtab.exit_scope()
1925
+ self.expect_symbol_(";")
1926
+ return block
1927
+
1928
+ def parse_cvCharacter_(self, tag):
1929
+ assert self.cur_token_ == "Character", self.cur_token_
1930
+ location, character = self.cur_token_location_, self.expect_any_number_()
1931
+ self.expect_symbol_(";")
1932
+ if not (0xFFFFFF >= character >= 0):
1933
+ raise FeatureLibError(
1934
+ "Character value must be between "
1935
+ "{:#x} and {:#x}".format(0, 0xFFFFFF),
1936
+ location,
1937
+ )
1938
+ return self.ast.CharacterStatement(character, tag, location=location)
1939
+
1940
+ def parse_FontRevision_(self):
1941
+ # Parses a ``FontRevision`` statement found in the head table. See
1942
+ # `section 9.c <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.c>`_.
1943
+ assert self.cur_token_ == "FontRevision", self.cur_token_
1944
+ location, version = self.cur_token_location_, self.expect_float_()
1945
+ self.expect_symbol_(";")
1946
+ if version <= 0:
1947
+ raise FeatureLibError("Font revision numbers must be positive", location)
1948
+ return self.ast.FontRevisionStatement(version, location=location)
1949
+
1950
+ def parse_conditionset_(self):
1951
+ name = self.expect_name_()
1952
+
1953
+ conditions = {}
1954
+ self.expect_symbol_("{")
1955
+
1956
+ while self.next_token_ != "}":
1957
+ self.advance_lexer_()
1958
+ if self.cur_token_type_ is not Lexer.NAME:
1959
+ raise FeatureLibError("Expected an axis name", self.cur_token_location_)
1960
+
1961
+ axis = self.cur_token_
1962
+ if axis in conditions:
1963
+ raise FeatureLibError(
1964
+ f"Repeated condition for axis {axis}", self.cur_token_location_
1965
+ )
1966
+
1967
+ if self.next_token_type_ is Lexer.FLOAT:
1968
+ min_value = self.expect_float_()
1969
+ elif self.next_token_type_ is Lexer.NUMBER:
1970
+ min_value = self.expect_number_(variable=False)
1971
+
1972
+ if self.next_token_type_ is Lexer.FLOAT:
1973
+ max_value = self.expect_float_()
1974
+ elif self.next_token_type_ is Lexer.NUMBER:
1975
+ max_value = self.expect_number_(variable=False)
1976
+ self.expect_symbol_(";")
1977
+
1978
+ conditions[axis] = (min_value, max_value)
1979
+
1980
+ self.expect_symbol_("}")
1981
+
1982
+ finalname = self.expect_name_()
1983
+ if finalname != name:
1984
+ raise FeatureLibError('Expected "%s"' % name, self.cur_token_location_)
1985
+ return self.ast.ConditionsetStatement(name, conditions)
1986
+
1987
+ def parse_block_(
1988
+ self, block, vertical, stylisticset=None, size_feature=False, cv_feature=None
1989
+ ):
1990
+ self.expect_symbol_("{")
1991
+ for symtab in self.symbol_tables_:
1992
+ symtab.enter_scope()
1993
+
1994
+ statements = block.statements
1995
+ while self.next_token_ != "}" or self.cur_comments_:
1996
+ self.advance_lexer_(comments=True)
1997
+ if self.cur_token_type_ is Lexer.COMMENT:
1998
+ statements.append(
1999
+ self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
2000
+ )
2001
+ elif self.cur_token_type_ is Lexer.GLYPHCLASS:
2002
+ statements.append(self.parse_glyphclass_definition_())
2003
+ elif self.is_cur_keyword_("anchorDef"):
2004
+ statements.append(self.parse_anchordef_())
2005
+ elif self.is_cur_keyword_({"enum", "enumerate"}):
2006
+ statements.append(self.parse_enumerate_(vertical=vertical))
2007
+ elif self.is_cur_keyword_("feature"):
2008
+ statements.append(self.parse_feature_reference_())
2009
+ elif self.is_cur_keyword_("ignore"):
2010
+ statements.append(self.parse_ignore_())
2011
+ elif self.is_cur_keyword_("language"):
2012
+ statements.append(self.parse_language_())
2013
+ elif self.is_cur_keyword_("lookup"):
2014
+ statements.append(self.parse_lookup_(vertical))
2015
+ elif self.is_cur_keyword_("lookupflag"):
2016
+ statements.append(self.parse_lookupflag_())
2017
+ elif self.is_cur_keyword_("markClass"):
2018
+ statements.append(self.parse_markClass_())
2019
+ elif self.is_cur_keyword_({"pos", "position"}):
2020
+ statements.append(
2021
+ self.parse_position_(enumerated=False, vertical=vertical)
2022
+ )
2023
+ elif self.is_cur_keyword_("script"):
2024
+ statements.append(self.parse_script_())
2025
+ elif self.is_cur_keyword_({"sub", "substitute", "rsub", "reversesub"}):
2026
+ statements.append(self.parse_substitute_())
2027
+ elif self.is_cur_keyword_("subtable"):
2028
+ statements.append(self.parse_subtable_())
2029
+ elif self.is_cur_keyword_("valueRecordDef"):
2030
+ statements.append(self.parse_valuerecord_definition_(vertical))
2031
+ elif stylisticset and self.is_cur_keyword_("featureNames"):
2032
+ statements.append(self.parse_featureNames_(stylisticset))
2033
+ elif cv_feature and self.is_cur_keyword_("cvParameters"):
2034
+ statements.append(self.parse_cvParameters_(cv_feature))
2035
+ elif size_feature and self.is_cur_keyword_("parameters"):
2036
+ statements.append(self.parse_size_parameters_())
2037
+ elif size_feature and self.is_cur_keyword_("sizemenuname"):
2038
+ statements.append(self.parse_size_menuname_())
2039
+ elif (
2040
+ self.cur_token_type_ is Lexer.NAME
2041
+ and self.cur_token_ in self.extensions
2042
+ ):
2043
+ statements.append(self.extensions[self.cur_token_](self))
2044
+ elif self.cur_token_ == ";":
2045
+ continue
2046
+ else:
2047
+ raise FeatureLibError(
2048
+ "Expected glyph class definition or statement: got {} {}".format(
2049
+ self.cur_token_type_, self.cur_token_
2050
+ ),
2051
+ self.cur_token_location_,
2052
+ )
2053
+
2054
+ self.expect_symbol_("}")
2055
+ for symtab in self.symbol_tables_:
2056
+ symtab.exit_scope()
2057
+
2058
+ name = self.expect_name_()
2059
+ if name != block.name.strip():
2060
+ raise FeatureLibError(
2061
+ 'Expected "%s"' % block.name.strip(), self.cur_token_location_
2062
+ )
2063
+ self.expect_symbol_(";")
2064
+
2065
+ def is_cur_keyword_(self, k):
2066
+ if self.cur_token_type_ is Lexer.NAME:
2067
+ if isinstance(k, type("")): # basestring is gone in Python3
2068
+ return self.cur_token_ == k
2069
+ else:
2070
+ return self.cur_token_ in k
2071
+ return False
2072
+
2073
+ def expect_class_name_(self):
2074
+ self.advance_lexer_()
2075
+ if self.cur_token_type_ is not Lexer.GLYPHCLASS:
2076
+ raise FeatureLibError("Expected @NAME", self.cur_token_location_)
2077
+ return self.cur_token_
2078
+
2079
+ def expect_cid_(self):
2080
+ self.advance_lexer_()
2081
+ if self.cur_token_type_ is Lexer.CID:
2082
+ return self.cur_token_
2083
+ raise FeatureLibError("Expected a CID", self.cur_token_location_)
2084
+
2085
+ def expect_filename_(self):
2086
+ self.advance_lexer_()
2087
+ if self.cur_token_type_ is not Lexer.FILENAME:
2088
+ raise FeatureLibError("Expected file name", self.cur_token_location_)
2089
+ return self.cur_token_
2090
+
2091
+ def expect_glyph_(self):
2092
+ self.advance_lexer_()
2093
+ if self.cur_token_type_ is Lexer.NAME:
2094
+ return self.cur_token_.lstrip("\\")
2095
+ elif self.cur_token_type_ is Lexer.CID:
2096
+ return "cid%05d" % self.cur_token_
2097
+ raise FeatureLibError("Expected a glyph name or CID", self.cur_token_location_)
2098
+
2099
+ def check_glyph_name_in_glyph_set(self, *names):
2100
+ """Adds a glyph name (just `start`) or glyph names of a
2101
+ range (`start` and `end`) which are not in the glyph set
2102
+ to the "missing list" for future error reporting.
2103
+
2104
+ If no glyph set is present, does nothing.
2105
+ """
2106
+ if self.glyphNames_:
2107
+ for name in names:
2108
+ if name in self.glyphNames_:
2109
+ continue
2110
+ if name not in self.missing:
2111
+ self.missing[name] = self.cur_token_location_
2112
+
2113
+ def expect_markClass_reference_(self):
2114
+ name = self.expect_class_name_()
2115
+ mc = self.glyphclasses_.resolve(name)
2116
+ if mc is None:
2117
+ raise FeatureLibError(
2118
+ "Unknown markClass @%s" % name, self.cur_token_location_
2119
+ )
2120
+ if not isinstance(mc, self.ast.MarkClass):
2121
+ raise FeatureLibError(
2122
+ "@%s is not a markClass" % name, self.cur_token_location_
2123
+ )
2124
+ return mc
2125
+
2126
+ def expect_tag_(self):
2127
+ self.advance_lexer_()
2128
+ if self.cur_token_type_ is not Lexer.NAME:
2129
+ raise FeatureLibError("Expected a tag", self.cur_token_location_)
2130
+ if len(self.cur_token_) > 4:
2131
+ raise FeatureLibError(
2132
+ "Tags cannot be longer than 4 characters", self.cur_token_location_
2133
+ )
2134
+ return (self.cur_token_ + " ")[:4]
2135
+
2136
+ def expect_script_tag_(self):
2137
+ tag = self.expect_tag_()
2138
+ if tag == "dflt":
2139
+ raise FeatureLibError(
2140
+ '"dflt" is not a valid script tag; use "DFLT" instead',
2141
+ self.cur_token_location_,
2142
+ )
2143
+ return tag
2144
+
2145
+ def expect_language_tag_(self):
2146
+ tag = self.expect_tag_()
2147
+ if tag == "DFLT":
2148
+ raise FeatureLibError(
2149
+ '"DFLT" is not a valid language tag; use "dflt" instead',
2150
+ self.cur_token_location_,
2151
+ )
2152
+ return tag
2153
+
2154
+ def expect_symbol_(self, symbol):
2155
+ self.advance_lexer_()
2156
+ if self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == symbol:
2157
+ return symbol
2158
+ raise FeatureLibError("Expected '%s'" % symbol, self.cur_token_location_)
2159
+
2160
+ def expect_keyword_(self, keyword):
2161
+ self.advance_lexer_()
2162
+ if self.cur_token_type_ is Lexer.NAME and self.cur_token_ == keyword:
2163
+ return self.cur_token_
2164
+ raise FeatureLibError('Expected "%s"' % keyword, self.cur_token_location_)
2165
+
2166
+ def expect_name_(self):
2167
+ self.advance_lexer_()
2168
+ if self.cur_token_type_ is Lexer.NAME:
2169
+ return self.cur_token_
2170
+ raise FeatureLibError("Expected a name", self.cur_token_location_)
2171
+
2172
+ def expect_number_(self, variable=False):
2173
+ self.advance_lexer_()
2174
+ if self.cur_token_type_ is Lexer.NUMBER:
2175
+ return self.cur_token_
2176
+ if variable and self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == "(":
2177
+ return self.expect_variable_scalar_()
2178
+ raise FeatureLibError("Expected a number", self.cur_token_location_)
2179
+
2180
+ def expect_variable_scalar_(self):
2181
+ self.advance_lexer_() # "("
2182
+ scalar = VariableScalar()
2183
+ while True:
2184
+ if self.cur_token_type_ == Lexer.SYMBOL and self.cur_token_ == ")":
2185
+ break
2186
+ location, value = self.expect_master_()
2187
+ scalar.add_value(location, value)
2188
+ return scalar
2189
+
2190
+ def expect_master_(self):
2191
+ location = {}
2192
+ while True:
2193
+ if self.cur_token_type_ is not Lexer.NAME:
2194
+ raise FeatureLibError("Expected an axis name", self.cur_token_location_)
2195
+ axis = self.cur_token_
2196
+ self.advance_lexer_()
2197
+ if not (self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == "="):
2198
+ raise FeatureLibError(
2199
+ "Expected an equals sign", self.cur_token_location_
2200
+ )
2201
+ value = self.expect_number_()
2202
+ location[axis] = value
2203
+ if self.next_token_type_ is Lexer.NAME and self.next_token_[0] == ":":
2204
+ # Lexer has just read the value as a glyph name. We'll correct it later
2205
+ break
2206
+ self.advance_lexer_()
2207
+ if not (self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == ","):
2208
+ raise FeatureLibError(
2209
+ "Expected an comma or an equals sign", self.cur_token_location_
2210
+ )
2211
+ self.advance_lexer_()
2212
+ self.advance_lexer_()
2213
+ value = int(self.cur_token_[1:])
2214
+ self.advance_lexer_()
2215
+ return location, value
2216
+
2217
+ def expect_any_number_(self):
2218
+ self.advance_lexer_()
2219
+ if self.cur_token_type_ in Lexer.NUMBERS:
2220
+ return self.cur_token_
2221
+ raise FeatureLibError(
2222
+ "Expected a decimal, hexadecimal or octal number", self.cur_token_location_
2223
+ )
2224
+
2225
+ def expect_float_(self):
2226
+ self.advance_lexer_()
2227
+ if self.cur_token_type_ is Lexer.FLOAT:
2228
+ return self.cur_token_
2229
+ raise FeatureLibError(
2230
+ "Expected a floating-point number", self.cur_token_location_
2231
+ )
2232
+
2233
+ def expect_decipoint_(self):
2234
+ if self.next_token_type_ == Lexer.FLOAT:
2235
+ return self.expect_float_()
2236
+ elif self.next_token_type_ is Lexer.NUMBER:
2237
+ return self.expect_number_() / 10
2238
+ else:
2239
+ raise FeatureLibError(
2240
+ "Expected an integer or floating-point number", self.cur_token_location_
2241
+ )
2242
+
2243
+ def expect_stat_flags(self):
2244
+ value = 0
2245
+ flags = {
2246
+ "OlderSiblingFontAttribute": 1,
2247
+ "ElidableAxisValueName": 2,
2248
+ }
2249
+ while self.next_token_ != ";":
2250
+ if self.next_token_ in flags:
2251
+ name = self.expect_name_()
2252
+ value = value | flags[name]
2253
+ else:
2254
+ raise FeatureLibError(
2255
+ f"Unexpected STAT flag {self.cur_token_}", self.cur_token_location_
2256
+ )
2257
+ return value
2258
+
2259
+ def expect_stat_values_(self):
2260
+ if self.next_token_type_ == Lexer.FLOAT:
2261
+ return self.expect_float_()
2262
+ elif self.next_token_type_ is Lexer.NUMBER:
2263
+ return self.expect_number_()
2264
+ else:
2265
+ raise FeatureLibError(
2266
+ "Expected an integer or floating-point number", self.cur_token_location_
2267
+ )
2268
+
2269
+ def expect_string_(self):
2270
+ self.advance_lexer_()
2271
+ if self.cur_token_type_ is Lexer.STRING:
2272
+ return self.cur_token_
2273
+ raise FeatureLibError("Expected a string", self.cur_token_location_)
2274
+
2275
+ def advance_lexer_(self, comments=False):
2276
+ if comments and self.cur_comments_:
2277
+ self.cur_token_type_ = Lexer.COMMENT
2278
+ self.cur_token_, self.cur_token_location_ = self.cur_comments_.pop(0)
2279
+ return
2280
+ else:
2281
+ self.cur_token_type_, self.cur_token_, self.cur_token_location_ = (
2282
+ self.next_token_type_,
2283
+ self.next_token_,
2284
+ self.next_token_location_,
2285
+ )
2286
+ while True:
2287
+ try:
2288
+ (
2289
+ self.next_token_type_,
2290
+ self.next_token_,
2291
+ self.next_token_location_,
2292
+ ) = next(self.lexer_)
2293
+ except StopIteration:
2294
+ self.next_token_type_, self.next_token_ = (None, None)
2295
+ if self.next_token_type_ != Lexer.COMMENT:
2296
+ break
2297
+ self.cur_comments_.append((self.next_token_, self.next_token_location_))
2298
+
2299
+ @staticmethod
2300
+ def reverse_string_(s):
2301
+ """'abc' --> 'cba'"""
2302
+ return "".join(reversed(list(s)))
2303
+
2304
+ def make_cid_range_(self, location, start, limit):
2305
+ """(location, 999, 1001) --> ["cid00999", "cid01000", "cid01001"]"""
2306
+ result = list()
2307
+ if start > limit:
2308
+ raise FeatureLibError(
2309
+ "Bad range: start should be less than limit", location
2310
+ )
2311
+ for cid in range(start, limit + 1):
2312
+ result.append("cid%05d" % cid)
2313
+ return result
2314
+
2315
+ def make_glyph_range_(self, location, start, limit):
2316
+ """(location, "a.sc", "d.sc") --> ["a.sc", "b.sc", "c.sc", "d.sc"]"""
2317
+ result = list()
2318
+ if len(start) != len(limit):
2319
+ raise FeatureLibError(
2320
+ 'Bad range: "%s" and "%s" should have the same length' % (start, limit),
2321
+ location,
2322
+ )
2323
+
2324
+ rev = self.reverse_string_
2325
+ prefix = os.path.commonprefix([start, limit])
2326
+ suffix = rev(os.path.commonprefix([rev(start), rev(limit)]))
2327
+ if len(suffix) > 0:
2328
+ start_range = start[len(prefix) : -len(suffix)]
2329
+ limit_range = limit[len(prefix) : -len(suffix)]
2330
+ else:
2331
+ start_range = start[len(prefix) :]
2332
+ limit_range = limit[len(prefix) :]
2333
+
2334
+ if start_range >= limit_range:
2335
+ raise FeatureLibError(
2336
+ "Start of range must be smaller than its end", location
2337
+ )
2338
+
2339
+ uppercase = re.compile(r"^[A-Z]$")
2340
+ if uppercase.match(start_range) and uppercase.match(limit_range):
2341
+ for c in range(ord(start_range), ord(limit_range) + 1):
2342
+ result.append("%s%c%s" % (prefix, c, suffix))
2343
+ return result
2344
+
2345
+ lowercase = re.compile(r"^[a-z]$")
2346
+ if lowercase.match(start_range) and lowercase.match(limit_range):
2347
+ for c in range(ord(start_range), ord(limit_range) + 1):
2348
+ result.append("%s%c%s" % (prefix, c, suffix))
2349
+ return result
2350
+
2351
+ digits = re.compile(r"^[0-9]{1,3}$")
2352
+ if digits.match(start_range) and digits.match(limit_range):
2353
+ for i in range(int(start_range, 10), int(limit_range, 10) + 1):
2354
+ number = ("000" + str(i))[-len(start_range) :]
2355
+ result.append("%s%s%s" % (prefix, number, suffix))
2356
+ return result
2357
+
2358
+ raise FeatureLibError('Bad range: "%s-%s"' % (start, limit), location)
2359
+
2360
+
2361
+ class SymbolTable(object):
2362
+ def __init__(self):
2363
+ self.scopes_ = [{}]
2364
+
2365
+ def enter_scope(self):
2366
+ self.scopes_.append({})
2367
+
2368
+ def exit_scope(self):
2369
+ self.scopes_.pop()
2370
+
2371
+ def define(self, name, item):
2372
+ self.scopes_[-1][name] = item
2373
+
2374
+ def resolve(self, name):
2375
+ for scope in reversed(self.scopes_):
2376
+ item = scope.get(name)
2377
+ if item:
2378
+ return item
2379
+ return None