Evaluation operator
   HOME

TheInfoList



OR:

In some
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s, eval , short for the English evaluate, is a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
which evaluates a string as though it were an
expression Expression may refer to: Linguistics * Expression (linguistics), a word, phrase, or sentence * Fixed expression, a form of words with a specific meaning * Idiom, a type of fixed expression * Metaphorical expression, a particular word, phrase, o ...
in the language, and returns a
result A result (also called upshot) is the final consequence of a sequence of actions or events expressed qualitatively or quantitatively. Possible results include advantage, disadvantage, gain, injury, loss, value and victory. There may be a range ...
; 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; it may be structured representation of code, such as an
abstract syntax tree In computer science, an abstract syntax tree (AST), or just syntax tree, is a tree representation of the abstract syntactic structure of text (often source code) written in a formal language. Each node of the tree denotes a construct occurr ...
(like Lisp forms), or of special type such as code (as in Python). The analog for a statement is
exec Exec or EXEC may refer to: * Executive officer, a person responsible for running an organization * Executive producer, provides finance and guidance for the making of a commercial entertainment product * A family of kit helicopters produced by Rot ...
, 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 eval or exec is. Eval and apply are instances of
meta-circular evaluator In computing, a meta-circular evaluator (MCE) or meta-circular interpreter (MCI) is an interpreter which defines each feature of the interpreted language using a similar facility of the interpreter's host language. For example, interpreting a lambd ...
s, interpreters of a language that can be invoked within the language itself.


Security risks

Using eval with data from an untrusted source may introduce security vulnerabilities. For instance, assuming that the get_data() function gets data from the Internet, this
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
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.


Implementation

In
interpreted language In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. An interprete ...
s, eval is almost always implemented with the same interpreter as normal code. In compiled languages, 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 In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a ...
.


Programming languages


ECMAScript


JavaScript

In
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
, eval 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: 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 text, perhaps as part of an
Ajax Ajax may refer to: Greek mythology and tragedy * Ajax the Great, a Greek mythological hero, son of King Telamon and Periboea * Ajax the Lesser, a Greek mythological hero, son of Oileus, the king of Locris * ''Ajax'' (play), by the ancient Gree ...
framework. However, modern browsers provide JSON.parse as a more secure alternative for this task.


ActionScript

In
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning ...
(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." ActionScript 3 does not support eval. The ActionScript 3 Eval Library and the D.eval API were development projects to create equivalents to eval in ActionScript 3. Both have ended, as
Adobe Flash Player Adobe Flash Player (known in Internet Explorer, Firefox, and Google Chrome as Shockwave Flash) is computer software for viewing multimedia contents, executing rich Internet applications, and streaming audio and video content created on the ...
has reached its end-of-life.


Lisp

Lisp was the original language to make use of an eval function in 1958. In fact, definition of the eval function led to the first implementation of the language interpreter.John McCarthy, "History of Lisp - The Implementation of Lisp"
/ref> Before the eval function was defined, Lisp functions were manually compiled to assembly language statements. However, once the eval 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 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 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


Perl

In
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, 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 programming), 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";');
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
also has eval ''blocks'', which serves as its
exception handling In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
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 is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
, 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. Unlike some languages, PHP's eval is a "language construct" rather than a function, and so cannot be used in some contexts where functions can be, like higher-order functions. Example using echo: Example returning a value:


Lua

In
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
5.1, 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') Lua 5.2 deprecates loadstring in favor of the existing load function, which has been augmented to accept strings. In addition, it allows providing the function's environment directly, as environments are now upvalues. print(load("print('Hello ' .. a)", "", "t", )())


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 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. (file.ps) run


Python

In
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, 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 (or the exec function in Python 3.x) executes statements: exec example (interactive shell): >>> x = 1 >>> y = 1 >>> exec "x += 1; y -= 1" >>> x 2 >>> y 0 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() The above example will compile to exactly the same assembly language instructions as if "num++;" 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 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. ownumber)>


Ruby

The
Ruby programming language Ruby is an interpreted, high-level, general-purpose programming language which supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including p ...
interpreter offers an eval function similar to Python or Perl, and also allows a
scope Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinem ...
, 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. 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) 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"


FRED

Framework FRED is an interactive language in which all code is automatically evaluated by Eval. The string parameters in the examples below will run just the same as if typed and executed in a formula or when selected and executed. The Ampersand & is the strings concatenation operator. Eval recursively concatenates, resolves, and evaluates its parameter. FRED also has an internal function named @value that evaluate a parameter string. @value's optional second numeric parameter indicates input type and formats for special types such as dates, time. etc. and determines the returned value format. For security reasons @value reference scope is global relative so local variables created with @local are invisible to @value. They can only be "seen" by code in the same formula area. (see the example below), By the same token local vars created in @value scope can only be seen by @value and are invisible to the code in the same formula or any other code. (see comment (1*) below) FRED code examples: @value("5 + 4 + 1") # Return the numeric value 10 @value("2" & "3") # Return the numeric value 23 @value("2" & " + 3") # Return the numeric value 5 @value("2" & "+" & "3") # Return the numeric value 5 @value("2 + 3") # Return the numeric value 5 my_var := 3, @value("2 + my_var") # Return the numeric value 5 my_var := -3, @value("2 + @abs(my_var)") # Return the numeric value 5 For security reasons this will return an error since @value scope is global and @local is invisible to global references and can only be "seen" by code in its own formula. @local(a,b), a := 1, b := 2, @value("a + b") # return an error value (1*) but if a and b are frames @value which can reference global as well as relative variable frames, @value can "see" them a := 1, b := 2, @value("a + b") # Return the numeric value 3 This line of code will return 3 because the local vars are created and seen in the @value scope @value("@local(a,b),a:=1,b:=2,a+b") # Return the numeric value 3 But the next two lines of code will return an undefined reference error because a and b are created in the local @value scope and are invisible to rest of the code in the formula, in fact to any code anywhere but in this @value scope. @value("@local(a,b),a:=1,b:=2), a+b # Return an undefined reference error @value("",16) # Return the string "Dec 12, 2012" @value("@fileload(@inputline(""Enter drive letter"",""" & @item1 & """) & " & """:\myfile.txt"")") # where @item1 is received parameter "c", will executes the string parts, build the string below, and executes it as a program starting with @inputline requesting user input, suggesting "C", If the user enter C @fileload runs with the string "c:\myfile.txt" as its parameter: @fileload(@inputline("Enter drive letter","c") & ":\myfile.txt") # loads myfile.txt to the desktop


