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.

491 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 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 __eq__(self, other):
  140. if not isinstance(other, LineCounter):
  141. return False
  142. return (self.newline_char == other.newline_char and self.char_pos == other.char_pos
  143. and self.line == other.line and self.column == other.column
  144. and self.line_start_pos == other.line_start_pos)
  145. def feed(self, token, test_newline=True):
  146. """Consume a token and calculate the new line & column.
  147. As an optional optimization, set test_newline=False if token doesn't contain a newline.
  148. """
  149. if test_newline:
  150. newlines = token.count(self.newline_char)
  151. if newlines:
  152. self.line += newlines
  153. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  154. self.char_pos += len(token)
  155. self.column = self.char_pos - self.line_start_pos + 1
  156. class UnlessCallback:
  157. def __init__(self, mres):
  158. self.mres = mres
  159. def __call__(self, t):
  160. for mre, type_from_index in self.mres:
  161. m = mre.match(t.value)
  162. if m:
  163. t.type = type_from_index[m.lastindex]
  164. break
  165. return t
  166. class CallChain:
  167. def __init__(self, callback1, callback2, cond):
  168. self.callback1 = callback1
  169. self.callback2 = callback2
  170. self.cond = cond
  171. def __call__(self, t):
  172. t2 = self.callback1(t)
  173. return self.callback2(t) if self.cond(t2) else t2
  174. def _create_unless(terminals, g_regex_flags, re_, use_bytes):
  175. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  176. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  177. embedded_strs = set()
  178. callback = {}
  179. for retok in tokens_by_type.get(PatternRE, []):
  180. unless = []
  181. for strtok in tokens_by_type.get(PatternStr, []):
  182. if strtok.priority > retok.priority:
  183. continue
  184. s = strtok.pattern.value
  185. m = re_.match(retok.pattern.to_regexp(), s, g_regex_flags)
  186. if m and m.group(0) == s:
  187. unless.append(strtok)
  188. if strtok.pattern.flags <= retok.pattern.flags:
  189. embedded_strs.add(strtok)
  190. if unless:
  191. callback[retok.name] = UnlessCallback(build_mres(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
  192. terminals = [t for t in terminals if t not in embedded_strs]
  193. return terminals, callback
  194. def _build_mres(terminals, max_size, g_regex_flags, match_whole, re_, use_bytes):
  195. # Python sets an unreasonable group limit (currently 100) in its re module
  196. # Worse, the only way to know we reached it is by catching an AssertionError!
  197. # This function recursively tries less and less groups until it's successful.
  198. postfix = '$' if match_whole else ''
  199. mres = []
  200. while terminals:
  201. pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
  202. if use_bytes:
  203. pattern = pattern.encode('latin-1')
  204. try:
  205. mre = re_.compile(pattern, g_regex_flags)
  206. except AssertionError: # Yes, this is what Python provides us.. :/
  207. return _build_mres(terminals, max_size//2, g_regex_flags, match_whole, re_, use_bytes)
  208. mres.append((mre, {i: n for n, i in mre.groupindex.items()}))
  209. terminals = terminals[max_size:]
  210. return mres
  211. def build_mres(terminals, g_regex_flags, re_, use_bytes, match_whole=False):
  212. return _build_mres(terminals, len(terminals), g_regex_flags, match_whole, re_, use_bytes)
  213. def _regexp_has_newline(r):
  214. r"""Expressions that may indicate newlines in a regexp:
  215. - newlines (\n)
  216. - escaped newline (\\n)
  217. - anything but ([^...])
  218. - any-char (.) when the flag (?s) exists
  219. - spaces (\s)
  220. """
  221. return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r)
  222. class Lexer(object):
  223. """Lexer interface
  224. Method Signatures:
  225. lex(self, text) -> Iterator[Token]
  226. """
  227. lex = NotImplemented
  228. def make_lexer_state(self, text):
  229. line_ctr = LineCounter(b'\n' if isinstance(text, bytes) else '\n')
  230. return LexerState(text, line_ctr)
  231. class TraditionalLexer(Lexer):
  232. def __init__(self, conf):
  233. terminals = list(conf.terminals)
  234. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  235. self.re = conf.re_module
  236. if not conf.skip_validation:
  237. # Sanitization
  238. for t in terminals:
  239. try:
  240. self.re.compile(t.pattern.to_regexp(), conf.g_regex_flags)
  241. except self.re.error:
  242. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  243. if t.pattern.min_width == 0:
  244. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  245. if not (set(conf.ignore) <= {t.name for t in terminals}):
  246. raise LexError("Ignore terminals are not defined: %s" % (set(conf.ignore) - {t.name for t in terminals}))
  247. # Init
  248. self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
  249. self.ignore_types = frozenset(conf.ignore)
  250. terminals.sort(key=lambda x: (-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  251. self.terminals = terminals
  252. self.user_callbacks = conf.callbacks
  253. self.g_regex_flags = conf.g_regex_flags
  254. self.use_bytes = conf.use_bytes
  255. self.terminals_by_name = conf.terminals_by_name
  256. self._mres = None
  257. def _build(self):
  258. terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, self.re, self.use_bytes)
  259. assert all(self.callback.values())
  260. for type_, f in self.user_callbacks.items():
  261. if type_ in self.callback:
  262. # Already a callback there, probably UnlessCallback
  263. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  264. else:
  265. self.callback[type_] = f
  266. self._mres = build_mres(terminals, self.g_regex_flags, self.re, self.use_bytes)
  267. @property
  268. def mres(self):
  269. if self._mres is None:
  270. self._build()
  271. return self._mres
  272. def match(self, text, pos):
  273. for mre, type_from_index in self.mres:
  274. m = mre.match(text, pos)
  275. if m:
  276. return m.group(0), type_from_index[m.lastindex]
  277. def lex(self, state, parser_state):
  278. with suppress(EOFError):
  279. while True:
  280. yield self.next_token(state, parser_state)
  281. def next_token(self, lex_state, parser_state=None):
  282. line_ctr = lex_state.line_ctr
  283. while line_ctr.char_pos < len(lex_state.text):
  284. res = self.match(lex_state.text, line_ctr.char_pos)
  285. if not res:
  286. allowed = {v for m, tfi in self.mres for v in tfi.values()} - self.ignore_types
  287. if not allowed:
  288. allowed = {"<END-OF-FILE>"}
  289. raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
  290. allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token],
  291. state=parser_state, terminals_by_name=self.terminals_by_name)
  292. value, type_ = res
  293. if type_ not in self.ignore_types:
  294. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  295. line_ctr.feed(value, type_ in self.newline_types)
  296. t.end_line = line_ctr.line
  297. t.end_column = line_ctr.column
  298. t.end_pos = line_ctr.char_pos
  299. if t.type in self.callback:
  300. t = self.callback[t.type](t)
  301. if not isinstance(t, Token):
  302. raise LexError("Callbacks must return a token (returned %r)" % t)
  303. lex_state.last_token = t
  304. return t
  305. else:
  306. if type_ in self.callback:
  307. t2 = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  308. self.callback[type_](t2)
  309. line_ctr.feed(value, type_ in self.newline_types)
  310. # EOF
  311. raise EOFError(self)
  312. class LexerState:
  313. __slots__ = 'text', 'line_ctr', 'last_token'
  314. def __init__(self, text, line_ctr, last_token=None):
  315. self.text = text
  316. self.line_ctr = line_ctr
  317. self.last_token = last_token
  318. def __eq__(self, other):
  319. if not isinstance(other, LexerState):
  320. return False
  321. return (self.text == other.text and self.line_ctr == other.line_ctr
  322. and self.last_token == other.last_token)
  323. def __copy__(self):
  324. return type(self)(self.text, copy(self.line_ctr), self.last_token)
  325. class ContextualLexer(Lexer):
  326. def __init__(self, conf, states, always_accept=()):
  327. terminals = list(conf.terminals)
  328. terminals_by_name = conf.terminals_by_name
  329. trad_conf = copy(conf)
  330. trad_conf.terminals = terminals
  331. lexer_by_tokens = {}
  332. self.lexers = {}
  333. for state, accepts in states.items():
  334. key = frozenset(accepts)
  335. try:
  336. lexer = lexer_by_tokens[key]
  337. except KeyError:
  338. accepts = set(accepts) | set(conf.ignore) | set(always_accept)
  339. lexer_conf = copy(trad_conf)
  340. lexer_conf.terminals = [terminals_by_name[n] for n in accepts if n in terminals_by_name]
  341. lexer = TraditionalLexer(lexer_conf)
  342. lexer_by_tokens[key] = lexer
  343. self.lexers[state] = lexer
  344. assert trad_conf.terminals is terminals
  345. self.root_lexer = TraditionalLexer(trad_conf)
  346. def make_lexer_state(self, text):
  347. return self.root_lexer.make_lexer_state(text)
  348. def lex(self, lexer_state, parser_state):
  349. try:
  350. while True:
  351. lexer = self.lexers[parser_state.position]
  352. yield lexer.next_token(lexer_state, parser_state)
  353. except EOFError:
  354. pass
  355. except UnexpectedCharacters as e:
  356. # In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, but not in the current context.
  357. # This tests the input against the global context, to provide a nicer error.
  358. try:
  359. last_token = lexer_state.last_token # Save last_token. Calling root_lexer.next_token will change this to the wrong token
  360. token = self.root_lexer.next_token(lexer_state, parser_state)
  361. raise UnexpectedToken(token, e.allowed, state=parser_state, token_history=[last_token], terminals_by_name=self.root_lexer.terminals_by_name)
  362. except UnexpectedCharacters:
  363. raise e # Raise the original UnexpectedCharacters. The root lexer raises it with the wrong expected set.
  364. class LexerThread(object):
  365. """A thread that ties a lexer instance and a lexer state, to be used by the parser"""
  366. def __init__(self, lexer, text):
  367. self.lexer = lexer
  368. self.state = lexer.make_lexer_state(text)
  369. def lex(self, parser_state):
  370. return self.lexer.lex(self.state, parser_state)
  371. def __copy__(self):
  372. copied = type(self)(
  373. self.lexer,
  374. ''
  375. )
  376. copied.state = copy(self.state)
  377. return copied
  378. ###}