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