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.

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