In a quick glance this code seems close to completely brain dead :-( For one thing, why isn't it making separate determinations about whether the left and right inputs of the UNION (resp INTERSECT or EXCEPT) operator need to be parenthesized? After that maybe we could figure out what the individual decisions need to be.
Well it's the work of 5 seconds to have two separate tests. What I don't feel confident in doing is getting the tests themselves right. That's why I can't really do it...
---------------------------(end of broadcast)--------------------------- TIP 4: Don't 'kill -9' the postmaster