[Libre-soc-bugs] [Bug 1094] insndb instruction database visitor-walker is needed

bugzilla-daemon at libre-soc.org bugzilla-daemon at libre-soc.org
Sun Jun 4 23:08:07 BST 2023


https://bugs.libre-soc.org/show_bug.cgi?id=1094

--- Comment #47 from Luke Kenneth Casson Leighton <lkcl at lkcl.net> ---
another example:

https://stackoverflow.com/questions/1515357/simple-example-of-how-to-use-ast-nodevisitor/26374977#26374977

which is the same programming-concept as this
https://github.com/mbr/visitor/blob/master/visitor/__init__.py

but made much more generic.

that leads me to ast.py in python itself:

https://github.com/python/cpython/blob/1237fb6a4b177ce8f750949b9006c58f9f22942e/Lib/ast.py#L1667

BLECH!

    def visit_Lambda(self, node):
        with self.require_parens(_Precedence.TEST, node):
            self.write("lambda")
            with self.buffered() as buffer:
>>>>>>          self.traverse(node.args)   <<< EUURRRRRRG!
            if buffer:
                self.write(" ", *buffer)
            self.write(": ")
            self.set_precedence(_Precedence.TEST, node.body)
            self.traverse(node.body)


NOOOO! :)


i have a horrible feeling that stackoverflow answer is referring to an
older version of python.... ah yes it was

https://github.com/python/cpython/blob/2.7/Lib/ast.py

that's MUCH better.

ah HA!  see iter_fields(node).  it is *self-describing* thanks to fields,
and performs "yield"... 

  def iter_fields(node):
    for field in node._fields:
        try:
            yield field, getattr(node, field)
        except AttributeError:
            pass

and... ah HA! 

  class NodeVisitor(object):
      def visit(self, node):
          """Visit a node."""
          method = 'visit_' + node.__class__.__name__
          visitor = getattr(self, method, self.generic_visit)
          return visitor(node)

      def generic_visit(self, node):
        """Called if no explicit visitor function exists for a node."""
        for field, value in iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, AST):
                        self.visit(item)
            elif isinstance(value, AST):
                self.visit(value)

that's... that's awesome.  it's abstracting-out the field-definitions
and allowing for walking of them.

ah ha!  we have _fields already in the insndb!

ta-daaaa!

-- 
You are receiving this mail because:
You are on the CC list for the bug.


More information about the libre-soc-bugs mailing list