Compiler optimizations for Scopes, checkDoubleDefs

Resubmission of #3771, adds a unit test for Scope and
fixes the boostrap error from the previous attempt.

Review by @gkossakowsi