Eval
Encyclopedia
In some programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s, eval is a function
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

 which evaluates 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 eval. The input to eval is not necessarily a string; in languages that support syntactic abstractions (like Lisp), eval's input will consist of abstract syntactic forms.

Security risks

Special care must be taken when using eval with data from an untrusted source. For instance, assuming that the get_data function gets data from the Internet, this Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 code is insecure:

session['authenticated'] = False
data = get_data
foo = eval(data)


An attacker could supply the program with the string "session.update(authenticated=True)" as data, which would update the session dictionary to set an authenticated key to be True. To remedy this, all data which will be used with eval 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 simple mail merge
Mail merge
Mail merge is a software function which allows to create multiple documents from a single template form and a structured data source.-History:This technique of merging data to create gave rise to the term mail merge....

 facility, as in this PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 example:

$name = 'John Doe';
$greeting = 'Hello';
$template = '"$greeting, $name! How can I help you today?"';
print eval("return $template;");


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 changing the last line to print $template; and removing the single quotes from the previous line, or using printf.

eval is also sometimes used in applications needing to evaluate math expressions, such as spreadsheet
Spreadsheet
A spreadsheet is a computer application that simulates a paper accounting worksheet. It displays multiple cells usually in a two-dimensional matrix or grid consisting of rows and columns. Each cell contains alphanumeric text, numeric values or formulas...

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
Bootstrapping (compilers)
In computer science, bootstrapping is the process of writing a compiler in the target programming language which it is intended to compile...

 a new language (as with Lisp
Lisp programming language
Lisp is a family of computer programming languages with a long history and a distinctive, fully parenthesized syntax. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older...

), 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
Interpreted language
Interpreted language is a programming language in which programs are 'indirectly' executed by an interpreter program. This can be contrasted with a compiled language which is converted into machine code and then 'directly' executed by the host CPU...

s, eval is almost always implemented with the same interpreter as normal code. In compiled language
Compiled language
A compiled language is a programming language whose implementations are typically compilers , and not interpreters ....

s, the same compiler used to compile programs may be embedded in programs using the eval function; separate interpreters are sometimes used, though this results in code duplication.

JavaScript

In JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, 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 Javascript), and allows the final semicolon to be left off.

Example as an expression evaluator:

foo = 2;
alert(eval('foo + 2'));


Example as a statement executor:

foo = 2;
eval('foo = foo + 2;alert(foo);');


One use of JavaScript's eval is to parse JSON
JSON
JSON , or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects...

 text, perhaps as part of an Ajax
Ajax (programming)
Ajax is a group of interrelated web development methods used on the client-side to create asynchronous web applications...

 framework. However, modern browsers provide JSON.parse as a more secure alternative for this task.

ActionScript

In ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

 (Flash's programming language), eval cannot 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

ActionScript 3 does not support eval.

The ActionScript 3 Eval Library and the D.eval API are ongoing development projects to create equivalents to eval in ActionScript 3.

Lisp

Lisp
Lisp programming language
Lisp is a family of computer programming languages with a long history and a distinctive, fully parenthesized syntax. Originally specified in 1958, Lisp is the second-oldest high-level programming language in widespread use today; only Fortran is older...

 was the original language to make use of an eval function. In fact, definition of the eval function led to the first implementation of the language interpreter.
Before the eval function was defined, Lisp functions were manually compiled to assembly language
Assembly language
An assembly language is a low-level programming language for computers, microprocessors, microcontrollers, and other programmable devices. It implements a symbolic representation of the machine codes and other constants needed to program a given CPU architecture...

 statements. However, once the eval function had been manually compiled it was then used as part of a simple read-eval-print loop
Read-eval-print loop
A read–eval–print loop , also known as an interactive toplevel, is a simple, interactive computer programming environment. The term is most usually used to refer to a Lisp interactive environment, but can be applied to command line shells and similar environments for F#, Smalltalk, Standard ML,...

 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 to eval.

This is an example Lisp code:


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.


Lisp is well known to be very flexible and so is the eval function. For example, to evaluate the content of a string, the string would first have to be converted into a Lisp form using the read-from-string function and then the resulting form would have to be passed to eval:

(eval (read-from-string "(format t \"Hello World!!!~%\")"))

One major point of confusion is the question, in which context the symbols in the form will be evaluated. In the above example, form1 contains the symbol +. Evaluation of this symbol must yield the function for addition to make the example work as intended. Thus some dialects of lisp allow an additional parameter for eval to specify the context of evaluation (similar to the optional arguments to Python's eval function - see below). An example in the Scheme dialect of Lisp (R5RS and later):

Define some simple form as in the above example

(define form2 '(+ 5 2))
Value: form2
Evaluate the form within the initial context
A context for evaluation is called an "environment" in Scheme slang

(eval form2 user-initial-environment)
Value: 7
Confuse the initial environment, so that + will b
a name for the subtraction function

(environment-define user-initial-environment '+ -)
Value: +
Evaluate the form again
Notice that the returned value has changed

(eval form2 user-initial-environment)
Value: 3

Perl

In Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, the eval 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:

$foo = 2;
print eval('$foo + 2'), "\n";


Example as a statement executor:

$foo = 2;
eval('$foo += 2; print "$foo\n";');


(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
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 also has eval blocks, which serves as its exception handling
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

 mechanism (see Exception handling syntax#Perl). This differs from the above use of eval with strings in that code inside eval blocks is interpreted at compile-time instead of run-time, so it is not the meaning of eval used in this article.

PHP

In PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

, eval executes code in a string almost exactly as if it had been put in the file instead of the call to eval. The only exception is that errors are reported as coming from a call to eval, and return statements become the result of the function.

Unlike some languages, the argument to eval must be a string of one or more complete statements, not just expressions; however, one can get the "expression" form of eval by putting the expression in a return statement, which causes eval to return the result of that expression.

Example using echo:

$foo = "Hello, world!\n";
eval('echo "$foo";');
?>


Example returning a value:

$foo = "Goodbye, world!\n"; //does not work in PHP5
echo eval('return $foo;');
?>

Lua

In Lua
Lua
Lua may refer to:* Lua , a Roman goddess* Lua , a traditional Hawaiian martial art* Lua , a lightweight, extensible programming language* Lua , a single by the folk rock band Bright Eyes...

, loadstring compiles lua code into an anonymous function.

Example as an expression evaluator:

loadstring("print('Hello World!')")


Example to do the evaluation in two steps:

a = 1
f = loadstring("return a + 1") -- compile the expression to an anonymous function
print(f) -- execute (and print the result '2')

PostScript

PostScript
PostScript
PostScript is a dynamically typed concatenative programming language created by John Warnock and Charles Geschke in 1982. It is best known for its use as a page description language in the electronic and desktop publishing areas. Adobe PostScript 3 is also the worldwide printing and imaging...

'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 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 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):

>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1


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):

>>> x = 1
>>> y = 1
>>> exec "x += 1; y -= 1"
>>> x
2
>>> y
0

Note that in Python 3.x the exec statement became the exec function.

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):

>>> x = 1
>>> y = 2
>>> eval (compile ("print 'x + y = ', x + y", "compile-sample.py", "single"))
x + y = 3

D

D is a statically compiled language and therefore does not include an "eval" statement in the traditional sense, but does include the related "mixin" statement. The difference is that, where "eval" interprets a string as code at runtime, with a "mixin" the string is statically compiled like ordinary code and must be known at compile time. For example:


import std.stdio;

void main {
int num = 0;
mixin("num++;");
writeln(num); // Prints 1.
}


The above example will compile to exactly the same assembly language instructions as if "num++;" had been written directly instead of mixed in.

ColdFusion

ColdFusion
ColdFusion
In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...

'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
RBScript
RBScript is a scripting language which is similar to, and shares many features with, REALbasic. They are both object oriented, support modules and use almost identical datatypes...

 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)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

 interpreter offers an eval function similar to Python or Perl, and also allows a scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

, or binding
Name binding
In programming languages, name binding is the association of objects with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-object bindings as a service and notation for the programmer is implemented...

, 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.


a = 1
eval('a + 1') # (evaluates to 2)
  1. 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)



class Test; end
Test.class_eval("def hello; return 'hello';end") # add a method 'hello' to this class
Test.new.hello # evaluates to "hello"

Forth

Most standard implementations of Forth have two variants of eval: EVALUATE and INTERPRET.

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 virtual machine language where the runtime environment compiles and runs p-code. Its flavor of Eval supports only expression evaluation, where the expression may include user-defined functions and objects (but not user-defined variable names). Of note, the evaluator is different from VBS, and invocation of certain user-defined functions may work differently in VBA than the identical code in VBScript.

Smalltalk

As Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

's compiler classes are part of the standard class library and usually present at run time, these can be used to evaluate a code string.

Compiler evaluate:'1 + 2'

Because class and method definitions are also implemented by message-sends (to class objects), even code changes are possible:

Compiler evaluate:'Object subclass:#Foo'


Unix shells

The eval command is present in all Unix shell
Unix shell
A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems...

s, including the original "sh" (Bourne shell
Bourne shell
The Bourne shell, or sh, was the default Unix shell of Unix Version 7 and most Unix-like systems continue to have /bin/sh - which will be the Bourne shell, or a symbolic link or hard link to a compatible shell - even when more modern shells are used by most users.Developed by Stephen Bourne at AT&T...

). It concatenates all the arguments with spaces, then re-parses and executes the result as a command.

Windows PowerShell

In Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

, the Invoke-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
Theoretical computer science
Theoretical computer science is a division or subset of general computer science and mathematics which focuses on more abstract or mathematical aspects of computing....

, a careful distinction is commonly made between eval and apply
Apply
In mathematics and computer science, Apply is a function that applies functions to arguments. It is central to programming languages derived from lambda calculus, such as LISP and Scheme, and also in functional languages...

. 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 languages, and languages based on lambda calculus
Lambda calculus
In mathematical logic and computer science, lambda calculus, also written as λ-calculus, is a formal system for function definition, function application and recursion. The portion of lambda calculus relevant to computation is now called the untyped lambda calculus...

, such as LISP
Lisp
A lisp is a speech impediment, historically also known as sigmatism. Stereotypically, people with a lisp are unable to pronounce sibilants , and replace them with interdentals , though there are actually several kinds of lisp...

 and Scheme. Thus, for example, in Scheme, the distinction is between

(eval '(f x) )

where the form (f x) is to be evaluated, and

(apply f (list x))

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
Structure and Interpretation of Computer Programs
Structure and Interpretation of Computer Programs is a textbook published in 1984 about general computer programming concepts from MIT Press written by Massachusetts Institute of Technology professors Harold Abelson and Gerald Jay Sussman, with Julie Sussman...

.

The concept of apply, together with currying
Currying
In mathematics and computer science, currying is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument...

, plays an important mathematical role in the theory of lambda calculus applied to Cartesian closed categories.

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK