Search code examples
programming-languagesdynamic-typingcompiledtype-theory

Compiled Language with Dynamic Typing


I'm a bit confused when it comes to a compiled language (compilation to native code) with dynamic typing. Dynamic typing says that the types in a program are only inferred at runtime.

Now if a language is compiled, there's no interpreter running at runtime; it's just your CPU reading instructions off memory and executing them. In such a scenario, if any instruction violating the type semantics of the language happens to execute at runtime, there's no interpreter to intercept the execution of the program and throw any errors. How does the system work then?

What happens when an instruction violating the type semantics of a dynamically typed compiled language is executed at runtime?

PS: Some of the dynamically typed compiled languages I know of include Scheme, Lua and Common Lisp.


Solution

  • A compiler for a dynamically typed language would simply generate instructions that check the type where necessary. In fact even for some statically typed languages this is sometimes necessary, say, in case of an object oriented language with checked casts (like dynamic_cast in C++). In dynamically types languages it is simply necessary more often.

    For these checks to be possible each value needs to be represented in a way that keeps track of its type. A common way to represent values in dynamically typed languages is to represent them as pointers to a struct that contains the type as well as the value (as an optimization this is often avoided in case of (sufficiently small) integers by storing the integer directly as an invalid pointer (by shifting the integer one to the left and setting its least significant bit)).