Clean up query parser

It had some edge cases that finally annoyed me enough. This should
handle query canonicalization better.