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.

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