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.

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