3

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.

4

1 回答 1

4

动态类型语言的编译器只会在必要时生成检查类型的指令。事实上,即使对于某些静态类型的语言,这有时也是必要的,例如,在具有检查强制转换的面向对象语言的情况下(如dynamic_cast在 C++ 中)。在动态类型语言中,它只是更频繁地需要。

为了使这些检查成为可能,每个值都需要以跟踪其类型的方式表示。在动态类型语言中表示值的一种常用方法是将它们表示为指向包含类型和值的结构的指针(作为一种优化,在(足够小的)整数的情况下,通常通过将整数直接存储为一个无效的指针(通过将整数左移一位并设置其最低有效位)。

于 2014-07-19T22:28:53.253 回答