I don't understand this. Explain?

Hi, so I saw Fransesc Campoy’s youtube vid on parser and ast, and was trying it out. I don’t understand how the v is increasing and decreasing to modify the tabs. so I printed them out, and still don’t understand.
What I thought initially:
the visitor 0 visits ast.Ident
then visitor 1 visits
so the next visitor should revert back to 1 but it is actually 2
then after the 2 changes to 3 changes to 4 (instead of 3 as I thought)
i thought the next one should be 4 -> 5 but it changes back to 3

now I’m confused… i thought it was depth of tree or something, but it doesn’t match up. Help?

Check out the documentation of ast.Walk. It says:

Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).

So ast.Walk essentially does this:

w := v.Visit(n)
if w == nil {
    return
}
for _, child in range hypotheticalGetChildNodesFunction(n) {
    Walk(n, w)
}

So ast.Walk is recursive. When an inner call to ast.Walk returns, it “restores” the visitor (technically it’s not restoring, it’s still the same local visitor variable from before).

You can check the source code to ast.Walk to see that instead of my hypotheticalGetChildNodesFunction, the Walk function actually uses a type switch because there is a known set of ast.Expr implementations to check against.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.