rewritePostOrder function

Node rewritePostOrder(
  1. Node n,
  2. Node fn(
    1. Node
    ), {
  3. bool skip(
    1. Node
    )?,
  4. bool prune(
    1. Node
    )?,
})

Post-order tree rewrite:

  • Optionally rewrites children first (unless pruned)
  • Then applies fn to the node

Controls:

  • skip: if true, returns node as-is (no children rewrite, no fn)
  • prune: if true, does NOT rewrite children but DOES run fn(node)

Implementation

Node rewritePostOrder(
  Node n,
  Node Function(Node) fn, {
  bool Function(Node)? skip,
  bool Function(Node)? prune,
}) {
  if (skip != null && skip(n)) return n;

  final isPruned = prune != null && prune(n);

  if (!isPruned && n is GroupNode) {
    final kids = n.childrenOrEmpty;

    var changed = false;
    final nextKids = <Node>[];

    for (final c in kids) {
      final nc = rewritePostOrder(c, fn, skip: skip, prune: prune);
      if (!identical(nc, c)) changed = true;
      nextKids.add(nc);
    }

    if (changed) {
      n = n.copyWith(children: nextKids);
    }
  }

  return fn(n);
}