Eval
623831
225663482
2008-07-14T20:10:18Z
Btx40
6819698
/* Uses */
{{lowercase}}
In some [[programming language]]s, <code>eval</code> is a [[subroutine|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 the <code>eval</code>.
<code>eval</code>-like functions are more common in [[interpreted language]]s than in [[compiled 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 <code>eval</code> with data from an untrusted source. For instance, assuming that the <code>get_data()</code> function gets data from the Internet, this [[Python (programming language)|Python]] code is insecure:
<source lang="python">
session['authenticated'] = False
data = get_data()
foo = eval(data)
</source>
An attacker could supply the program with the string <code>"session.update(authenticated=True)"</code> as data, which would update the <code>session</code> dictionary to set an authenticated key to be True. To remedy this, all data which will be used with <code>eval</code> must be escaped, or it must be run without access to potentially harmful functions.
== Uses ==
A call to <code>eval</code> 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, <code>eval</code> is sometimes used for a simple [[mail merge]] facility, as in this [[PHP]] example:
<source lang="php">
$name = 'John Doe';
$greeting = 'Hello';
$template = '"$greeting, $name! How can I help you today?"';
print eval("return $template;");
</source>
<!-- Is eval needed here? All it does is return the value of $template (and execute any code in it). -->
Although this works, it can cause some security problems (see security risks), and will be much slower than other possible solutions. A faster and more secure solution would be simply changing the last line to <code>print $template;</code>.
<code>eval</code> is also sometimes used in applications needing to evaluate math expressions, such as [[spreadsheet]]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 <code>eval</code> is in [[Bootstrapping (compilers)|bootstrapping]] a new language (as with [[Lisp programming language|Lisp]]), and in language tutor programs which allow users to run their own programs in a controlled environment.
== Implementation ==
In [[interpreted language]]s, <code>eval</code> is almost always implemented with the same interpreter as normal code. In [[compiled language]]s, the same compiler used to compile programs may be embedded in programs using the <code>eval</code> function; separate interpreters are sometimes used, though this results in [[code duplication]].
== Programming languages ==
=== JavaScript ===
In [[JavaScript]], <code>eval</code> 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:
<source lang="javascript">
foo = 2;
alert(eval('foo + 2'));
</source>
Example as a statement executor:
<source lang="javascript">
foo = 2;
eval('foo = foo + 2;alert(foo);');
</source>
One use of Javascript's <code>eval</code> is to parse [[JSON]] text, perhaps as part of an [[Ajax (programming)|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), <code>eval</code> 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 programming language|Lisp]] was the original language to make use of an <code>eval</code> function. In fact, definition of the <code>eval</code> function led to the first implementation of the language interpreter.
Before the <code>eval</code> function was defined, Lisp functions were manually compiled to [[assembly language]] statements. However, once the <code>eval</code> function had been manually compiled it was then used as part of a simple [[read-eval-print loop]] which formed the basis of the first Lisp interpreter.
Later versions of the Lisp <code>eval</code> function have also been implemented as compilers.
The <code>eval</code> 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 to <code>eval</code>.
Now let us see some Lisp code:
<source lang="lisp">
; A form which calls the + function with 1,2 and 3 as arguments.
; It returns 6.
(+ 1 2 3)
; In lisp any form is meant to be evaluated, therefore
; the call to + was performed.
; We can prevent Lisp from performing evaluation
; of a form by prefixing it with "'", for example:
(setq form1 '(+ 1 2 3))
; Now form1 contains a form that can be used by eval, for
; example:
(eval form1)
; eval evaluated (+ 1 2 3) and returned 6.
</source>
Lisp is well known to be very flexible and so is the <code>eval</code> 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 the <code>read-from-string</code> function and then to pass the resulting form to <code>eval</code>, like this:
<source lang="lisp">(eval (read-from-string "(format t \"Hello World!!!~%\")"))</source>
=== Perl ===
In [[Perl]], the <code>eval</code> 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:
<source lang="perl">
$foo = 2;
print eval('$foo + 2'), "\n";
</source>
Example as a statement executor:
<source lang="perl">
$foo = 2;
eval('$foo += 2; print "$foo\n";');
</source>
(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 [[variable#Variable interpolation|interpolate]] the value of the variable into the string before passing it to "<code>eval</code>", defeating the purpose of the "<code>eval</code>", and possibly causing syntax errors, in the case of assignment.)
[[Perl]] also has <code>eval</code> ''blocks'', which serves as its [[exception handling]] mechanism (see [[Exception handling syntax#Perl]]). This differs from the above use of <code>eval</code> with strings in that code inside <code>eval</code> blocks is interpreted at compile-time instead of run-time, so it is not the meaning of <code>eval</code> used in this article.
=== PHP ===
In [[PHP]], <code>eval</code> executes code in a string almost exactly as if it had been put in the file instead of the call to <code>eval()</code>. The only exception is that errors are reported as coming from a call to <code>eval()</code>, and return statements become the result of the function.
Example using echo:
<source lang="php">
<?php
$foo = "Hello, world!\n";
eval('echo $foo;');
?>
</source>
Example returning a value:
<source lang="php">
<?php
$foo = "Goodbye, world!\n"; //does not work in PHP5
echo eval('return $foo;');
?>
</source>
=== PostScript ===
[[PostScript]]'s <tt>exec</tt> 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 exec
converts 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 <tt>run</tt> operator is similar in functionality but instead the interpreter interprets PostScript expressions in a file, itself.
=== Python ===
In [[Python (language)|Python]], the <tt>eval</tt> function in its simplest form evaluates a single expression.
<tt>eval</tt> example (interactive shell):
<source lang="python">
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
</source>
The <tt>eval</tt> function takes two optional arguments, <tt>global</tt> and <tt>locals</tt>, which allow the programmer to set up a restricted environment for the evaluation of the expression.
The <tt>exec</tt> statement executes statements:
<tt>exec</tt> example (interactive shell):
<source lang="python">
>>> x = 1
>>> y = 1
>>> exec "x += 1; y -= 1"
>>> x
2
>>> y
0
</source>
The most general form for evaluating statements/expressions is using code objects. Those can be created by invoking the <tt>compile()</tt> function and by telling it what kind of input it has to compile: an "<tt>exec</tt>" statement, an "<tt>eval</tt>" statement or a "<tt>single</tt>" statement:
<tt>compile</tt> example (interactive shell):
<source lang="python">
>>> x = 1
>>> y = 2
>>> eval (compile ("print 'x + y = ', x + y", "compile-sample.py", "single"))
x + y = 3
</source>
=== ColdFusion ===
[[ColdFusion]]'s <tt>evaluate</tt> function lets you evaluate a string expression at runtime.
<source lang="cfm">
<cfset x = "int(1+1)">
<cfset y = Evaluate(x)>
</source>
It is particularly useful when you need to programatically choose the variable you want to read from.
<source lang="cfm"><cfset x = Evaluate("queryname.#columnname#[rownumber]")></source>
=== REALbasic ===
In [[REALbasic programming language|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)|Ruby programming language]] interpreter offers an <code>eval</code> function similar to Python or Perl, and also allows a [[Scope (programming)|scope]], or [[Name binding|binding]], to be specified.
Aside from specifying a function's binding, <code>eval</code> 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.
<source lang="ruby">
a = 1
eval('a + 1') # (evaluates to 2)
# evaluating within a context
def get_binding(a)
binding
end
eval('a+1',get_binding(3)) # (evaluates to 4, because 'a' in the context of get_binding is 3)
</source>
<source lang="ruby">
class Test; end
Test.class_eval("def hello; return 'hello';end") # add a method 'hello' to this class
Test.new.hello # evaluates to "hello"
</source>
Ruby additionally provides a convenient shorthand for evaluating elements of a string literal. In double-quoted strings literals, any characters enclosed in an <code>#{}</code> will be evaluated in the current scope, and the returned valued will be substituted for the <code>#{}</code>. For example:
<source lang="ruby">
"#{class NewClass; def test; "Hello"; end; end}"
a = NewClass.new
print "#{a.test} There!"
</source>
Will display the message: Hello There!
=== Forth ===
Most standard implementations of [[Forth (programming language)|Forth]] have two variants of <code>eval</code>: <code>EVALUATE</code> and <code>INTERPRET</code>.
Win32FORTH code example:
S" 2 2 + ." EVALUATE \ Outputs "4"
== Command line interpreters ==
=== Windows PowerShell ===
In [[Windows PowerShell]], the <code>Invoke-Expression</code> 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 <code>$null</code>. 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 between [[eval]] and [[apply]]. ''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 in [[functional language]]s, and languages based on [[lambda calculus]], such as [[LISP]] and [[scheme (programming language)|Scheme]]. Thus, for example, in Scheme, the distinction is between
<source lang="lisp">(eval '(f x) )</source>
where the form (f x) is to be evaluated, and
<source lang="lisp">(apply f (list x))</source>
where the function ''f'' is to be called with argument ''x''.
The concept of ''apply'', together with [[currying]], plays an important mathematical role in the theory of lambda calculus applied to [[Cartesian closed categories]].
==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]
[[Category:Control flow]]
[[es:Eval]]
[[fr:Eval]]
[[ja:Eval]]