Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Python's exec and eval were compiled?

Can the equivalent of eval and exec exist in a compiled language? If so, how would they be compiled (roughly speaking)?

like image 836
Nick Avatar asked Jan 06 '11 03:01

Nick


2 Answers

For starters, python is a compiled language, it just does the compilation at runtime. That being said, all that you need to do to implement eval in any other compiled language is to be able to run the compiler (and dynamically load object code) - you can do this in Python (and a litany of other languages) easily because the compiler is an integral part of the runtime. There's technically nothing that stops a program written in C from invoking the compiler and loading the result at runtime (using dlopen), it's just not a common occurrence because the C runtime doesn't require a compiler, so most users don't have one.

like image 66
Nick Bastin Avatar answered Sep 22 '22 21:09

Nick Bastin


Certainly, various Lisp environments have had this capability for decades. A Lisp compiler typically works on a per-function basis, and the compiler and runtime system work hand in hand.

When asked to eval something, the Lisp runtime environment will pass the list (a data structure) to the compiler for compiling. The compiler may generate machine code (or maybe bytecode, depending on the system), and then the function will be callable at the machine level just like every other function in the program.

like image 20
Greg Hewgill Avatar answered Sep 22 '22 21:09

Greg Hewgill