LibCST icon indicating copy to clipboard operation
LibCST copied to clipboard

Using inverse of matcher errors for visit decorators

Open SamLau95 opened this issue 4 years ago • 1 comments

Sorry if this comes across as a newbie question!

I'd like to call a visit function whenever I visit a node that isn't whitespace, like so:

import libcst as cst
import libcst.matchers as m

whitespace = (m.Comment() | m.EmptyLine() | m.Newline()
              | m.ParenthesizedWhitespace() | m.SimpleWhitespace()
              | m.TrailingWhitespace() | m.BaseParenthesizableWhitespace())

class LoggingVisitor(m.MatcherDecoratableVisitor):
    @m.visit(~whitespace)
    def visit_not_whitespace(self, node):
        print('hello')

However, this code errors:

  File "/Users/sam/anaconda3/lib/python3.8/site-packages/libcst/matchers/_visitors.py", line 680, in __init__
    _check_types(
  File "/Users/sam/anaconda3/lib/python3.8/site-packages/libcst/matchers/_visitors.py", line 222, in _check_types
    possible_match_classes = _get_possible_match_classes(matcher)
  File "/Users/sam/anaconda3/lib/python3.8/site-packages/libcst/matchers/_visitors.py", line 77, in _get_possible_match_classes
    return [getattr(cst, m.__class__.__name__) for m in matcher.options]
  File "/Users/sam/anaconda3/lib/python3.8/site-packages/libcst/matchers/_visitors.py", line 77, in <listcomp>
    return [getattr(cst, m.__class__.__name__) for m in matcher.options]
AttributeError: module 'libcst' has no attribute '_InverseOf'

Is this intended behavior? Or is there a workaround for this that I'm not seeing?

I suspect this is happening because inverting a matcher creates an _InverseOf object, but this object doesn't correspond directly to any concrete nodes from libcst.

(I'm using Python 3.8 and libcst v0.3.18.)

SamLau95 avatar Nov 04 '21 07:11 SamLau95

I have to admit I'm not intimate with the matcher API, but I'd expect something like your use case to work. Marking this issue as a bug

zsol avatar Dec 20 '21 12:12 zsol