Aha, it's called tree pattern matching, and it seems to be a bit of deep algorithmic science. I am unsurprised that it involves algorithms similar to regular expressions. Now that someone told me what it is, and sent me a link to code he had written (Thanks much Thilo :), I can actually do it.
It looks like I'm going to use the AST Visitor that Jeremy Hylton wrote to zip across the tree and fill in a state machine. Should be entertaining.