This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

372 lines
12 KiB

  1. ## Lexer Implementation
  2. import re
  3. from .utils import Str, classify, get_regexp_width, Py36, Serialize
  4. from .exceptions import UnexpectedCharacters, LexError
  5. ###{standalone
  6. class Pattern(Serialize):
  7. __serialize_fields__ = 'value', 'flags'
  8. def __init__(self, value, flags=()):
  9. self.value = value
  10. self.flags = frozenset(flags)
  11. def __repr__(self):
  12. return repr(self.to_regexp())
  13. # Pattern Hashing assumes all subclasses have a different priority!
  14. def __hash__(self):
  15. return hash((type(self), self.value, self.flags))
  16. def __eq__(self, other):
  17. return type(self) == type(other) and self.value == other.value and self.flags == other.flags
  18. def to_regexp(self):
  19. raise NotImplementedError()
  20. if Py36:
  21. # Python 3.6 changed syntax for flags in regular expression
  22. def _get_flags(self, value):
  23. for f in self.flags:
  24. value = ('(?%s:%s)' % (f, value))
  25. return value
  26. else:
  27. def _get_flags(self, value):
  28. for f in self.flags:
  29. value = ('(?%s)' % f) + value
  30. return value
  31. class PatternStr(Pattern):
  32. type = "str"
  33. def to_regexp(self):
  34. return self._get_flags(re.escape(self.value))
  35. @property
  36. def min_width(self):
  37. return len(self.value)
  38. max_width = min_width
  39. class PatternRE(Pattern):
  40. type = "re"
  41. def to_regexp(self):
  42. return self._get_flags(self.value)
  43. _width = None
  44. def _get_width(self):
  45. if self._width is None:
  46. self._width = get_regexp_width(self.to_regexp())
  47. return self._width
  48. @property
  49. def min_width(self):
  50. return self._get_width()[0]
  51. @property
  52. def max_width(self):
  53. return self._get_width()[1]
  54. class TerminalDef(Serialize):
  55. __serialize_fields__ = 'name', 'pattern', 'priority'
  56. __serialize_namespace__ = PatternStr, PatternRE
  57. def __init__(self, name, pattern, priority=1):
  58. assert isinstance(pattern, Pattern), pattern
  59. self.name = name
  60. self.pattern = pattern
  61. self.priority = priority
  62. def __repr__(self):
  63. return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
  64. class Token(Str):
  65. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column')
  66. def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None, end_line=None, end_column=None):
  67. try:
  68. self = super(Token, cls).__new__(cls, value)
  69. except UnicodeDecodeError:
  70. value = value.decode('latin1')
  71. self = super(Token, cls).__new__(cls, value)
  72. self.type = type_
  73. self.pos_in_stream = pos_in_stream
  74. self.value = Str(value)
  75. self.line = line
  76. self.column = column
  77. self.end_line = end_line
  78. self.end_column = end_column
  79. return self
  80. @classmethod
  81. def new_borrow_pos(cls, type_, value, borrow_t):
  82. return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column)
  83. def __reduce__(self):
  84. return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, ))
  85. def __repr__(self):
  86. return 'Token(%s, %r)' % (self.type, self.value)
  87. def __deepcopy__(self, memo):
  88. return Token(self.type, self.value, self.pos_in_stream, self.line, self.column)
  89. def __eq__(self, other):
  90. if isinstance(other, Token) and self.type != other.type:
  91. return False
  92. return Str.__eq__(self, other)
  93. __hash__ = Str.__hash__
  94. class LineCounter:
  95. def __init__(self):
  96. self.newline_char = '\n'
  97. self.char_pos = 0
  98. self.line = 1
  99. self.column = 1
  100. self.line_start_pos = 0
  101. def feed(self, token, test_newline=True):
  102. """Consume a token and calculate the new line & column.
  103. As an optional optimization, set test_newline=False is token doesn't contain a newline.
  104. """
  105. if test_newline:
  106. newlines = token.count(self.newline_char)
  107. if newlines:
  108. self.line += newlines
  109. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  110. self.char_pos += len(token)
  111. self.column = self.char_pos - self.line_start_pos + 1
  112. class _Lex:
  113. "Built to serve both Lexer and ContextualLexer"
  114. def __init__(self, lexer, state=None):
  115. self.lexer = lexer
  116. self.state = state
  117. def lex(self, stream, newline_types, ignore_types):
  118. newline_types = frozenset(newline_types)
  119. ignore_types = frozenset(ignore_types)
  120. line_ctr = LineCounter()
  121. last_token = None
  122. while line_ctr.char_pos < len(stream):
  123. lexer = self.lexer
  124. for mre, type_from_index in lexer.mres:
  125. m = mre.match(stream, line_ctr.char_pos)
  126. if not m:
  127. continue
  128. t = None
  129. value = m.group(0)
  130. type_ = type_from_index[m.lastindex]
  131. if type_ not in ignore_types:
  132. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  133. if t.type in lexer.callback:
  134. t = lexer.callback[t.type](t)
  135. if not isinstance(t, Token):
  136. raise ValueError("Callbacks must return a token (returned %r)" % t)
  137. last_token = t
  138. yield t
  139. else:
  140. if type_ in lexer.callback:
  141. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  142. lexer.callback[type_](t)
  143. line_ctr.feed(value, type_ in newline_types)
  144. if t:
  145. t.end_line = line_ctr.line
  146. t.end_column = line_ctr.column
  147. break
  148. else:
  149. allowed = {v for m, tfi in lexer.mres for v in tfi.values()}
  150. raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, allowed=allowed, state=self.state, token_history=last_token and [last_token])
  151. class UnlessCallback:
  152. def __init__(self, mres):
  153. self.mres = mres
  154. def __call__(self, t):
  155. for mre, type_from_index in self.mres:
  156. m = mre.match(t.value)
  157. if m:
  158. t.type = type_from_index[m.lastindex]
  159. break
  160. return t
  161. class CallChain:
  162. def __init__(self, callback1, callback2, cond):
  163. self.callback1 = callback1
  164. self.callback2 = callback2
  165. self.cond = cond
  166. def __call__(self, t):
  167. t2 = self.callback1(t)
  168. return self.callback2(t) if self.cond(t2) else t2
  169. def _create_unless(terminals):
  170. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  171. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  172. embedded_strs = set()
  173. callback = {}
  174. for retok in tokens_by_type.get(PatternRE, []):
  175. unless = [] # {}
  176. for strtok in tokens_by_type.get(PatternStr, []):
  177. if strtok.priority > retok.priority:
  178. continue
  179. s = strtok.pattern.value
  180. m = re.match(retok.pattern.to_regexp(), s)
  181. if m and m.group(0) == s:
  182. unless.append(strtok)
  183. if strtok.pattern.flags <= retok.pattern.flags:
  184. embedded_strs.add(strtok)
  185. if unless:
  186. callback[retok.name] = UnlessCallback(build_mres(unless, match_whole=True))
  187. terminals = [t for t in terminals if t not in embedded_strs]
  188. return terminals, callback
  189. def _build_mres(terminals, max_size, match_whole):
  190. # Python sets an unreasonable group limit (currently 100) in its re module
  191. # Worse, the only way to know we reached it is by catching an AssertionError!
  192. # This function recursively tries less and less groups until it's successful.
  193. postfix = '$' if match_whole else ''
  194. mres = []
  195. while terminals:
  196. try:
  197. mre = re.compile(u'|'.join(u'(?P<%s>%s)'%(t.name, t.pattern.to_regexp()+postfix) for t in terminals[:max_size]))
  198. except AssertionError: # Yes, this is what Python provides us.. :/
  199. return _build_mres(terminals, max_size//2, match_whole)
  200. # terms_from_name = {t.name: t for t in terminals[:max_size]}
  201. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  202. terminals = terminals[max_size:]
  203. return mres
  204. def build_mres(terminals, match_whole=False):
  205. return _build_mres(terminals, len(terminals), match_whole)
  206. def _regexp_has_newline(r):
  207. """Expressions that may indicate newlines in a regexp:
  208. - newlines (\n)
  209. - escaped newline (\\n)
  210. - anything but ([^...])
  211. - any-char (.) when the flag (?s) exists
  212. """
  213. return '\n' in r or '\\n' in r or '[^' in r or ('(?s' in r and '.' in r)
  214. class Lexer(object):
  215. """Lexer interface
  216. Method Signatures:
  217. lex(self, stream) -> Iterator[Token]
  218. set_parser_state(self, state) # Optional
  219. """
  220. set_parser_state = NotImplemented
  221. lex = NotImplemented
  222. class TraditionalLexer(Lexer):
  223. def __init__(self, terminals, ignore=(), user_callbacks={}):
  224. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  225. terminals = list(terminals)
  226. # Sanitization
  227. for t in terminals:
  228. try:
  229. re.compile(t.pattern.to_regexp())
  230. except:
  231. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  232. if t.pattern.min_width == 0:
  233. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  234. assert set(ignore) <= {t.name for t in terminals}
  235. # Init
  236. self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())]
  237. self.ignore_types = list(ignore)
  238. terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  239. self.terminals = terminals
  240. self.user_callbacks = user_callbacks
  241. self.build()
  242. def build(self):
  243. terminals, self.callback = _create_unless(self.terminals)
  244. assert all(self.callback.values())
  245. for type_, f in self.user_callbacks.items():
  246. if type_ in self.callback:
  247. # Already a callback there, probably UnlessCallback
  248. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  249. else:
  250. self.callback[type_] = f
  251. self.mres = build_mres(terminals)
  252. def lex(self, stream):
  253. return _Lex(self).lex(stream, self.newline_types, self.ignore_types)
  254. class ContextualLexer(Lexer):
  255. def __init__(self, terminals, states, ignore=(), always_accept=(), user_callbacks={}):
  256. tokens_by_name = {}
  257. for t in terminals:
  258. assert t.name not in tokens_by_name, t
  259. tokens_by_name[t.name] = t
  260. lexer_by_tokens = {}
  261. self.lexers = {}
  262. for state, accepts in states.items():
  263. key = frozenset(accepts)
  264. try:
  265. lexer = lexer_by_tokens[key]
  266. except KeyError:
  267. accepts = set(accepts) | set(ignore) | set(always_accept)
  268. state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name]
  269. lexer = TraditionalLexer(state_tokens, ignore=ignore, user_callbacks=user_callbacks)
  270. lexer_by_tokens[key] = lexer
  271. self.lexers[state] = lexer
  272. self.root_lexer = TraditionalLexer(terminals, ignore=ignore, user_callbacks=user_callbacks)
  273. self.set_parser_state(None) # Needs to be set on the outside
  274. def set_parser_state(self, state):
  275. self.parser_state = state
  276. def lex(self, stream):
  277. l = _Lex(self.lexers[self.parser_state], self.parser_state)
  278. for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
  279. yield x
  280. l.lexer = self.lexers[self.parser_state]
  281. l.state = self.parser_state
  282. ###}