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.

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