BASIC


REALbasic

In
REALbasic The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
, 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 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.


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 JScript 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 Visual Basic for Applications (VBA) is an implementation of Microsoft's event-driven programming language Visual Basic 6.0 built into most desktop Microsoft Office applications. Although based on pre-.NET Visual Basic, which is no longer support ...
(VBA), the programming language of Microsoft Office, is a virtual machine language where the runtime environment compiles and runs
p-code Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software Interpreter (computing), interpreter. Unlike Human-readable code, human-readable source code, bytecodes are compact nume ...
. 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. 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'


Tcl

The
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited ...
programming language has a command called eval, 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 eval can have the same formatting as any other source code. set foo eval $foo


bs

bs has an eval 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 bs
man page A man page (short for manual page) is a form of software documentation usually found on a Unix or Unix-like operating system. Topics covered include computer programs (including library and system calls), formal standards and conventions, and e ...
as appears in the
UNIX System V Unix System V (pronounced: "System Five") is one of the first commercial versions of the Unix operating system. It was originally developed by AT&T and first released in 1983. Four major versions of System V were released, numbered 1, 2, 3, an ...
Release 3.2 Programmer's Manual.


Command-line interpreters


Unix shells

The ''eval'' command is present in all
Unix shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating syste ...
s, including the original "sh" ( Bourne shell). It concatenates all the arguments with spaces, then re-parses and executes the result as a command.


Windows PowerShell

In
Windows PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-so ...
, 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'


Microcode

In 1966 IBM
Conversational Programming System Conversational Programming System or CPS was an early Time-sharing system offered by IBM which ran on System/360 mainframes ''circa'' 1967 through 1972 in a partition of OS/360 Release 17 MFT II or MVT or above. CPS was implemented as an int ...
(CPS) introduced a microprogrammed function EVAL to perform "interpretive evaluation of expressions which are written in a modified Polish-string notation" on an
IBM System/360 Model 50 The IBM System/360 Model 50 is a member of the IBM System/360 family of computers. The Model 50 was announced in April 1964 with the other initial models of the family, and first shipped in August 1965 to the Bank of America. Models There are f ...
. Microcoding this function was "substantially more" than five times faster compared to a program that interpreted an
assignment Assignment, assign or The Assignment may refer to: * Homework * Sex assignment * The process of sending National Basketball Association players to its development league; see Computing * Assignment (computer science), a type of modification to ...
statement.


Theory

In
theoretical computer science computer science (TCS) is a subset of general computer science and mathematics that focuses on mathematical aspects of computer science such as the theory of computation, lambda calculus, and type theory. It is difficult to circumscribe the ...
, 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 In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
s, and languages based on lambda calculus, such as 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'' (''SICP'') is a computer science textbook by Massachusetts Institute of Technology professors Harold Abelson and Gerald Jay Sussman with Julie Sussman. It is known as the "Wizard Book" in ha ...
.The Metacircular Evaluator
(SICP Section 4.1)
In category theory, the ''eval'' morphism is used to define the
closed monoidal category In mathematics, especially in category theory, a closed monoidal category (or a ''monoidal closed category'') is a category that is both a monoidal category and a closed category in such a way that the structures are compatible. A classic exa ...
. Thus, for example, the
category of sets In the mathematical field of category theory, the category of sets, denoted as Set, is the category whose objects are sets. The arrows or morphisms between sets ''A'' and ''B'' are the total functions from ''A'' to ''B'', and the composition o ...
, with functions taken as morphisms, and the cartesian product taken as the
product Product may refer to: Business * Product (business), an item that serves as a solution to a specific consumer problem. * Product (project management), a deliverable or set of deliverables that contribute to a business solution Mathematics * Produ ...
, forms a
Cartesian closed category In category theory, a category is Cartesian closed if, roughly speaking, any morphism defined on a product of two objects can be naturally identified with a morphism defined on one of the factors. These categories are particularly important in math ...
. Here, ''eval'' (or, properly speaking, '' apply'') together with its
right adjoint In mathematics, specifically category theory, adjunction is a relationship that two functors may exhibit, intuitively corresponding to a weak form of equivalence between two related categories. Two functors that stand in this relationship are kno ...
, currying, form the
simply typed lambda calculus The simply typed lambda calculus (\lambda^\to), a form of type theory, is a typed interpretation of the lambda calculus with only one type constructor (\to) that builds function types. It is the canonical and simplest example of a typed lambda c ...
, which can be interpreted to be the morphisms of Cartesian closed categories.


References

{{Reflist


External links


ANSI and GNU Common Lisp Document: eval functionJonathan Johnson on exposing classes to RBScriptExamples of runtime evaluation in several languages
on Rosetta Code Control flow Unix SUS2008 utilities IBM i Qshell commands