lexer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound
  2. from fontTools.feaLib.location import FeatureLibLocation
  3. import re
  4. import os
  5. try:
  6. import cython
  7. except ImportError:
  8. # if cython not installed, use mock module with no-op decorators and types
  9. from fontTools.misc import cython
  10. class Lexer(object):
  11. NUMBER = "NUMBER"
  12. HEXADECIMAL = "HEXADECIMAL"
  13. OCTAL = "OCTAL"
  14. NUMBERS = (NUMBER, HEXADECIMAL, OCTAL)
  15. FLOAT = "FLOAT"
  16. STRING = "STRING"
  17. NAME = "NAME"
  18. FILENAME = "FILENAME"
  19. GLYPHCLASS = "GLYPHCLASS"
  20. CID = "CID"
  21. SYMBOL = "SYMBOL"
  22. COMMENT = "COMMENT"
  23. NEWLINE = "NEWLINE"
  24. ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK"
  25. CHAR_WHITESPACE_ = " \t"
  26. CHAR_NEWLINE_ = "\r\n"
  27. CHAR_SYMBOL_ = ",;:-+'{}[]<>()="
  28. CHAR_DIGIT_ = "0123456789"
  29. CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef"
  30. CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  31. CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\"
  32. CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-"
  33. RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$")
  34. MODE_NORMAL_ = "NORMAL"
  35. MODE_FILENAME_ = "FILENAME"
  36. def __init__(self, text, filename):
  37. self.filename_ = filename
  38. self.line_ = 1
  39. self.pos_ = 0
  40. self.line_start_ = 0
  41. self.text_ = text
  42. self.text_length_ = len(text)
  43. self.mode_ = Lexer.MODE_NORMAL_
  44. def __iter__(self):
  45. return self
  46. def next(self): # Python 2
  47. return self.__next__()
  48. def __next__(self): # Python 3
  49. while True:
  50. token_type, token, location = self.next_()
  51. if token_type != Lexer.NEWLINE:
  52. return (token_type, token, location)
  53. def location_(self):
  54. column = self.pos_ - self.line_start_ + 1
  55. return FeatureLibLocation(self.filename_ or "<features>", self.line_, column)
  56. def next_(self):
  57. self.scan_over_(Lexer.CHAR_WHITESPACE_)
  58. location = self.location_()
  59. start = self.pos_
  60. text = self.text_
  61. limit = len(text)
  62. if start >= limit:
  63. raise StopIteration()
  64. cur_char = text[start]
  65. next_char = text[start + 1] if start + 1 < limit else None
  66. if cur_char == "\n":
  67. self.pos_ += 1
  68. self.line_ += 1
  69. self.line_start_ = self.pos_
  70. return (Lexer.NEWLINE, None, location)
  71. if cur_char == "\r":
  72. self.pos_ += 2 if next_char == "\n" else 1
  73. self.line_ += 1
  74. self.line_start_ = self.pos_
  75. return (Lexer.NEWLINE, None, location)
  76. if cur_char == "#":
  77. self.scan_until_(Lexer.CHAR_NEWLINE_)
  78. return (Lexer.COMMENT, text[start : self.pos_], location)
  79. if self.mode_ is Lexer.MODE_FILENAME_:
  80. if cur_char != "(":
  81. raise FeatureLibError("Expected '(' before file name", location)
  82. self.scan_until_(")")
  83. cur_char = text[self.pos_] if self.pos_ < limit else None
  84. if cur_char != ")":
  85. raise FeatureLibError("Expected ')' after file name", location)
  86. self.pos_ += 1
  87. self.mode_ = Lexer.MODE_NORMAL_
  88. return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location)
  89. if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_:
  90. self.pos_ += 1
  91. self.scan_over_(Lexer.CHAR_DIGIT_)
  92. return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location)
  93. if cur_char == "@":
  94. self.pos_ += 1
  95. self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_)
  96. glyphclass = text[start + 1 : self.pos_]
  97. if len(glyphclass) < 1:
  98. raise FeatureLibError("Expected glyph class name", location)
  99. if not Lexer.RE_GLYPHCLASS.match(glyphclass):
  100. raise FeatureLibError(
  101. "Glyph class names must consist of letters, digits, "
  102. "underscore, period or hyphen",
  103. location,
  104. )
  105. return (Lexer.GLYPHCLASS, glyphclass, location)
  106. if cur_char in Lexer.CHAR_NAME_START_:
  107. self.pos_ += 1
  108. self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_)
  109. token = text[start : self.pos_]
  110. if token == "include":
  111. self.mode_ = Lexer.MODE_FILENAME_
  112. return (Lexer.NAME, token, location)
  113. if cur_char == "0" and next_char in "xX":
  114. self.pos_ += 2
  115. self.scan_over_(Lexer.CHAR_HEXDIGIT_)
  116. return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location)
  117. if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_:
  118. self.scan_over_(Lexer.CHAR_DIGIT_)
  119. return (Lexer.OCTAL, int(text[start : self.pos_], 8), location)
  120. if cur_char in Lexer.CHAR_DIGIT_:
  121. self.scan_over_(Lexer.CHAR_DIGIT_)
  122. if self.pos_ >= limit or text[self.pos_] != ".":
  123. return (Lexer.NUMBER, int(text[start : self.pos_], 10), location)
  124. self.scan_over_(".")
  125. self.scan_over_(Lexer.CHAR_DIGIT_)
  126. return (Lexer.FLOAT, float(text[start : self.pos_]), location)
  127. if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_:
  128. self.pos_ += 1
  129. self.scan_over_(Lexer.CHAR_DIGIT_)
  130. if self.pos_ >= limit or text[self.pos_] != ".":
  131. return (Lexer.NUMBER, int(text[start : self.pos_], 10), location)
  132. self.scan_over_(".")
  133. self.scan_over_(Lexer.CHAR_DIGIT_)
  134. return (Lexer.FLOAT, float(text[start : self.pos_]), location)
  135. if cur_char in Lexer.CHAR_SYMBOL_:
  136. self.pos_ += 1
  137. return (Lexer.SYMBOL, cur_char, location)
  138. if cur_char == '"':
  139. self.pos_ += 1
  140. self.scan_until_('"')
  141. if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"':
  142. self.pos_ += 1
  143. # strip newlines embedded within a string
  144. string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1])
  145. return (Lexer.STRING, string, location)
  146. else:
  147. raise FeatureLibError("Expected '\"' to terminate string", location)
  148. raise FeatureLibError("Unexpected character: %r" % cur_char, location)
  149. def scan_over_(self, valid):
  150. p = self.pos_
  151. while p < self.text_length_ and self.text_[p] in valid:
  152. p += 1
  153. self.pos_ = p
  154. def scan_until_(self, stop_at):
  155. p = self.pos_
  156. while p < self.text_length_ and self.text_[p] not in stop_at:
  157. p += 1
  158. self.pos_ = p
  159. def scan_anonymous_block(self, tag):
  160. location = self.location_()
  161. tag = tag.strip()
  162. self.scan_until_(Lexer.CHAR_NEWLINE_)
  163. self.scan_over_(Lexer.CHAR_NEWLINE_)
  164. regexp = r"}\s*" + tag + r"\s*;"
  165. split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1)
  166. if len(split) != 2:
  167. raise FeatureLibError(
  168. "Expected '} %s;' to terminate anonymous block" % tag, location
  169. )
  170. self.pos_ += len(split[0])
  171. return (Lexer.ANONYMOUS_BLOCK, split[0], location)
  172. class IncludingLexer(object):
  173. """A Lexer that follows include statements.
  174. The OpenType feature file specification states that due to
  175. historical reasons, relative imports should be resolved in this
  176. order:
  177. 1. If the source font is UFO format, then relative to the UFO's
  178. font directory
  179. 2. relative to the top-level include file
  180. 3. relative to the parent include file
  181. We only support 1 (via includeDir) and 2.
  182. """
  183. def __init__(self, featurefile, *, includeDir=None):
  184. """Initializes an IncludingLexer.
  185. Behavior:
  186. If includeDir is passed, it will be used to determine the top-level
  187. include directory to use for all encountered include statements. If it is
  188. not passed, ``os.path.dirname(featurefile)`` will be considered the
  189. include directory.
  190. """
  191. self.lexers_ = [self.make_lexer_(featurefile)]
  192. self.featurefilepath = self.lexers_[0].filename_
  193. self.includeDir = includeDir
  194. def __iter__(self):
  195. return self
  196. def next(self): # Python 2
  197. return self.__next__()
  198. def __next__(self): # Python 3
  199. while self.lexers_:
  200. lexer = self.lexers_[-1]
  201. try:
  202. token_type, token, location = next(lexer)
  203. except StopIteration:
  204. self.lexers_.pop()
  205. continue
  206. if token_type is Lexer.NAME and token == "include":
  207. fname_type, fname_token, fname_location = lexer.next()
  208. if fname_type is not Lexer.FILENAME:
  209. raise FeatureLibError("Expected file name", fname_location)
  210. # semi_type, semi_token, semi_location = lexer.next()
  211. # if semi_type is not Lexer.SYMBOL or semi_token != ";":
  212. # raise FeatureLibError("Expected ';'", semi_location)
  213. if os.path.isabs(fname_token):
  214. path = fname_token
  215. else:
  216. if self.includeDir is not None:
  217. curpath = self.includeDir
  218. elif self.featurefilepath is not None:
  219. curpath = os.path.dirname(self.featurefilepath)
  220. else:
  221. # if the IncludingLexer was initialized from an in-memory
  222. # file-like stream, it doesn't have a 'name' pointing to
  223. # its filesystem path, therefore we fall back to using the
  224. # current working directory to resolve relative includes
  225. curpath = os.getcwd()
  226. path = os.path.join(curpath, fname_token)
  227. if len(self.lexers_) >= 5:
  228. raise FeatureLibError("Too many recursive includes", fname_location)
  229. try:
  230. self.lexers_.append(self.make_lexer_(path))
  231. except FileNotFoundError as err:
  232. raise IncludedFeaNotFound(fname_token, fname_location) from err
  233. else:
  234. return (token_type, token, location)
  235. raise StopIteration()
  236. @staticmethod
  237. def make_lexer_(file_or_path):
  238. if hasattr(file_or_path, "read"):
  239. fileobj, closing = file_or_path, False
  240. else:
  241. filename, closing = file_or_path, True
  242. fileobj = open(filename, "r", encoding="utf-8-sig")
  243. data = fileobj.read()
  244. filename = getattr(fileobj, "name", None)
  245. if closing:
  246. fileobj.close()
  247. return Lexer(data, filename)
  248. def scan_anonymous_block(self, tag):
  249. return self.lexers_[-1].scan_anonymous_block(tag)
  250. class NonIncludingLexer(IncludingLexer):
  251. """Lexer that does not follow `include` statements, emits them as-is."""
  252. def __next__(self): # Python 3
  253. return next(self.lexers_[0])