Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
internal/astutil/cursor: Cursor API for inspector
This CL defines the Cursor type, which represents a node in the traversal done by go/ast/inspector (represented by the index of its push event). From this, we can derive all the operators for navigating the AST in the four "cardinal directions", similar to the DOM of a web browser: - Parent (the immediate parent) - Stack (all ancestors) - Children, FirstChild, and LastChild - PrevSibling and NextSibling All operations are O(1) except Parent, which is O(n) for a node in a list of length n. In addition, all the usual traversals over the inspector can be offered as traversals within a subtree rooted at a given node, allowing multi-level traversals with independent control over type-based node filtering and independent control over pruning descent into subtrees. We can also provide fast means to obtain the cursor for a particular node or position. - Cursor.Inspect(types []ast.Node, f func(c Cursor, push bool) (bool)) - Cursor.Preorder(types ...ast.Node) iter.Seq[Cursor] - Cursor.FindNode(n ast.Node) (Cursor, bool) - Cursor.FindPos(start, end token.Pos) (Cursor, bool) All of these operations are simple to express using inspector's existing threaded tree representation, and they make it both simpler and more efficient to express the kinds of queries that turn up in our refactoring efforts. For example: "Find all function literals; then find all defer statements within them; then go to the previous statement to see if it is a call to Mutex.Lock" etc. This CL also includes one token usage of Cursor from an existing analyzer. The CursorStack benchmark is significantly slower than the existing WithStack operation, but I suspect the frequency of calls to Cursor.Stack is actually much rarer in practice than the benchmark would suggest, because one typically calls Stack only after a highly selective filtering. When Stack is called infrequently, the Cursor-based traversal is about 27% faster while still providing the option to obtain the stack when needed. We will evaluate these operators in the coming weeks and update proposal golang/go#70859 in light of our experience. In the meantime, we must use linkname hackery to augment the existing inspector for use in gopls. Updates golang/go#70859 Change-Id: I1ec8c1a20dc07ad80dad8f0038c0cf3f8f791050 Reviewed-on: https://go-review.googlesource.com/c/tools/+/636656 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Robert Findley <[email protected]>
- Loading branch information