Circular reference detection

A basic way of avoiding stack overflows with circular references in a
type hierarchy. Looks a bit messy but I have a feeling it can be
refactored into something nicer. Related to #20