|
| 1 | +"""Cache libcst visitor dispatch table construction. |
| 2 | +
|
| 3 | +libcst's ``MatcherDecoratableTransformer`` and |
| 4 | +``MatcherDecoratableVisitor`` rebuild visitor dispatch tables on |
| 5 | +every instantiation by iterating ``dir(self)`` (~600 attributes) |
| 6 | +and calling ``getattr`` + ``inspect.ismethod`` on each. The |
| 7 | +results depend only on the class, not the instance, so caching |
| 8 | +by ``type(obj)`` is safe. |
| 9 | +
|
| 10 | +Import this module before any libcst visitors are instantiated |
| 11 | +to install the cache. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +import libcst.matchers._visitors as _mv |
| 19 | + |
| 20 | +_visit_cache: dict[type, Any] = {} |
| 21 | +_leave_cache: dict[type, Any] = {} |
| 22 | +_matchers_cache: dict[type, Any] = {} |
| 23 | + |
| 24 | +_original_visit = _mv._gather_constructed_visit_funcs # noqa: SLF001 |
| 25 | +_original_leave = _mv._gather_constructed_leave_funcs # noqa: SLF001 |
| 26 | +_original_matchers = _mv._gather_matchers # noqa: SLF001 |
| 27 | + |
| 28 | + |
| 29 | +def _cached_visit(obj: object) -> Any: |
| 30 | + """Return cached visit-function dispatch table for the object's class.""" |
| 31 | + cls = type(obj) |
| 32 | + try: |
| 33 | + return _visit_cache[cls] |
| 34 | + except KeyError: |
| 35 | + result = _original_visit(obj) |
| 36 | + _visit_cache[cls] = result |
| 37 | + return result |
| 38 | + |
| 39 | + |
| 40 | +def _cached_leave(obj: object) -> Any: |
| 41 | + """Return cached leave-function dispatch table for the object's class.""" |
| 42 | + cls = type(obj) |
| 43 | + try: |
| 44 | + return _leave_cache[cls] |
| 45 | + except KeyError: |
| 46 | + result = _original_leave(obj) |
| 47 | + _leave_cache[cls] = result |
| 48 | + return result |
| 49 | + |
| 50 | + |
| 51 | +def _cached_matchers(obj: object) -> Any: |
| 52 | + """Return cached matcher dispatch table for the object's class.""" |
| 53 | + cls = type(obj) |
| 54 | + try: |
| 55 | + return dict(_matchers_cache[cls]) |
| 56 | + except KeyError: |
| 57 | + result = _original_matchers(obj) |
| 58 | + _matchers_cache[cls] = result |
| 59 | + return dict(result) |
| 60 | + |
| 61 | + |
| 62 | +_mv._gather_constructed_visit_funcs = _cached_visit # noqa: SLF001 |
| 63 | +_mv._gather_constructed_leave_funcs = _cached_leave # noqa: SLF001 |
| 64 | +_mv._gather_matchers = _cached_matchers # noqa: SLF001 |
0 commit comments