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.

459 lines
16 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=(), raw=None):
  9. self.value = value
  10. self.flags = frozenset(flags)
  11. self.raw = raw
  12. def __repr__(self):
  13. return repr(self.to_regexp())
  14. # Pattern Hashing assumes all subclasses have a different priority!
  15. def __hash__(self):
  16. return hash((type(self), self.value, self.flags))
  17. def __eq__(self, other):
  18. return type(self) == type(other) and self.value == other.value and self.flags == other.flags
  19. def to_regexp(self):
  20. raise NotImplementedError()
  21. if Py36:
  22. # Python 3.6 changed syntax for flags in regular expression
  23. def _get_flags(self, value):
  24. for f in self.flags:
  25. value = ('(?%s:%s)' % (f, value))
  26. return value
  27. else:
  28. def _get_flags(self, value):
  29. for f in self.flags:
  30. value = ('(?%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. pos_in_stream: 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 ``pos_in_stream + len(token)``)
  88. """
  89. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column', 'end_pos')
  90. def __new__(cls, type_, value, pos_in_stream=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.pos_in_stream = pos_in_stream
  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.pos_in_stream, 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.pos_in_stream, 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.pos_in_stream, 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 feed(self, token, test_newline=True):
  134. """Consume a token and calculate the new line & column.
  135. As an optional optimization, set test_newline=False if token doesn't contain a newline.
  136. """
  137. if test_newline:
  138. newlines = token.count(self.newline_char)
  139. if newlines:
  140. self.line += newlines
  141. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  142. self.char_pos += len(token)
  143. self.column = self.char_pos - self.line_start_pos + 1
  144. class UnlessCallback:
  145. def __init__(self, mres):
  146. self.mres = mres
  147. def __call__(self, t):
  148. for mre, type_from_index in self.mres:
  149. m = mre.match(t.value)
  150. if m:
  151. t.type = type_from_index[m.lastindex]
  152. break
  153. return t
  154. class CallChain:
  155. def __init__(self, callback1, callback2, cond):
  156. self.callback1 = callback1
  157. self.callback2 = callback2
  158. self.cond = cond
  159. def __call__(self, t):
  160. t2 = self.callback1(t)
  161. return self.callback2(t) if self.cond(t2) else t2
  162. def _create_unless(terminals, g_regex_flags, re_, use_bytes):
  163. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  164. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  165. embedded_strs = set()
  166. callback = {}
  167. for retok in tokens_by_type.get(PatternRE, []):
  168. unless = []
  169. for strtok in tokens_by_type.get(PatternStr, []):
  170. if strtok.priority > retok.priority:
  171. continue
  172. s = strtok.pattern.value
  173. m = re_.match(retok.pattern.to_regexp(), s, g_regex_flags)
  174. if m and m.group(0) == s:
  175. unless.append(strtok)
  176. if strtok.pattern.flags <= retok.pattern.flags:
  177. embedded_strs.add(strtok)
  178. if unless:
  179. callback[retok.name] = UnlessCallback(build_mres(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
  180. terminals = [t for t in terminals if t not in embedded_strs]
  181. return terminals, callback
  182. def _build_mres(terminals, max_size, g_regex_flags, match_whole, re_, use_bytes):
  183. # Python sets an unreasonable group limit (currently 100) in its re module
  184. # Worse, the only way to know we reached it is by catching an AssertionError!
  185. # This function recursively tries less and less groups until it's successful.
  186. postfix = '$' if match_whole else ''
  187. mres = []
  188. while terminals:
  189. pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
  190. if use_bytes:
  191. pattern = pattern.encode('latin-1')
  192. try:
  193. mre = re_.compile(pattern, g_regex_flags)
  194. except AssertionError: # Yes, this is what Python provides us.. :/
  195. return _build_mres(terminals, max_size//2, g_regex_flags, match_whole, re_, use_bytes)
  196. mres.append((mre, {i: n for n, i in mre.groupindex.items()}))
  197. terminals = terminals[max_size:]
  198. return mres
  199. def build_mres(terminals, g_regex_flags, re_, use_bytes, match_whole=False):
  200. return _build_mres(terminals, len(terminals), g_regex_flags, match_whole, re_, use_bytes)
  201. def _regexp_has_newline(r):
  202. r"""Expressions that may indicate newlines in a regexp:
  203. - newlines (\n)
  204. - escaped newline (\\n)
  205. - anything but ([^...])
  206. - any-char (.) when the flag (?s) exists
  207. - spaces (\s)
  208. """
  209. return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r)
  210. class Lexer(object):
  211. """Lexer interface
  212. Method Signatures:
  213. lex(self, text) -> Iterator[Token]
  214. """
  215. lex = NotImplemented
  216. def make_lexer_state(self, text):
  217. line_ctr = LineCounter(b'\n' if isinstance(text, bytes) else '\n')
  218. return LexerState(text, line_ctr)
  219. class TraditionalLexer(Lexer):
  220. def __init__(self, conf):
  221. terminals = list(conf.terminals)
  222. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  223. self.re = conf.re_module
  224. if not conf.skip_validation:
  225. # Sanitization
  226. for t in terminals:
  227. try:
  228. self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags)
  229. except self.re.error:
  230. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  231. if t.pattern.min_width == 0:
  232. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  233. assert set(conf.ignore) <= {t.name for t in terminals}
  234. # Init
  235. self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
  236. self.ignore_types = frozenset(conf.ignore)
  237. terminals.sort(key=lambda x: (-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  238. self.terminals = terminals
  239. self.user_callbacks = conf.callbacks
  240. self.g_regex_flags = conf.g_regex_flags
  241. self.use_bytes = conf.use_bytes
  242. self.terminals_by_name = conf.terminals_by_name
  243. self._mres = None
  244. def _build(self):
  245. terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, self.re, self.use_bytes)
  246. assert all(self.callback.values())
  247. for type_, f in self.user_callbacks.items():
  248. if type_ in self.callback:
  249. # Already a callback there, probably UnlessCallback
  250. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  251. else:
  252. self.callback[type_] = f
  253. self._mres = build_mres(terminals, self.g_regex_flags, self.re, self.use_bytes)
  254. @property
  255. def mres(self):
  256. if self._mres is None:
  257. self._build()
  258. return self._mres
  259. def match(self, text, pos):
  260. for mre, type_from_index in self.mres:
  261. m = mre.match(text, pos)
  262. if m:
  263. return m.group(0), type_from_index[m.lastindex]
  264. def lex(self, state, parser_state):
  265. with suppress(EOFError):
  266. while True:
  267. yield self.next_token(state, parser_state)
  268. def next_token(self, lex_state, parser_state=None):
  269. line_ctr = lex_state.line_ctr
  270. while line_ctr.char_pos < len(lex_state.text):
  271. res = self.match(lex_state.text, line_ctr.char_pos)
  272. if not res:
  273. allowed = {v for m, tfi in self.mres for v in tfi.values()} - self.ignore_types
  274. if not allowed:
  275. allowed = {"<END-OF-FILE>"}
  276. raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
  277. allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token],
  278. state=parser_state, terminals_by_name=self.terminals_by_name)
  279. value, type_ = res
  280. if type_ not in self.ignore_types:
  281. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  282. line_ctr.feed(value, type_ in self.newline_types)
  283. t.end_line = line_ctr.line
  284. t.end_column = line_ctr.column
  285. t.end_pos = line_ctr.char_pos
  286. if t.type in self.callback:
  287. t = self.callback[t.type](t)
  288. if not isinstance(t, Token):
  289. raise LexError("Callbacks must return a token (returned %r)" % t)
  290. lex_state.last_token = t
  291. return t
  292. else:
  293. if type_ in self.callback:
  294. t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  295. self.callback[type_](t2)
  296. line_ctr.feed(value, type_ in self.newline_types)
  297. # EOF
  298. raise EOFError(self)
  299. class LexerState:
  300. __slots__ = 'text', 'line_ctr', 'last_token'
  301. def __init__(self, text, line_ctr, last_token=None):
  302. self.text = text
  303. self.line_ctr = line_ctr
  304. self.last_token = last_token
  305. def __copy__(self):
  306. return type(self)(self.text, copy(self.line_ctr), self.last_token)
  307. class ContextualLexer(Lexer):
  308. def __init__(self, conf, states, always_accept=()):
  309. terminals = list(conf.terminals)
  310. terminals_by_name = conf.terminals_by_name
  311. trad_conf = copy(conf)
  312. trad_conf.terminals = terminals
  313. lexer_by_tokens = {}
  314. self.lexers = {}
  315. for state, accepts in states.items():
  316. key = frozenset(accepts)
  317. try:
  318. lexer = lexer_by_tokens[key]
  319. except KeyError:
  320. accepts = set(accepts) | set(conf.ignore) | set(always_accept)
  321. lexer_conf = copy(trad_conf)
  322. lexer_conf.terminals = [terminals_by_name[n] for n in accepts if n in terminals_by_name]
  323. lexer = TraditionalLexer(lexer_conf)
  324. lexer_by_tokens[key] = lexer
  325. self.lexers[state] = lexer
  326. assert trad_conf.terminals is terminals
  327. self.root_lexer = TraditionalLexer(trad_conf)
  328. def make_lexer_state(self, text):
  329. return self.root_lexer.make_lexer_state(text)
  330. def lex(self, lexer_state, parser_state):
  331. try:
  332. while True:
  333. lexer = self.lexers[parser_state.position]
  334. yield lexer.next_token(lexer_state, parser_state)
  335. except EOFError:
  336. pass
  337. except UnexpectedCharacters as e:
  338. # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, but not in the current context.
  339. # This tests the input against the global context, to provide a nicer error.
  340. try:
  341. last_token = lexer_state.last_token # Save last_token. Calling root_lexer.next_token will change this to the wrong token
  342. token = self.root_lexer.next_token(lexer_state, parser_state)
  343. raise UnexpectedToken(token, e.allowed, state=parser_state, token_history=[last_token], terminals_by_name=self.root_lexer.terminals_by_name)
  344. except UnexpectedCharacters:
  345. raise e # Raise the original UnexpectedCharacters. The root lexer raises it with the wrong expected set.
  346. class LexerThread:
  347. """A thread that ties a lexer instance and a lexer state, to be used by the parser"""
  348. def __init__(self, lexer, text):
  349. self.lexer = lexer
  350. self.state = lexer.make_lexer_state(text)
  351. def lex(self, parser_state):
  352. return self.lexer.lex(self.state, parser_state)
  353. ###}