For simple tracks, there's a number of options. You can do grammars, but I'd prefer vectors (I'm a math major, not a linguistics major). You have some starting point and a set of vectors (your track pieces). Each vector modifies the current position by providing a new position based on the old one in a relative fashion. Then, using basic vector math, you can determine if a given layout is closed or not.
My criteria for good software:
- Does it work?
- Can someone else come in, make a change, and be reasonably certain no bugs were introduced?