Interacting with the tree

Static and Dynamic Symbols

The AST tree is composed of 3 types of symbols:

  • Static symbols: Symbol<T> where T implements AstSymbol.
  • Dynamic symbols: DynSymbol which is a trait object that wraps a Symbol<T>.
  • Weak symbols: WeakSymbol which is a weak reference to a DynSymbol.

Dynamic symbols implement downcasting thanks to the downcast_rs crate.

Weak symbols can be upgraded to a dynamic symbol using the WeakSymbol::to_dyn method.

Static symbols offer better performance due to static dispatch and type safety, while dynamic symbols are useful for referencing symbols anywhere in the tree or performing method calls without needing to worry about the type.

Walking the tree

While the tree does not implement iterators, it still provides methods to locate a node or walk inside:

  • descendant_at: Find the lowest node in the tree at the given offset.
  • descendant_at_and_collect: Find the lowest node in the tree at the given offset and clones all nodes matching the closure's condition.
  • traverse_and_collect: Find the lowest node in the tree at the given offset and clone all nodes that match the closure's condition.

All methods that imply walking the tree will return a DynSymbol that can be downcasted to the desired type.

In addition, all symbols have a get_parent mmethod to retrieve the parent symbol. Since the parent might be dropped, which could invalidate the child nodes, a WeakSymbol returned and must be upgraded to a DynSymbol when used.

Warning

It is strongly discouraged to store symbols or manually edit them, as this may lead to memory leaks or an inconsistent tree.