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.

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