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.

443 lines
15 KiB

  1. ## Lexer Implementation
  2. import re
  3. from .utils import Str, classify, get_regexp_width, Py36, Serialize, suppress
  4. from .exceptions import UnexpectedCharacters, LexError, UnexpectedToken
  5. ###{standalone
  6. from copy import copy
  7. class Pattern(Serialize):
  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. __serialize_fields__ = 'value', 'flags'
  33. type = "str"
  34. def to_regexp(self):
  35. return self._get_flags(re.escape(self.value))
  36. @property
  37. def min_width(self):
  38. return len(self.value)
  39. max_width = min_width
  40. class PatternRE(Pattern):
  41. __serialize_fields__ = 'value', 'flags', '_width'
  42. type = "re"
  43. def to_regexp(self):
  44. return self._get_flags(self.value)
  45. _width = None
  46. def _get_width(self):
  47. if self._width is None:
  48. self._width = get_regexp_width(self.to_regexp())
  49. return self._width
  50. @property
  51. def min_width(self):
  52. return self._get_width()[0]
  53. @property
  54. def max_width(self):
  55. return self._get_width()[1]
  56. class TerminalDef(Serialize):
  57. __serialize_fields__ = 'name', 'pattern', 'priority'
  58. __serialize_namespace__ = PatternStr, PatternRE
  59. def __init__(self, name, pattern, priority=1):
  60. assert isinstance(pattern, Pattern), pattern
  61. self.name = name
  62. self.pattern = pattern
  63. self.priority = priority
  64. def __repr__(self):
  65. return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
  66. class Token(Str):
  67. """A string with meta-information, that is produced by the lexer.
  68. When parsing text, the resulting chunks of the input that haven't been discarded,
  69. will end up in the tree as Token instances. The Token class inherits from Python's ``str``,
  70. so normal string comparisons and operations will work as expected.
  71. Attributes:
  72. type: Name of the token (as specified in grammar)
  73. value: Value of the token (redundant, as ``token.value == token`` will always be true)
  74. pos_in_stream: The index of the token in the text
  75. line: The line of the token in the text (starting with 1)
  76. column: The column of the token in the text (starting with 1)
  77. end_line: The line where the token ends
  78. end_column: The next column after the end of the token. For example,
  79. if the token is a single character with a column value of 4,
  80. end_column will be 5.
  81. end_pos: the index where the token ends (basically ``pos_in_stream + len(token)``)
  82. """
  83. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column', 'end_pos')
  84. def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None, end_line=None, end_column=None, end_pos=None):
  85. try:
  86. self = super(Token, cls).__new__(cls, value)
  87. except UnicodeDecodeError:
  88. value = value.decode('latin1')
  89. self = super(Token, cls).__new__(cls, value)
  90. self.type = type_
  91. self.pos_in_stream = pos_in_stream
  92. self.value = value
  93. self.line = line
  94. self.column = column
  95. self.end_line = end_line
  96. self.end_column = end_column
  97. self.end_pos = end_pos
  98. return self
  99. def update(self, type_=None, value=None):
  100. return Token.new_borrow_pos(
  101. type_ if type_ is not None else self.type,
  102. value if value is not None else self.value,
  103. self
  104. )
  105. @classmethod
  106. def new_borrow_pos(cls, type_, value, borrow_t):
  107. return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column, borrow_t.end_pos)
  108. def __reduce__(self):
  109. return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, ))
  110. def __repr__(self):
  111. return 'Token(%r, %r)' % (self.type, self.value)
  112. def __deepcopy__(self, memo):
  113. return Token(self.type, self.value, self.pos_in_stream, self.line, self.column)
  114. def __eq__(self, other):
  115. if isinstance(other, Token) and self.type != other.type:
  116. return False
  117. return Str.__eq__(self, other)
  118. __hash__ = Str.__hash__
  119. class LineCounter:
  120. __slots__ = 'char_pos', 'line', 'column', 'line_start_pos', 'newline_char'
  121. def __init__(self, newline_char):
  122. self.newline_char = newline_char
  123. self.char_pos = 0
  124. self.line = 1
  125. self.column = 1
  126. self.line_start_pos = 0
  127. def feed(self, token, test_newline=True):
  128. """Consume a token and calculate the new line & column.
  129. As an optional optimization, set test_newline=False if token doesn't contain a newline.
  130. """
  131. if test_newline:
  132. newlines = token.count(self.newline_char)
  133. if newlines:
  134. self.line += newlines
  135. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  136. self.char_pos += len(token)
  137. self.column = self.char_pos - self.line_start_pos + 1
  138. class UnlessCallback:
  139. def __init__(self, mres):
  140. self.mres = mres
  141. def __call__(self, t):
  142. for mre, type_from_index in self.mres:
  143. m = mre.match(t.value)
  144. if m:
  145. t.type = type_from_index[m.lastindex]
  146. break
  147. return t
  148. class CallChain:
  149. def __init__(self, callback1, callback2, cond):
  150. self.callback1 = callback1
  151. self.callback2 = callback2
  152. self.cond = cond
  153. def __call__(self, t):
  154. t2 = self.callback1(t)
  155. return self.callback2(t) if self.cond(t2) else t2
  156. def _create_unless(terminals, g_regex_flags, re_, use_bytes):
  157. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  158. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  159. embedded_strs = set()
  160. callback = {}
  161. for retok in tokens_by_type.get(PatternRE, []):
  162. unless = [] # {}
  163. for strtok in tokens_by_type.get(PatternStr, []):
  164. if strtok.priority > retok.priority:
  165. continue
  166. s = strtok.pattern.value
  167. m = re_.match(retok.pattern.to_regexp(), s, g_regex_flags)
  168. if m and m.group(0) == s:
  169. unless.append(strtok)
  170. if strtok.pattern.flags <= retok.pattern.flags:
  171. embedded_strs.add(strtok)
  172. if unless:
  173. callback[retok.name] = UnlessCallback(build_mres(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
  174. terminals = [t for t in terminals if t not in embedded_strs]
  175. return terminals, callback
  176. def _build_mres(terminals, max_size, g_regex_flags, match_whole, re_, use_bytes):
  177. # Python sets an unreasonable group limit (currently 100) in its re module
  178. # Worse, the only way to know we reached it is by catching an AssertionError!
  179. # This function recursively tries less and less groups until it's successful.
  180. postfix = '$' if match_whole else ''
  181. mres = []
  182. while terminals:
  183. pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
  184. if use_bytes:
  185. pattern = pattern.encode('latin-1')
  186. try:
  187. mre = re_.compile(pattern, g_regex_flags)
  188. except AssertionError: # Yes, this is what Python provides us.. :/
  189. return _build_mres(terminals, max_size//2, g_regex_flags, match_whole, re_, use_bytes)
  190. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  191. terminals = terminals[max_size:]
  192. return mres
  193. def build_mres(terminals, g_regex_flags, re_, use_bytes, match_whole=False):
  194. return _build_mres(terminals, len(terminals), g_regex_flags, match_whole, re_, use_bytes)
  195. def _regexp_has_newline(r):
  196. r"""Expressions that may indicate newlines in a regexp:
  197. - newlines (\n)
  198. - escaped newline (\\n)
  199. - anything but ([^...])
  200. - any-char (.) when the flag (?s) exists
  201. - spaces (\s)
  202. """
  203. return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r)
  204. class Lexer(object):
  205. """Lexer interface
  206. Method Signatures:
  207. lex(self, text) -> Iterator[Token]
  208. """
  209. lex = NotImplemented
  210. def make_lexer_state(self, text):
  211. line_ctr = LineCounter(b'\n' if isinstance(text, bytes) else '\n')
  212. return LexerState(text, line_ctr)
  213. class TraditionalLexer(Lexer):
  214. def __init__(self, conf):
  215. terminals = list(conf.tokens)
  216. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  217. self.re = conf.re_module
  218. if not conf.skip_validation:
  219. # Sanitization
  220. for t in terminals:
  221. try:
  222. self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags)
  223. except self.re.error:
  224. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  225. if t.pattern.min_width == 0:
  226. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  227. assert set(conf.ignore) <= {t.name for t in terminals}
  228. # Init
  229. self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
  230. self.ignore_types = frozenset(conf.ignore)
  231. terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  232. self.terminals = terminals
  233. self.user_callbacks = conf.callbacks
  234. self.g_regex_flags = conf.g_regex_flags
  235. self.use_bytes = conf.use_bytes
  236. self._mres = None
  237. def _build(self):
  238. terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, re_=self.re, use_bytes=self.use_bytes)
  239. assert all(self.callback.values())
  240. for type_, f in self.user_callbacks.items():
  241. if type_ in self.callback:
  242. # Already a callback there, probably UnlessCallback
  243. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  244. else:
  245. self.callback[type_] = f
  246. self._mres = build_mres(terminals, self.g_regex_flags, self.re, self.use_bytes)
  247. @property
  248. def mres(self):
  249. if self._mres is None:
  250. self._build()
  251. return self._mres
  252. def match(self, text, pos):
  253. for mre, type_from_index in self.mres:
  254. m = mre.match(text, pos)
  255. if m:
  256. return m.group(0), type_from_index[m.lastindex]
  257. def lex(self, state, parser_state):
  258. with suppress(EOFError):
  259. while True:
  260. yield self.next_token(state)
  261. def next_token(self, lex_state):
  262. line_ctr = lex_state.line_ctr
  263. while line_ctr.char_pos < len(lex_state.text):
  264. res = self.match(lex_state.text, line_ctr.char_pos)
  265. if not res:
  266. allowed = {v for m, tfi in self.mres for v in tfi.values()} - self.ignore_types
  267. if not allowed:
  268. allowed = {"<END-OF-FILE>"}
  269. raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
  270. allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token])
  271. value, type_ = res
  272. if type_ not in self.ignore_types:
  273. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  274. line_ctr.feed(value, type_ in self.newline_types)
  275. t.end_line = line_ctr.line
  276. t.end_column = line_ctr.column
  277. t.end_pos = line_ctr.char_pos
  278. if t.type in self.callback:
  279. t = self.callback[t.type](t)
  280. if not isinstance(t, Token):
  281. raise ValueError("Callbacks must return a token (returned %r)" % t)
  282. lex_state.last_token = t
  283. return t
  284. else:
  285. if type_ in self.callback:
  286. t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  287. self.callback[type_](t2)
  288. line_ctr.feed(value, type_ in self.newline_types)
  289. # EOF
  290. raise EOFError(self)
  291. class LexerState:
  292. __slots__ = 'text', 'line_ctr', 'last_token'
  293. def __init__(self, text, line_ctr, last_token=None):
  294. self.text = text
  295. self.line_ctr = line_ctr
  296. self.last_token = last_token
  297. def __copy__(self):
  298. return type(self)(self.text, copy(self.line_ctr), self.last_token)
  299. class ContextualLexer(Lexer):
  300. def __init__(self, conf, states, always_accept=()):
  301. terminals = list(conf.tokens)
  302. tokens_by_name = {}
  303. for t in terminals:
  304. assert t.name not in tokens_by_name, t
  305. tokens_by_name[t.name] = t
  306. trad_conf = copy(conf)
  307. trad_conf.tokens = terminals
  308. lexer_by_tokens = {}
  309. self.lexers = {}
  310. for state, accepts in states.items():
  311. key = frozenset(accepts)
  312. try:
  313. lexer = lexer_by_tokens[key]
  314. except KeyError:
  315. accepts = set(accepts) | set(conf.ignore) | set(always_accept)
  316. state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name]
  317. lexer_conf = copy(trad_conf)
  318. lexer_conf.tokens = state_tokens
  319. lexer = TraditionalLexer(lexer_conf)
  320. lexer_by_tokens[key] = lexer
  321. self.lexers[state] = lexer
  322. assert trad_conf.tokens is terminals
  323. self.root_lexer = TraditionalLexer(trad_conf)
  324. def make_lexer_state(self, text):
  325. return self.root_lexer.make_lexer_state(text)
  326. def lex(self, lexer_state, parser_state):
  327. try:
  328. while True:
  329. lexer = self.lexers[parser_state.position]
  330. yield lexer.next_token(lexer_state)
  331. except EOFError:
  332. pass
  333. except UnexpectedCharacters as e:
  334. # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, but not in the current context.
  335. # This tests the input against the global context, to provide a nicer error.
  336. token = self.root_lexer.next_token(lexer_state)
  337. raise UnexpectedToken(token, e.allowed, state=parser_state.position)
  338. class LexerThread:
  339. "A thread that ties a lexer instance and a lexer state, to be used by the parser"
  340. def __init__(self, lexer, text):
  341. self.lexer = lexer
  342. self.state = lexer.make_lexer_state(text)
  343. def lex(self, parser_state):
  344. return self.lexer.lex(self.state, parser_state)
  345. ###}