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.

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