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.

540 rivejä
18 KiB

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