We continue the development of our toy programming language. In this episode, our speaker Yuri demonstrates how to implement functions and explains how functions, scopes, and symbol lookup are built in code using C++.
About the speaker
Yuri Minaev is an experienced C++ developer, architect at PVS-Studio, and a recognized voice in the C++ community who has spoken at CppCast, C++ on Sea, and CppCon. Over the course of ten sessions, he'll guide you through each stage of building your own programming language.
Introducing scopes
Functions introduce multiple scopes and different levels of name visibility. Unlike variables, which previously existed only in the global scope, functions create their own scope. Names declared inside a function are not visible outside it, while names from parent scopes remain accessible. Compound statements can also create nested scopes.
Managing the symbol table
To resolve names, the semantic analyzer uses a symbol table that associates names with their declarators and the scopes where they appear. Two lookup methods are used. An unscoped lookup searches the current scope and then moves upward through parent scopes until it finds the name. A scoped lookup checks only a specified scope. The latter also prevents duplicate names from being declared within the same scope.
Parsing functions
A function consists of the fn keyword, a name, parameters, an optional return type, and a compound statement containing its body. Parameters have a type and a unique name. Functions are parsed in two stages: the declaration is parsed and registered in the symbol table before the body is processed. This allows the function to reference itself recursively.
Handling return types
The semantic analyzer determines a function's return type from its return statements when no type is specified. It also checks that return expressions are compatible with the function's return type and adds implicit casts when necessary. An empty function with no return statements gets the void type. Incompatible return types make the function invalid.
The talk concludes with functions implemented and introduces the evaluator as the next step.
Want more?
If you want to watch other talks, follow this link.
You can also sign up for our upcoming webinars: Let's make a programming language. Evaluator. We hope to see you there!
If you'd like to learn more about PVS-Studio analyzer, check out our website.
See ya!
Top comments (0)