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.

530 lines
18 KiB

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