Rewrite resolver to be more comprehensible

Avoiding mutable state and instead transforming the tree as we resolve it. Fixes #177 and probably a variety of other subtle issues.