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.

479 lines
16 KiB

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