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.

493 lines
17 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. inst = super(Token, cls).__new__(cls, value)
  93. except UnicodeDecodeError:
  94. value = value.decode('latin1')
  95. inst = super(Token, cls).__new__(cls, value)
  96. inst.type = type_
  97. inst.start_pos = start_pos
  98. inst.value = value
  99. inst.line = line
  100. inst.column = column
  101. inst.end_line = end_line
  102. inst.end_column = end_column
  103. inst.end_pos = end_pos
  104. return inst
  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: 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, scanner):
  150. self.scanner = scanner
  151. def __call__(self, t):
  152. res = self.scanner.match(t.value, 0)
  153. if res:
  154. _value, t.type = res
  155. return t
  156. class CallChain:
  157. def __init__(self, callback1, callback2, cond):
  158. self.callback1 = callback1
  159. self.callback2 = callback2
  160. self.cond = cond
  161. def __call__(self, t):
  162. t2 = self.callback1(t)
  163. return self.callback2(t) if self.cond(t2) else t2
  164. def _get_match(re_, regexp, s, flags):
  165. m = re_.match(regexp, s, flags)
  166. if m:
  167. return m.group(0)
  168. def _create_unless(terminals, g_regex_flags, re_, use_bytes):
  169. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  170. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  171. embedded_strs = set()
  172. callback = {}
  173. for retok in tokens_by_type.get(PatternRE, []):
  174. unless = []
  175. for strtok in tokens_by_type.get(PatternStr, []):
  176. if strtok.priority > retok.priority:
  177. continue
  178. s = strtok.pattern.value
  179. if s == _get_match(re_, retok.pattern.to_regexp(), s, g_regex_flags):
  180. unless.append(strtok)
  181. if strtok.pattern.flags <= retok.pattern.flags:
  182. embedded_strs.add(strtok)
  183. if unless:
  184. callback[retok.name] = UnlessCallback(Scanner(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
  185. new_terminals = [t for t in terminals if t not in embedded_strs]
  186. return new_terminals, callback
  187. class Scanner:
  188. def __init__(self, terminals, g_regex_flags, re_, use_bytes, match_whole=False):
  189. self.terminals = terminals
  190. self.g_regex_flags = g_regex_flags
  191. self.re_ = re_
  192. self.use_bytes = use_bytes
  193. self.match_whole = match_whole
  194. self.allowed_types = {t.name for t in self.terminals}
  195. self._mres = self._build_mres(terminals, len(terminals))
  196. def _build_mres(self, terminals, max_size):
  197. # Python sets an unreasonable group limit (currently 100) in its re module
  198. # Worse, the only way to know we reached it is by catching an AssertionError!
  199. # This function recursively tries less and less groups until it's successful.
  200. postfix = '$' if self.match_whole else ''
  201. mres = []
  202. while terminals:
  203. pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
  204. if self.use_bytes:
  205. pattern = pattern.encode('latin-1')
  206. try:
  207. mre = self.re_.compile(pattern, self.g_regex_flags)
  208. except AssertionError: # Yes, this is what Python provides us.. :/
  209. return self._build_mres(terminals, max_size//2)
  210. mres.append((mre, {i: n for n, i in mre.groupindex.items()}))
  211. terminals = terminals[max_size:]
  212. return mres
  213. def match(self, text, pos):
  214. for mre, type_from_index in self._mres:
  215. m = mre.match(text, pos)
  216. if m:
  217. return m.group(0), type_from_index[m.lastindex]
  218. def _regexp_has_newline(r: str):
  219. r"""Expressions that may indicate newlines in a regexp:
  220. - newlines (\n)
  221. - escaped newline (\\n)
  222. - anything but ([^...])
  223. - any-char (.) when the flag (?s) exists
  224. - spaces (\s)
  225. """
  226. return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r)
  227. class Lexer(object):
  228. """Lexer interface
  229. Method Signatures:
  230. lex(self, text) -> Iterator[Token]
  231. """
  232. lex = NotImplemented
  233. def make_lexer_state(self, text):
  234. line_ctr = LineCounter(b'\n' if isinstance(text, bytes) else '\n')
  235. return LexerState(text, line_ctr)
  236. class TraditionalLexer(Lexer):
  237. def __init__(self, conf):
  238. terminals = list(conf.terminals)
  239. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  240. self.re = conf.re_module
  241. if not conf.skip_validation:
  242. # Sanitization
  243. for t in terminals:
  244. try:
  245. self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags)
  246. except self.re.error:
  247. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  248. if t.pattern.min_width == 0:
  249. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  250. if not (set(conf.ignore) <= {t.name for t in terminals}):
  251. raise LexError("Ignore terminals are not defined: %s" % (set(conf.ignore) - {t.name for t in terminals}))
  252. # Init
  253. self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
  254. self.ignore_types = frozenset(conf.ignore)
  255. terminals.sort(key=lambda x: (-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  256. self.terminals = terminals
  257. self.user_callbacks = conf.callbacks
  258. self.g_regex_flags = conf.g_regex_flags
  259. self.use_bytes = conf.use_bytes
  260. self.terminals_by_name = conf.terminals_by_name
  261. self._scanner = None
  262. def _build_scanner(self):
  263. terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, self.re, self.use_bytes)
  264. assert all(self.callback.values())
  265. for type_, f in self.user_callbacks.items():
  266. if type_ in self.callback:
  267. # Already a callback there, probably UnlessCallback
  268. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  269. else:
  270. self.callback[type_] = f
  271. self._scanner = Scanner(terminals, self.g_regex_flags, self.re, self.use_bytes)
  272. @property
  273. def scanner(self):
  274. if self._scanner is None:
  275. self._build_scanner()
  276. return self._scanner
  277. def match(self, text, pos):
  278. return self.scanner.match(text, pos)
  279. def lex(self, state, parser_state):
  280. with suppress(EOFError):
  281. while True:
  282. yield self.next_token(state, parser_state)
  283. def next_token(self, lex_state, parser_state=None):
  284. line_ctr = lex_state.line_ctr
  285. while line_ctr.char_pos < len(lex_state.text):
  286. res = self.match(lex_state.text, line_ctr.char_pos)
  287. if not res:
  288. allowed = self.scanner.allowed_types - self.ignore_types
  289. if not allowed:
  290. allowed = {"<END-OF-FILE>"}
  291. raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
  292. allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token],
  293. state=parser_state, terminals_by_name=self.terminals_by_name)
  294. value, type_ = res
  295. if type_ not in self.ignore_types:
  296. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  297. line_ctr.feed(value, type_ in self.newline_types)
  298. t.end_line = line_ctr.line
  299. t.end_column = line_ctr.column
  300. t.end_pos = line_ctr.char_pos
  301. if t.type in self.callback:
  302. t = self.callback[t.type](t)
  303. if not isinstance(t, Token):
  304. raise LexError("Callbacks must return a token (returned %r)" % t)
  305. lex_state.last_token = t
  306. return t
  307. else:
  308. if type_ in self.callback:
  309. t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  310. self.callback[type_](t2)
  311. line_ctr.feed(value, type_ in self.newline_types)
  312. # EOF
  313. raise EOFError(self)
  314. class LexerState(object):
  315. __slots__ = 'text', 'line_ctr', 'last_token'
  316. def __init__(self, text, line_ctr, last_token=None):
  317. self.text = text
  318. self.line_ctr = line_ctr
  319. self.last_token = last_token
  320. def __eq__(self, other):
  321. if not isinstance(other, LexerState):
  322. return NotImplemented
  323. return self.text is other.text and self.line_ctr == other.line_ctr and self.last_token == other.last_token
  324. def __copy__(self):
  325. return type(self)(self.text, copy(self.line_ctr), self.last_token)
  326. class ContextualLexer(Lexer):
  327. def __init__(self, conf, states, always_accept=()):
  328. terminals = list(conf.terminals)
  329. terminals_by_name = conf.terminals_by_name
  330. trad_conf = copy(conf)
  331. trad_conf.terminals = terminals
  332. lexer_by_tokens = {}
  333. self.lexers = {}
  334. for state, accepts in states.items():
  335. key = frozenset(accepts)
  336. try:
  337. lexer = lexer_by_tokens[key]
  338. except KeyError:
  339. accepts = set(accepts) | set(conf.ignore) | set(always_accept)
  340. lexer_conf = copy(trad_conf)
  341. lexer_conf.terminals = [terminals_by_name[n] for n in accepts if n in terminals_by_name]
  342. lexer = TraditionalLexer(lexer_conf)
  343. lexer_by_tokens[key] = lexer
  344. self.lexers[state] = lexer
  345. assert trad_conf.terminals is terminals
  346. self.root_lexer = TraditionalLexer(trad_conf)
  347. def make_lexer_state(self, text):
  348. return self.root_lexer.make_lexer_state(text)
  349. def lex(self, lexer_state, parser_state):
  350. try:
  351. while True:
  352. lexer = self.lexers[parser_state.position]
  353. yield lexer.next_token(lexer_state, parser_state)
  354. except EOFError:
  355. pass
  356. except UnexpectedCharacters as e:
  357. # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, but not in the current context.
  358. # This tests the input against the global context, to provide a nicer error.
  359. try:
  360. last_token = lexer_state.last_token # Save last_token. Calling root_lexer.next_token will change this to the wrong token
  361. token = self.root_lexer.next_token(lexer_state, parser_state)
  362. raise UnexpectedToken(token, e.allowed, state=parser_state, token_history=[last_token], terminals_by_name=self.root_lexer.terminals_by_name)
  363. except UnexpectedCharacters:
  364. raise e # Raise the original UnexpectedCharacters. The root lexer raises it with the wrong expected set.
  365. class LexerThread(object):
  366. """A thread that ties a lexer instance and a lexer state, to be used by the parser"""
  367. def __init__(self, lexer, text):
  368. self.lexer = lexer
  369. self.state = lexer.make_lexer_state(text)
  370. def lex(self, parser_state):
  371. return self.lexer.lex(self.state, parser_state)
  372. def __copy__(self):
  373. copied = object.__new__(LexerThread)
  374. copied.lexer = self.lexer
  375. copied.state = copy(self.state)
  376. return copied
  377. ###}