Fix a bug with function name registration. Improve the handling of toplevel parsing, which required some helper refactoring