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.

494 lines
17 KiB

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