Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-work EmPy token caching #662

Merged
merged 2 commits into from
Sep 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 29 additions & 22 deletions colcon_core/shell/template/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from io import StringIO
import os

from colcon_core.generic_decorator import GenericDecorator
from colcon_core.logging import colcon_logger
try:
from em import Interpreter
Expand Down Expand Up @@ -69,25 +70,31 @@ def installProxy(self): # noqa: D102 N802


class CachingInterpreter(BypassStdoutInterpreter):
"""Interpreter for EmPy which which caches parsed tokens."""

def parse(self, scanner, locals=None): # noqa: A002 D102
global cached_tokens
data = scanner.buffer
# try to use cached tokens
tokens = cached_tokens.get(data)
if tokens is None:
# collect tokens and cache them
tokens = []
while True:
token = scanner.one()
if token is None:
break
tokens.append(token)
cached_tokens[data] = tokens

# reimplement the parse method using the (cached) tokens
self.invoke('atParse', scanner=scanner, locals=locals)
for token in tokens:
self.invoke('atToken', token=token)
token.run(self, locals)
"""Interpreter for EmPy which caches parsed tokens."""

class _CachingScannerDecorator(GenericDecorator):

def __init__(self, decoree, cache):
super().__init__(decoree, _cache=cache, _idx=0)

def one(self, *args, **kwargs):
try:
token, count = self._cache[self._idx]
except IndexError:
count = len(self._decoree)
token = self._decoree.one(*args, **kwargs)
count -= len(self._decoree)
self._cache.append((token, count))
else:
self.advance(count)
self.sync()
cottsay marked this conversation as resolved.
Show resolved Hide resolved

self._idx += 1
return token

def parse(self, scanner, *args, **kwargs): # noqa: A002 D102
cache = cached_tokens.setdefault(scanner.buffer, [])
return super().parse(
CachingInterpreter._CachingScannerDecorator(scanner, cache),
*args,
**kwargs)
Loading