Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Eval
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{short description|Function in a programming language, which evaluates a string}} {{redirects|Evaluation (computer science)|other uses|Evaluation (disambiguation)}} {{lowercase}} {{Use mdy dates|date=April 2025}} {{Use American English|date=April 2025}} In some [[programming language]]s, '''<code>eval</code>''' , short for [[wiktionary:evaluate|evaluate]], is a [[subroutine|function]] which evaluates a string as though it were an [[expression (programming)|expression]] in the language, and returns a [[return value|result]]; in others, it executes multiple lines of code as though they had been included instead of the line including the <code>eval</code>. The input to <code>eval</code> is not necessarily a string; it may be structured representation of code, such as an [[abstract syntax tree]] (like [[Lisp (programming language)|Lisp]] forms), or of special type such as <code>code</code> (as in Python). The analog for a [[Statement (computer science)|statement]] is [[Exec (system call)|exec]], which executes a string (or code in other format) as if it were a statement; in some languages, such as Python, both are present, while in other languages only one of either <code>eval</code> or <code>exec</code> is. == Security risks == Using <code>eval</code> with data from an untrusted source may introduce security vulnerabilities. For instance, assuming that the <code>get_data()</code> function gets data from the Internet, this [[Python (programming language)|Python]] code is insecure: <syntaxhighlight lang="python"> session['authenticated'] = False data = get_data() foo = eval(data) </syntaxhighlight> An attacker [[Code injection|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. == 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 == === ECMAScript === ==== 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. Example as an expression evaluator: <syntaxhighlight lang="javascript"> foo = 2; alert(eval('foo + 2')); </syntaxhighlight> Example as a statement executor: <syntaxhighlight lang="javascript"> foo = 2; eval('foo = foo + 2;alert(foo);'); </syntaxhighlight> One use of JavaScript's <code>eval</code> is to parse [[JSON]] text, perhaps as part of an [[Ajax (programming)|Ajax]] framework. However, modern browsers provide <code>JSON.parse</code> as a more secure alternative for this task. ==== ActionScript ==== In [[ActionScript]] (Flash's programming language), <code>eval</code> 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."<ref>{{cite web |url = http://livedocs.macromedia.com/flash/8/index.html |archive-url = https://web.archive.org/web/20061010123451/http://livedocs.macromedia.com/flash/8/index.html |url-status = dead |archive-date = October 10, 2006 |title = Flash 8 LiveDocs |date = October 10, 2006}}</ref> ActionScript 3 does not support eval. The ActionScript 3 Eval Library<ref>[http://eval.hurlant.com ActionScript 3 Eval Library]</ref> and the D.eval API<ref>{{cite web |url=http://www.riaone.com/products/deval/ |title=The D.eval API |archive-url=https://web.archive.org/web/20130314012753/http://www.riaone.com/products/deval/ |archive-date=March 14, 2013 |url-status=dead}}</ref> were development projects to create equivalents to <code>eval</code> in ActionScript 3. Both have ended, as [[Adobe Flash Player]] has reached its [[End-of-life_product|end-of-life]]. === Lisp === [[Lisp programming language|Lisp]] was the original language to make use of an <code>eval</code> function in 1958. In fact, definition of the <code>eval</code> function led to the first implementation of the language interpreter.<ref name="mccarthy">[https://www-formal.stanford.edu/jmc/history/lisp/node3.html John McCarthy, "History of Lisp - The Implementation of Lisp"]</ref> 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 as its argument. The resulting value of the given form will be the returned value of the call to <code>eval</code>. This is an example Lisp code: <syntaxhighlight 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. </syntaxhighlight> Lisp is well known to be very flexible and so is the <code>eval</code> function. For example, to evaluate the content of a string, the string would first have to be converted into a Lisp form using the <code>read-from-string</code> function and then the resulting form would have to be passed to <code>eval</code>: <syntaxhighlight lang="lisp">(eval (read-from-string "(format t \"Hello World!!!~%\")"))</syntaxhighlight> One major point of confusion is the question, in which context the symbols in the form will be evaluated. In the above example, <code>form1</code> contains the symbol <code>+</code>. 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 <code>eval</code> to specify the context of evaluation (similar to the optional arguments to Python's <code>eval</code> function - see below). An example in the [[Scheme (programming language)|Scheme]] dialect of Lisp (R<sup>5</sup>RS and later): <syntaxhighlight lang="scheme"> ;; 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 be ;; 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 </syntaxhighlight> === 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 programming), and allows the final semicolon to be left off. Example as an expression evaluator: <syntaxhighlight lang="perl"> $foo = 2; print eval('$foo + 2'), "\n"; </syntaxhighlight> Example as a statement executor: <syntaxhighlight lang="perl"> $foo = 2; eval('$foo += 2; print "$foo\n";'); </syntaxhighlight> [[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. Unlike some languages, the argument to <code>eval</code> must be a string of one or more complete statements, not just expressions; however, one can get the "expression" form of <code>eval</code> by putting the expression in a return statement, which causes <code>eval</code> to return the result of that expression. Unlike some languages, PHP's <code>eval</code> is a "language construct" rather than a function,<ref>{{cite web|url=https://php.net/eval|website=[[PHP]].net|access-date=September 10, 2015|title=PHP: eval - Manual}}</ref> and so cannot be used in some contexts where functions can be, like higher-order functions. Example using echo: <syntaxhighlight lang="php"> <?php $foo = "Hello, world!\n"; eval('echo "$foo";'); ?> </syntaxhighlight> Example returning a value: <syntaxhighlight lang="php"> <?php $foo = "Goodbye, world!\n"; //does not work in PHP5 echo eval('return $foo;'); ?> </syntaxhighlight> ===Lua=== In [[Lua (programming language)|Lua]] 5.1, <code>loadstring</code> compiles Lua code into an anonymous function. Example as an expression evaluator: <syntaxhighlight lang="lua"> loadstring("print('Hello World!')")() </syntaxhighlight> Example to do the evaluation in two steps: <syntaxhighlight lang="lua"> a = 1 f = loadstring("return a + 1") -- compile the expression to an anonymous function print(f()) -- execute (and print the result '2') </syntaxhighlight> Lua 5.2 deprecates <code>loadstring</code> in favor of the existing <code>load</code> function, which has been augmented to accept strings. In addition, it allows providing the function's environment directly, as environments are now [[closure (computer science)|upvalues]]. <syntaxhighlight lang="lua"> load("print('Hello ' .. a)", "", "t", { a = "World!", print = print })() </syntaxhighlight> === PostScript === [[PostScript]]'s <code>exec</code> 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: <syntaxhighlight lang="postscript"> ((Hello World) =) cvx exec </syntaxhighlight> converts the PostScript expression <syntaxhighlight lang="postscript"> (Hello World) = </syntaxhighlight> 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 <code>run</code> operator is similar in functionality but instead the interpreter interprets PostScript expressions in a file, itself. <syntaxhighlight lang="postscript"> (file.ps) run </syntaxhighlight> === Python === In [[Python (language)|Python]], the <code>eval</code> function in its simplest form evaluates a single expression. <code>eval</code> example (interactive shell): <syntaxhighlight lang="pycon"> >>> x = 1 >>> eval('x + 1') 2 >>> eval('x') 1 </syntaxhighlight> The <code>eval</code> function takes two optional arguments, <code>global</code> and <code>locals</code>, which allow the programmer to set up a restricted environment for the evaluation of the expression. The <code>exec</code> statement (or the <code>exec</code> function in Python 3.x) executes statements: <code>exec</code> example (interactive shell): <syntaxhighlight lang="pycon"> >>> x = 1 >>> y = 1 >>> exec "x += 1; y -= 1" >>> x 2 >>> y 0 </syntaxhighlight> The most general form for evaluating statements/expressions is using code objects. Those can be created by invoking the <code>compile()</code> function and by telling it what kind of input it has to compile: an "<code>exec</code>" statement, an "<code>eval</code>" statement or a "<code>single</code>" statement: <code>compile</code> example (interactive shell): <syntaxhighlight lang="pycon"> >>> x = 1 >>> y = 2 >>> eval (compile ("print 'x + y = ', x + y", "compile-sample.py", "single")) x + y = 3 </syntaxhighlight> === D === [[D programming|D]] is a statically compiled language and therefore does not include an "<code>eval</code>" statement in the traditional sense, but does include the related "<code>mixin</code>" statement. The difference is that, where "<code>eval</code>" interprets a string as code at runtime, with a "<code>mixin</code>" the string is statically compiled like ordinary code and must be known at compile time. For example: <syntaxhighlight lang="D"> import std.stdio; void main() { int num = 0; mixin("num++;"); writeln(num); // Prints 1. } </syntaxhighlight> The above example will compile to exactly the same assembly language instructions as if "<code>num++;</code>" had been written directly instead of mixed in. The argument to mixin doesn't need to be a string literal, but arbitrary expressions resulting in a string value, including function calls, that can be evaluated at compile time. === ColdFusion === [[ColdFusion]]'s <code>evaluate</code> function lets users evaluate a string expression at runtime. <syntaxhighlight lang="cfm"> <cfset x = "int(1+1)"> <cfset y = Evaluate(x)> </syntaxhighlight> It is particularly useful when users need to programmatically choose the variable they want to read from. <syntaxhighlight lang="cfm"><cfset x = Evaluate("queryname.#columnname#[rownumber]")></syntaxhighlight> === 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. <syntaxhighlight 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) </syntaxhighlight> <syntaxhighlight 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" </syntaxhighlight> === 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: <syntaxhighlight lang="forth"> S" 2 2 + ." EVALUATE \ Outputs "4" </syntaxhighlight> === BASIC === ==== 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, and users have to allow it access to things they would like it to have. They 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 they have a function that returns a Dictionary or MySpiffyObject, RBScript will be unable to use it. Users can also communicate with their RBScript through the Print and Input events. ==== VBScript ==== Microsoft's VBScript, which is an interpreted language, has two constructs. <code>Eval</code> 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.) <code>Execute</code> executes one or more colon-separated statements, which can change global state. Both VBScript and JScript <code>eval</code> 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 [[Byte code|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]]'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. <syntaxhighlight lang="smalltalk"> Compiler evaluate:'1 + 2' </syntaxhighlight> Because class and method definitions are also implemented by message-sends (to class objects), even code changes are possible: <syntaxhighlight lang="smalltalk"> Compiler evaluate:'Object subclass:#Foo' </syntaxhighlight> === Tcl === The [[Tcl]] programming language has a command called <code>eval</code>, which executes the source code provided as an argument. Tcl represents all source code as strings, with curly braces acting as quotation marks, so that the argument to <code>eval</code> can have the same formatting as any other source code. <syntaxhighlight lang="Tcl"> set foo { while {[incr i]<10} { puts "$i squared is [expr $i*$i]" } } eval $foo </syntaxhighlight> === bs === [[bs (programming language)|bs]] has an <code>eval</code> function that takes one string argument. The function is both an expression evaluator and a statement executor. In the latter role, it can also be used for error handling. The following examples and text are from the <code>bs</code> [[man page]] as appears in the [[UNIX System V]] Release 3.2 Programmer's Manual.<ref name=SVR32>{{cite book |title = UNIX Programmer's Manual |section = Volume 1 Commands and Utilities |year = 1986 |publisher = AT&T |page = 41 |url=https://bitsavers.trailing-edge.com/pdf/att/unix/System_V_Release_2/UNIX_Programmers_Manual_Vol_1_Commands_and_Utilities_1986.pdf}} </ref> {{Quote |text=The string argument is evaluated as a <code>bs</code> expression. The function is handy for converting numeric strings to numeric internal form. The <code>eval</code> can also be used as a crude form of indirection, as in the following (Note that, in <code>bs</code>, <code>_</code> (underscore) is the concatenation operator.): <syntaxhighlight lang="bash"> name = "xyz" eval("++" _ name) </syntaxhighlight> which increments the variable <code>xyz</code>. In addition, <code>eval</code> preceded by the interrogation operator, <code>?</code>, permits the user to control <code>bs</code> error conditions. For example: <syntaxhighlight lang="bash"> ?eval("open(\"X\", \"XXX\", \"r\")") </syntaxhighlight> returns the value zero if there is no file named "XXX" (instead of halting the user's program). The following executes a <code>goto</code> to the label <code>L</code> (if it exists): <syntaxhighlight lang="bash"> label = "L" if !(?eval("goto " _ label)) puterr = "no label" </syntaxhighlight> }} == Command-line interpreters == === Unix shells === The ''eval'' command is present in all [[Unix shell]]s, including the original "sh" ([[Bourne shell]]). It concatenates all the arguments with spaces, then re-parses and executes the result as a command. {{man|1|sh|FreeBSD}} === PowerShell === In [[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 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, PowerShell allows the final semicolon to be left off. Example as an expression evaluator: <syntaxhighlight lang="ps1con"> PS > $foo = 2 PS > Invoke-Expression '$foo + 2' </syntaxhighlight> Example as a statement executor: <syntaxhighlight lang="ps1con"> PS > $foo = 2 PS > Invoke-Expression '$foo += 2; $foo' </syntaxhighlight> ==Microcode== In 1966 [[IBM]] [[Conversational Programming System]] (CPS) introduced a [[Microcode|microprogrammed]] function <code>EVAL</code> to perform "interpretive evaluation of expressions which are written in a modified [[Polish notation|Polish-string notation]]" on an [[IBM System/360 Model 50]].<ref>{{cite web|last1=Allen-Babcock|title=Draft EVAL Microprogram|url=https://bitsavers.trailing-edge.com/pdf/allen-babcock/cps/Draft_Eval_Microprogram_Mar66.pdf|website=Bitsavers.org|access-date=January 17, 2016}}</ref> Microcoding this function was "substantially more" than five times faster compared to a program that interpreted an [[Assignment (computer science)|assignment]] statement.<ref>{{cite web|last1=Rochester|first1=Nathaniel|title=Conversational Programming System Progress Report|url=https://bitsavers.trailing-edge.com/pdf/allen-babcock/cps/CPS_Progress_Report_may66.pdf|website=Bitsavers.org|access-date=January 17, 2016}}</ref> ==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 <syntaxhighlight lang="lisp">(eval '(f x) )</syntaxhighlight> where the form (f x) is to be evaluated, and <syntaxhighlight lang="lisp">(apply f (list x))</syntaxhighlight> 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 [[Structure and Interpretation of Computer Programs|SICP]].<ref>[http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html The Metacircular Evaluator] (SICP Section 4.1)</ref> In [[category theory]], the ''eval'' [[morphism]] is used to define the [[closed monoidal category]]. Thus, for example, the [[category of sets]], with functions taken as morphisms, and the [[cartesian product]] taken as the [[product (category theory)|product]], forms a [[Cartesian closed category]]. Here, ''eval'' (or, properly speaking, ''[[apply]]'') together with its [[right adjoint]], [[currying]], form the [[simply typed lambda calculus]], which can be interpreted to be the morphisms of Cartesian closed categories. ==See also== * [[Data as code]] ==References== {{Reflist}} ==External links== *[https://web.archive.org/web/20030322002401/http://www.cs.queensu.ca/software_docs/gnudev/gcl-ansi/gcl_256.html ANSI and GNU Common Lisp Document: eval function] *[https://web.archive.org/web/20080930143344/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] *[https://rosettacode.org/wiki/Runtime_evaluation Examples of runtime evaluation in several languages] on [[Rosetta Code]] [[Category:Control flow]] [[Category:Unix SUS2008 utilities]] [[Category:IBM i Qshell commands]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Lowercase
(
edit
)
Template:Man
(
edit
)
Template:Quote
(
edit
)
Template:Redirects
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Use American English
(
edit
)
Template:Use mdy dates
(
edit
)