- Eval
In some
programming language s,eval
is a function which "eval"uates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including theeval
.eval
-like functions are more common ininterpreted language s than incompiled language s, since including one in a compiled language would require including an interpreter or compiler with the program, and more runtime information (such as variable names). Some compiled languages do have something similar to an eval function, see below.Security risks
Special care must be taken when using
eval
with data from an untrusted source. For instance, assuming that theget_data()
function gets data from the Internet, this Python code is insecure:An attacker could supply the program with the string
"session.update(authenticated=True)"
as data, which would update thesession
dictionary to set an authenticated key to be True. To remedy this, all data which will be used witheval
must be escaped, or it must be run without access to potentially harmful functions.Uses
A call to
eval
is sometimes used by inexperienced programmers for all sorts of things. In most cases, there are alternatives which are more flexible and do not require the speed penalty of parsing code.For instance,
eval
is sometimes used for a simplemail merge facility, as in thisPHP example:eval
is also sometimes used in applications needing to evaluate math expressions, such asspreadsheet s. This is much easier than writing an expression parser, but finding or writing one would often be a wiser choice. Besides the fixable security risks, using the language's evaluation features would most likely be slower, and wouldn't be as customizable.Perhaps the best use of
eval
is in bootstrapping a new language (as with Lisp), and in language tutor programs which allow users to run their own programs in a controlled environment.For the purpose of expression evaluation, the major advantage of eval over expression parsers is that, in most programming environments where
eval
is supported, the expression may be arbitrarily complex, and may include calls to functions written by the user that could not have possibly been known in advance by the parser's creator. This capability allows you to effectively augment the eval() engine with a library of functions that you can enhance as needed, without having to continually maintain an expression parser. If, however, you do not need this ultimate level of flexibility, expression parsers are far more efficient and lightweight.Implementation
In
interpreted language s,eval
is almost always implemented with the same interpreter as normal code. Incompiled language s, the same compiler used to compile programs may be embedded in programs using theeval
function; separate interpreters are sometimes used, though this results incode duplication .Programming languages
JavaScript
In
JavaScript ,eval
is something of a hybrid between an expression evaluator and a statement executor. It returns the result of the last expression evaluated (all statements are expressions in both Javascript & ActionScript), and allows the final semicolon to be left off.Example as an expression evaluator:
Example as a statement executor:
One use of Javascript's
eval
is to parseJSON text, perhaps as part of an Ajax framework.See also [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Functions:eval] , [http://www.danbbs.dk/~erikoest/js_eval.htm] .
For mathematical functions and constants see [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Math] .
ActionScript
In
ActionScript (Flash's programming language),eval
can not be used to evaluate arbitrary expressions. According to the Flash 8 documentation, its usage is limited to expressions which represent "the name of a variable, property, object, or movie clip to retrieve. This parameter can be either a String or a direct reference to the object instance." [http://livedocs.macromedia.com/flash/8/index.html]Lisp
Lisp was the original language to make use of an
eval
function. In fact, definition of theeval
function led to the first implementation of the language interpreter.Before the
eval
function was defined, Lisp functions were manually compiled toassembly language statements. However, once theeval
function had been manually compiled it was then used as part of a simpleread-eval-print loop which formed the basis of the first Lisp interpreter.Later versions of the Lisp
eval
function have also been implemented as compilers.The
eval
function in Lisp expects a form to be evaluated and executed as argument. The return value of the given form will be the return value of the call toeval
.Now let us see some Lisp code:
Lisp is well known to be very flexible and so is the
eval
function. If for example we would like to evaluate the content of a string, we would first have to convert the string into a Lisp form using theread-from-string
function and then to pass the resulting form toeval
, like this:Perl
In
Perl , theeval
function is something of a hybrid between an expression evaluator and a statement executor. It returns the result of the last expression evaluated (all statements are expressions in Perl), and allows the final semicolon to be left off.Example as an expression evaluator:
Example as a statement executor:
(Beware about the quoting of strings. Note that single quotes were used above to quote the string. If double quotes were used, then it would interpolate the value of the variable into the string before passing it to "
eval
", defeating the purpose of the "eval
", and possibly causing syntax errors, in the case of assignment.)Perl also haseval
"blocks", which serves as itsexception handling mechanism (seeException handling syntax#Perl ). This differs from the above use ofeval
with strings in that code insideeval
blocks is interpreted at compile-time instead of run-time, so it is not the meaning ofeval
used in this article.PHP
In
PHP ,eval
executes code in a string almost exactly as if it had been put in the file instead of the call toeval()
. The only exception is that errors are reported as coming from a call toeval()
, and return statements become the result of the function.Example using echo:
Example returning a value:
PostScript
PostScript 's exec operator takes an operand — if it is a simple literal it pushes it back on the stack. If one takes a string containing a PostScript expression however, one can convert the string to an executable which then can be executed by the interpreter, for example: ((Hello World) =) cvx execconverts the PostScript expression (Hello World) =which pops the string "Hello World" off the stack and displays it on the screen, to have an executable type, then is executed.PostScript's run operator is similar in functionality but instead the interpreter interprets PostScript expressions in a file, itself.
Python
In Python, the eval function in its simplest form evaluates a single expression.
eval example (interactive shell):
The eval function takes two optional arguments, global and locals, which allow the programmer to set up a restricted environment for the evaluation of the expression.
The exec statement executes statements:
exec example (interactive shell):
The most general form for evaluating statements/expressions is using code objects. Those can be created by invoking the compile() function and by telling it what kind of input it has to compile: an "exec" statement, an "eval" statement or a "single" statement:
compile example (interactive shell):
ColdFusion
ColdFusion 's evaluate function lets you evaluate a string expression at runtime.It is particularly useful when you need to programatically choose the variable you want to read from.
REALbasic
In REALbasic, there is a class called
RBScript which can execute REALbasic code at runtime. RBScript is very sandboxed -- only the most core language features are there, you have to allow it access to things you want it to have. You can optionally assign an object to the context property. This allows for the code in RBScript to call functions and use properties of the context object. However, it is still limited to only understanding the most basic types, so if you have a function that returns a Dictionary or MySpiffyObject, RBScript will be unable to use it. You can also communicate with your RBScript through the Print and Input events.Ruby
The Ruby programming language interpreter offers an
eval
function similar to Python or Perl, and also allows a scope, or binding, to be specified.Aside from specifying a function's binding,
eval
may also be used to evaluate an expression within a specific class definition binding or object instance binding, allowing classes to be extended with new methods specified in strings.# evaluating within a contextdef get_binding(a) bindingendeval('a+1',get_binding(3)) # (evaluates to 4, because 'a' in the context of get_binding is 3)
Ruby additionally provides a convenient shorthand for evaluating elements of a string literal. In double-quoted strings literals, any characters enclosed in an
#{}
will be evaluated in the current scope, and the returned valued will be substituted for the#{}
. For example:Will display the message: Hello There!
Forth
Most standard implementations of Forth have two variants of
eval
:EVALUATE
andINTERPRET
.Win32FORTH code example:
S" 2 2 + ." EVALUATE Outputs "4"
VBScript
Microsoft's VBScript, which is an interpreted language, has two constructs.
Eval
is a function evaluator that can include calls to user-defined functions. (These functions may have side-effects such as changing the values of global variables.)Execute
executes one or more colon-separated statements, which can change global state.Both VBScript and JavaScript
eval
are available to developers of compiled Windows applications (written in languages which do not support Eval) through an ActiveX control called the Microsoft Script Control, whose Eval method can be called by application code. To support calling of user-defined functions, one must first initialize the control with the AddCode method, which loads a string (or a string resource) containing a library of user-defined functions defined in the language of one's choice, prior to calling Eval.Visual Basic for Applications
Visual Basic for Applications (VBA), the programming language of Microsoft Office, is a pseudo-compiled language where the runtime environment interprets p-code. Its flavor of Eval supports only expression evaluation, where the expression may include user-defined functions that are side-effect-free. Of note, the evaluator is somewhat buggy, and invokation of certain user-defined functions may not work in VBA, even if the identical code works in VBScript. (Historically, VBA's eval was implemented after VBScript's eval, and appears to use a different code base.)
Command line interpreters
Windows PowerShell
In
Windows PowerShell , theInvoke-Expression
Cmdlet serves the same purpose as the eval function in programming languages like JavaScript, PHP and Python.The Cmdlet runs any Windows PowerShell expression that is provided as a command parameter in the form of a string and outputs the result of the specified expression.Usually, the output of the Cmdlet is of the same type as the result of executing the expression. However, if the result is an empty array, it outputs$null
. In case the result is a single-element array, it outputs that single element. Similar to JavaScript, Windows PowerShell allows the final semicolon to be left off.Example as an expression evaluator: PS> $foo = 2 PS> invoke-expression '$foo + 2'
Example as a statement executor: PS> $foo = 2 PS> invoke-expression '$foo += 2; $foo'
Theory
In
theoretical computer science , a careful distinction is commonly made betweeneval andapply . "Eval" is understood to be the step of converting a quoted string into a callable function and its arguments, whereas "apply" is the actual call of the function with a given set of arguments. The distinction is particularly noticeable infunctional language s, and languages based onlambda calculus , such asLISP and Scheme. Thus, for example, in Scheme, the distinction is betweenwhere the form (f x) is to be evaluated, and
where the function "f" is to be called with argument "x".
"Eval" and "apply" are the two interdependent components of the "eval-apply cycle", which is the essence of evaluating Lisp, described in SICP. [ [http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html The Metacircular Evaluator] (SICP Section 4.1)]
The concept of "apply", together with
currying , plays an important mathematical role in the theory of lambda calculus applied toCartesian closed categories .References
External links
* [http://www.cs.queensu.ca/software_docs/gnudev/gcl-ansi/gcl_256.html ANSI and GNU Common Lisp Document: eval function]
* [http://docs.python.org/lib/built-in-funcs.html#l2h-25 Python Library Reference: eval built-in function]
* [http://www.nilobject.com/?p=138 Jonathan Johnson on exposing classes to RBScript]
Wikimedia Foundation. 2010.