Lately I came across the eval() function in a couple of places (some D and JavaScript code). This experience make me realize that I didn’t understand the difference between a language with or without eval().
In fact, I have been able to survive without using it (although sometimes is tempting :)).
Do you know from any fundamental difference between a language implementing eval() and a language that does not implement it (even if it is at compile time)? If there is no fundamental difference is there an expressiveness difference?
Do you know any paper or reference explaining what is the added computational power/expressiveness provided by eval()? This is, What can we implement with eval() that we can not implement without it (or at a higher cost)?
There is no difference in capability between a language with
evaland a language without. You can always implementevalyourself in a language that doesn’t have it, although it is easier in some languages (Lisp) and harder in other languages (C). This is why we know it doesn’t add any new capabilities to a language.Eval is generally considered “powerful but dangerous and unnecessary in production code”. If you ever get your source code reviewed, and it uses
eval, you will have to get used to people telling you not to useeval. Usually, if you useeval, there is a more straightforward and safer way to accomplish the same task.Security vulnerabilities
The
evalfunction often leads to security vulnerabilities, such as in web applications. For example, in Python:The
inputfunction in Python prior to 3.x evaluates the user input, leading to security problems:Enter a number> __import__('os').system('rm -rf $HOME') # DO NOT TRY THISThis can be avoided in fully sandboxed runtimes, such as JavaScript, Lua, CLI, etc. However, in code that is not sandboxed, it is just too difficult to use
evalsafely.REPL
The one glorious use of
evalis the REPL, which is a useful tool for software development. In Google Chrome, you can bring a REPL up right now by pressing Ctrl+Shift+I — just start typing JavaScript in the box that comes up. Firefox and Safari both have REPLs too.Why not include
eval?The
evalfunction is usually incredibly complex. Including it in the standard library means that the library or runtime has to include a complete compiler or interpreter for the language, which is a hefty chunk of code. That’s why you usually seeevalin languages that are typically interpreted or JITed — Lisp, Python, and JavaScript runtimes typically already include a complete compiler, soevalis no extra baggage.Implementations of
evalfor C are real beasts, so they’re optional and shoved into libraries.