Foreach scope fixing and type checking