Wednesday, June 5, 2013

type checking a program

The previous post talked about treating the program as a list of functions. The program is type correct when all the functions are type correct. The functions are type checked using a symbol table where all the functions are bound to their type. This is done with two passes over the list of functions. One to build the symbol table and the other to check the function definitions using the table. With an additional helper function to get the pair of function's declared name and type, which consists of the types of the arguments and the types of the result, we can build the symbol table and then check the function definitions.
Assignments, data structures and overloading can also be type-checked. When a variable is given a value by an assignment, its type can be checked. Whether the variable had a previously assigned value or if the assigned value is never used are additional checks that can be performed but they are not based on the structural information that type checking depends on.
To check the data structures such as structs or a value that maybe of different types, the type checker uses a data structure similar to the one used by the abstract syntax trees of declarations. When the structured data is modified by operations that have well defined types for arguments and result, then they can be type checked just like functions.
When methods are overloaded, the same name is used for several different operations. They can all be tried one after the other and the expected type and arguments can be used to pick the matching one.
When a function is defined as a polymorphic type, the type checker can insert the actual types at every use of the generic / polymorphic type. This is different from type checking overloaded methods in that the function can be instantiated by any type and not just limited by a limited list of declared alternatives.
If the program uses implicit types, a type inference algorithm gathers information about the uses of functions and variables with which it infers the types.
Thus we have seen the type checking for expressions, function declarations and programs. Type-checking enforcing static type correctness and adds to the checks for the correctness of a program. This kind of checking is often not context free and hence it is done conceptually after lexing and parsing though it could be interleaved with the syntax analysis.
Also, translator may exploit or depend on type information in which case type checking may be combined with the actual translation.
Some other constructs of a language also adds to type safety. For example, virtual functions, templates, static_casts all improve type checking.
(text from Mogensen) 

No comments:

Post a Comment