[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 22:36:48 BST 2023


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

--- Comment #46 from Luke Kenneth Casson Leighton <lkcl at lkcl.net> ---
ah!

i think i know how to describe Visitor-walking.

* imagine that the original data (and its format) has been lost.
  there is no chance of recovery.
* imagine that you investigate and find a "trace log" - a print-out - of
  the ENTIRE database contents
  (a good example would be a "SQL DUMP")
* each new line in the trace-log has:
  - the TYPE of the thing
  - its CONTENTs
  - what its PARENT is

now write two COMPLETELY SEPARATE programs:

* program 1) can PRODUCE that trace-log
* program 2) can RECREATE the database - both its format and its data -
             purely FROM the trace-log

that's how Visitor-walking works.

------------------------------------

ah. i found another one, which says it is "so small you might as well
cut/paste it into your project"

    https://github.com/mbr/visitor

here's the tree-walk repro example:

https://github.com/mbr/visitor/blob/9b7dbe83ed2163b2cfc4424926b555bb636492b0/tests/example.py#L18

    def visit_list(self, node):
        self.indent += 1
        s = '[\n' + '  ' * self.indent
        s += (',\n' + '  ' * self.indent).join(self.visit(item)
                                               for item in node)
        self.indent -= 1
        s += '\n' + '  ' * self.indent + ']'
        return s

ahh yuk.  notice "self.visit(child_item)"?  that's exactly the kind of
thing that good Visitor APIs *don't* do: impose on the caller to explicitly
continue the recursive-descent.

(that is probably why you believe that pyomo's Visitor API is "complex"
 because they have abstracted-out the "tree-walking" part entirely
 from the "taking action" part)

yes, it really is this simple!

   https://github.com/mbr/visitor/blob/master/visitor/__init__.py

that's literally one function!

class Visitor(object):
    """Base class for visitors."""

    def visit(self, node):

        if isinstance(node, type):
            mro = node.mro()
        else:
            mro = type(node).mro()
        for cls in mro:
            meth = getattr(self, 'visit_' + cls.__name__, None)
            if meth is not None:
                return meth(node)

        raise NotImplementedError('No visitation method visit_{}'
                                  .format(node.__class__.__name__))


note absolutely zero use of typing!

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


More information about the libre-soc-bugs mailing list