Handle hoisted functions better in reference collection. Fixes issue 354