Runtime evaluation: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(27 intermediate revisions by 19 users not shown)
Line 10:
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
<br><br>
=={{header|6502 Assembly}}==
The 6502 can execute code at runtime through the use of self-modifying code, provided that the code runs in RAM. For programs that are defined in ROM, the code can be copied to RAM and executed from RAM. If you have a way to type numeric values into your program and save them in a contiguous section of memory, and those values are stored as numbers and not ASCII, a <code>JMP</code> to their storage location can be used to execute arbitrary code.
 
This example runs on the Commodore 64 and prints the letter A using a crude "eval":
<syntaxhighlight lang="6502asm">;Init Routine
*=$0801
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00
*=$0810 ;Start at $0810
 
LDA #$A9 ;opcode for LDA immediate
STA smc_test
LDA #'A'
STA smc_test+1
lda #$20 ;opcode for JSR
STA smc_test+2
lda #<CHROUT
STA smc_test+3
lda #>CHROUT
STA smc_test+4
smc_test:
nop ;gets overwritten with LDA
nop ;gets overwritten with #$41
nop ;gets overwritten with JSR
nop ;gets overwritten with <CHROUT
nop ;gets overwritten with >CHROUT
 
rts ;return to basic</syntaxhighlight>
 
{{out}}
<pre>
LOAD"*",8,1
 
SEARCHING FOR *
LOADING
READY.
RUN
A
READY.
</pre>
 
=={{header|ALGOL 68}}==
Line 18 ⟶ 65:
<!-- {{does not work with|ELLA ALGOL 68|Any This implementation is a compiler}} -->
Variable names are generally not visible at run time with classic compilers. However '''ALGOL 68G''' is an interpretor and it retains this ability.
<langsyntaxhighlight lang="algol68">print(evaluate("4.0*arctan(1.0)"))</langsyntaxhighlight>
{{out}}
<pre>
Line 27 ⟶ 74:
 
{{works with|ALGOL 68G|tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># procedure to call the Algol 68G evaluate procedure #
# the environment of the evaluation will be the caller's environment #
# with "code", "x" and "y" defined as the procedure parameters #
Line 61 ⟶ 108:
# if this next call was executed, a runtime error would occur as x and y #
# do not exist anymore #
# ;print( ( evaluate( "x + y" ), newline ) ) #</langsyntaxhighlight>
 
{{out}}
Line 71 ⟶ 118:
code + codecode + code
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">a: {print ["The result is:" 2+3]}
do a
 
userCode: input "Give me some code: "
do userCode</syntaxhighlight>
 
{{out}}
 
<pre>The result is: 5
Give me some code: print "Hello world!"
Hello world!</pre>
 
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_H}}
function [http://www.autohotkey.net/~HotKeyIt/AutoHotkey/addScript.htm addScript] can be used to dynamically add lines of code to a running script.
<langsyntaxhighlight AutoHotkeylang="autohotkey">; requires AutoHotkey_H or AutoHotkey.dll
msgbox % eval("3 + 4")
msgbox % eval("4 + 4")
Line 106 ⟶ 167:
if fnp := FindFunc(funcName)
numput(&x%newname%, fnp+0, 0, "uint")
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 159 ⟶ 220:
In ZX Spectrum Basic, loading a new program will replace the existing program. The new program will sutomatically run, if it was saved to do so by using SAVE together with LINE:
 
<langsyntaxhighlight lang="zxbasic">
10 REM load the next program
20 LOAD "PROG2"
</syntaxhighlight>
</lang>
 
You can also include code in a text string as follows:
<langsyntaxhighlight lang="zxbasic">10 LET f$=CHR$ 187+"(x)+"+CHR$ 178+"(x*3)/2": REM LET f$="SQR (x)+SIN (x*3)/2"
20 FOR x=0 TO 2 STEP 0.2
30 LET y=VAL f$
40 PRINT y
50 NEXT x
</syntaxhighlight>
</lang>
 
CHR$ 178 is the token of function SQR, and CHR$ 178 is the token of function SIN.
 
In 48 k mode, you can also write this:
<langsyntaxhighlight lang="zxbasic">10 LET f= SQR (x)+SIN (x*3)/2</langsyntaxhighlight>
Then the type of the variable is changed and the formula is enclosed in quotation marks:
<langsyntaxhighlight lang="zxbasic">10 LET f$=" SQR (x)+SIN (x*3)/2"</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
Line 183 ⟶ 244:
===Expressions===
Expressions can be evaluated using the EVAL function:
<langsyntaxhighlight lang="bbcbasic"> expr$ = "PI^2 + 1"
PRINT EVAL(expr$)</langsyntaxhighlight>
{{out}}
<pre>
Line 192 ⟶ 253:
===Statements===
Statements can be executed by being tokenised and then written to a temporary file:
<langsyntaxhighlight lang="bbcbasic"> exec$ = "PRINT ""Hello world!"""
bbc$ = FNtokenise(exec$)
Line 208 ⟶ 269:
A$ = $(!332+2)
= CHR$(LENA$+4) + CHR$0 + CHR$0 + A$ + CHR$13
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 219 ⟶ 280:
Evaluating a block:
 
<langsyntaxhighlight lang="burlesque">
blsq ) {5 5 .+}e!
10
</syntaxhighlight>
</lang>
 
Creating code at runtime (changing map (+5) to map (+6) at runtime):
 
<langsyntaxhighlight lang="burlesque">
blsq ) 1 10r@{5.+}m[
{6 7 8 9 10 11 12 13 14 15}
blsq ) 1 10r@{5.+}6 0sam[
{7 8 9 10 11 12 13 14 15 16}
</syntaxhighlight>
</lang>
 
Code from string at runtime:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 1 10r@"5.+"psm[
{6 7 8 9 10 11 12 13 14 15}
</syntaxhighlight>
</lang>
 
Evaluating strings at runtime (reverse is just for demonstration):
 
<langsyntaxhighlight lang="burlesque">
blsq ) "[m}+.5{@r01 1"<-pe
{6 7 8 9 10 11 12 13 14 15}
</syntaxhighlight>
</lang>
 
Injecting other functions into code:
 
<langsyntaxhighlight lang="burlesque">
blsq ) {3 2}(?*)[+e!
6
</syntaxhighlight>
</lang>
 
Identifiers not contained in a block require to be quoted to push them to the stack. Note the difference:
 
<langsyntaxhighlight lang="burlesque">
blsq ) ?+
ERROR: Burlesque: (.+) Invalid arguments!
Line 265 ⟶ 326:
blsq ) (?+)to
"Ident"
</syntaxhighlight>
</lang>
 
(also note the fallback to ''.+'' from ''?+'').
Line 288 ⟶ 349:
The <tt>eval</tt> function evaluates Lisp code at runtime.
 
<langsyntaxhighlight lang="lisp">(eval '(+ 4 5)) ; returns 9</langsyntaxhighlight>
 
In Common Lisp, programs are represented as trees (s-expressions). Therefore, it is easily possible to construct a program which includes externally specified values, particularly using backquote template syntax:
 
<langsyntaxhighlight lang="lisp">(defun add-four-complicated (a-number)
(eval `(+ 4 ',a-number)))</langsyntaxhighlight>
 
Or you can construct a function and then call it. (If the function is used more than once, it would be good to use <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_cmp.htm compile]</code> instead of <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_eval.htm eval]</code>, which compiles the code before returning the function. <code>eval</code> is permitted to compile as well, but <code>compile</code> requires it.)
 
<langsyntaxhighlight lang="lisp">(defun add-four-by-function (a-number)
(funcall (eval '(lambda (n) (+ 4 n)))) a-number)</langsyntaxhighlight>
 
If your program came from a file or user input, then you have it as a string, and [http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_rd.htm <code>read</code>] or <code>read-from-string</code> will convert it to s-expression form:
 
<langsyntaxhighlight lang="lisp">(eval (read-from-string "(+ 4 5)"))</langsyntaxhighlight>
 
Common Lisp has lexical scope, but <code>eval</code> always evaluates “in the null lexical environment”. In particular, <code>eval</code> does not inherit the lexical variables from the enclosing code. (Note that <code>eval</code> is an ordinary function and as such does not have access to that environment anyway.)
 
<langsyntaxhighlight lang="lisp">(let ((x 11) (y 22))
;; This is an error! Inside the eval, x and y are unbound!
(format t "~%x + y = ~a" (eval '(+ x y))))</langsyntaxhighlight>
 
One way to fix the error is to <tt>(declare (special x y))</tt> for dynamic variables; but the easier and shorter way is to insert the values of x and y with the backquote template syntax.
 
<langsyntaxhighlight lang="lisp">(let ((x 11) (y 22))
(format t "~%x + y = ~a" (eval `(+ ,x ,y))))</langsyntaxhighlight>
 
===Sandboxing Discussion===
Line 321 ⟶ 382:
One approach to define a sublanguage and validate expressions before passing them to <code>compile</code> or <code>eval</code>. Of course, a whole different language entirely can be defined, and translated to Lisp. This is essentially the classic "trusted compiler generating safe code in an untrusted target language" approach.
 
One way to simplify the validator is to use the package system to create a sandbox. This is done by defining a package arbitrarily called <code>sandbox</code>. The validator then simply has to make sure that all symbols used in the expression are restricted to those which are visible inside the <code>sandbox</code> package. Inside <code>sandbox</code>, we include only those functions, operators, variables and other symbols from system packages that are safe: materials which don't allow sandboxed code to do anything harmful from within the sandbox, or to escape from the sandbox. For instance, suppose that some package <code>system</code> has a function called <code>run-shell-command</code>. We do not import <code>run-shell-command</code> into the <code>sandbox</code> package, and our validator will reject code which has references such as <langsyntaxhighlight lang="lisp">(system:run-shell-command ...)</langsyntaxhighlight>. Therefore, the sandboxed code has no direct way to run that function. To gain access to it, it must exploit some flaw in the sandbox. One flaw in the sandbox would be the inclusion of certain package-related functions like <code>find-symbol</code>. The expression <langsyntaxhighlight lang="lisp">(find-symbol "FOO" "BAR")</langsyntaxhighlight> will retrieve symbol <code>foo::bar</code> if it exists. The validator will not find this code because it has no embedded symbolic references to package <code>foo</code>; they are disguised as character string. A cautious approach to the sandbox should be taken: include less rather than more, and consider each expansion of the sandbox with meticulous care.
 
===Debugging Notes===
Line 332 ⟶ 393:
Each compiled fragment is considered to be a single "file", and cannot access any local variables from outside of itself.
 
<langsyntaxhighlight lang="dejavu">!run-blob !compile-string "(fake filename)" "!print \qHello world\q"</langsyntaxhighlight>
{{out}}
<pre>Hello world</pre>
Line 342 ⟶ 403:
The lexical environment is provided as a parameter and cannot be omitted. The evaluated program has no access to anything but the provided environment.
 
<langsyntaxhighlight lang="e">? e`1 + 1`.eval(safeScope)
# value: 2</langsyntaxhighlight>
 
<code>eval</code> returns the value of the expression. <code>evalToPair</code> also returns the modified environment for use with further evaluation, e.g. for implementing a [[REPL]].
 
<langsyntaxhighlight lang="e">? def [value, env] := e`def x := 1 + 1`.evalToPair(safeScope)
# value: [2, ...]
 
? e`x`.eval(env)
# value: 2</langsyntaxhighlight>
 
Eval from a string may be done by invoking the parser.
 
<langsyntaxhighlight lang="e">? def prog := <elang:syntax.makeEParser>.run("1 + 1")
# value: e`1.add(1)`
 
? prog.eval(safeScope)
# value: 2</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
'''eval''' : The evaluation of the eval argument must give a symbolic expression, which is in turn evaluated. Alternatively, '''read-from-string''' produces a s-expression - any kind of program - from a string.
<langsyntaxhighlight lang="scheme">
(eval (list * 6 7))
→ 42
Line 370 ⟶ 431:
(eval (read-from-string "(* 6 7)"))
→ 42
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 6.x:
Using ELENA Script engine and VM client mode (3.3.0):
Using ELENA Script engine:
<lang elena>import extensions'scripting.
<syntaxhighlight lang="elena">import extensions'scripting;
 
public program()
program =
{
[
escript evallscript.interpretLine("system'console .writeLine(""Hello World"").").;
}</syntaxhighlight>
].</lang>
{{out}}
<pre>
Line 385 ⟶ 448:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> Code.eval_string("x + 4 * Enum.sum([1,2,3,4])", [x: 17])
{57, [x: 17]}
iex(2)> Code.eval_string("c = a + b", [a: 1, b: 2])
{3, [a: 1, b: 2, c: 3]}
iex(3)> Code.eval_string("a = a + b", [a: 1, b: 2])
{3, [a: 3, b: 2]}</langsyntaxhighlight>
 
=={{header|Erlang}}==
 
Erlang eval is a bit complex/verbose and requires the interaction of 3 modules: <tt>erl_scan</tt> (tokenizes), <tt>erl_parse</tt> (returns an abstract form) and <tt>erl_eval</tt> (variable binding, evaluate abstract form, etc).
<langsyntaxhighlight lang="erlang">1> {ok, Tokens, _} = erl_scan:string("X + 4 * lists:sum([1,2,3,4]).").
...
2> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
Line 405 ⟶ 468:
5> Value.
57
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 433 ⟶ 496:
=={{header|Forth}}==
EVALUATE invokes the interpreter on a string of Forth code, using and modifying the current dictionary and stack state.
<langsyntaxhighlight lang="forth">s" variable foo 1e fatan 4e f*" evaluate
 
f. \ 3.14159...
1 foo !</langsyntaxhighlight>
 
Sandboxing can be achieved in general by using MARKER, which defines a checkpoint for the dictionary state which can later be restored.
 
<langsyntaxhighlight lang="forth">unused . \ show how much dictionary space is available
marker restore
 
Line 449 ⟶ 512:
 
restore
unused . \ same as first unused; restore, foo, and my-def no longer defined</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="vb">#macro assign(sym, expr)
__fb_unquote__(__fb_eval__("#undef " + sym))
__fb_unquote__(__fb_eval__("#define " + sym + " " + __fb_quote__(__fb_eval__(expr))))
#endmacro
 
#define a, b, x
 
assign("a", 8)
assign("b", 7)
assign("x", Sqr(a) + (Sin(b*3)/2))
Print x
 
assign("x", "goodbye")
Print x
 
Sleep</syntaxhighlight>
{{out}}
<pre> 3.246754944014219
goodby</pre>
 
=={{header|Frink}}==
The <CODE>eval[]</CODE> function can be used to evaluate aribitraryarbitrary Frink code in the current environment, or in a new context.
<langsyntaxhighlight lang="frink">
eval["length = 1234 feet + 2 inches"]
</syntaxhighlight>
</lang>
 
There is also a two-argument version, <CODE>eval[expression, rethrows]</CODE> where the <CODE>rethrows</CODE> argument is a boolean flag indicating if we want evaluation errors to be thrown or just suppressed and <CODE>undef</CODE> returned. If it is true, errors will be rethrown as Java exceptions, otherwise an error returns undef.
Line 465 ⟶ 549:
=={{header|Go}}==
As a compiled, strongly typed language, <code>eval()</code> is not the strong suit of Go. Nevertheless, an <code>eval</code> package exists that does that. Just don't expect it to be as easy or efficient as in interpreted languages. The eval package was originally part of the Go standard library but is now hosted and maintained externally.
<langsyntaxhighlight lang="go">package main
import (
"fmt"
Line 489 ⟶ 573:
fmt.Println("Return value:", val) //prints, well, 3
 
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 500 ⟶ 584:
A script is a either a set of statements to be executed in order, or a Groovy class with a '''main()''' method, or a Groovy '''Thread''' subclass or '''Runnable''' implementation.
The return value is the value of the last statement executed, or the value of an explicit '''return''' statement (if any).
<langsyntaxhighlight lang="groovy">def years1 = new GroovyShell().evaluate('''
(2008..2121).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
Line 506 ⟶ 590:
''')
 
println years1</langsyntaxhighlight>
 
The last expression evaluated in the script, a list of years found, is the return value of the '''evaluate()''' method.
Line 518 ⟶ 602:
'''GString''' embedded values<br>
Setting up the script as a '''GString''' with embedded value parsing is a "natural" ''ad hoc'' solution for Groovy programmers, but there are possible pitfalls if the script itself contains '''GString'''s.
<langsyntaxhighlight lang="groovy">def startYear = 2008
def endYear = 2121
def years2 = new GroovyShell().evaluate("""
Line 526 ⟶ 610:
""")
 
println years2</langsyntaxhighlight>
The variables "startYear" and "endYear" are dynamically pulled into the script '''GString''' as embedded values before the script itself ever executes.
 
Line 533 ⟶ 617:
'''Binding''' variables<br>
'''GroovyShell''' uses a '''Binding''' object to pass variable values to a script. This is the only way to pass variables if the script comes from a '''File''' or '''InputStream''', but even if the script is a string '''Binding''' avoids the nested quoting issue caused by the ''ad hoc'' use of '''GString'''.
<langsyntaxhighlight lang="groovy">def context = new Binding()
context.startYear = 2008
context.endYear = 2121
Line 540 ⟶ 624:
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')</langsyntaxhighlight>
 
We may instantiate '''Binding''' with the variables as named parameters, allowing a more terse syntax:
<langsyntaxhighlight lang="groovy">def years4 = new GroovyShell( new Binding(startYear: 2008, endYear: 2121) ).evaluate('''
(startYear..endYear).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
Line 549 ⟶ 633:
''')
 
println years4</langsyntaxhighlight>
 
We may also access the '''Binding''' object ''after'' script evaluation to extract values of any global variables set during the evaluation:
<langsyntaxhighlight lang="groovy">def binding = new Binding(startYear: 2008, endYear: 2121)
new GroovyShell( binding ).evaluate('''
yearList = (startYear..endYear).findAll {
Line 559 ⟶ 643:
''')
 
println binding.yearList</langsyntaxhighlight>
 
'''Eval''' shortcut<br>
For simple evaluation of string-based scripts with only a few variables (like this one), the '''Eval''' class has static shortcut methods that do the '''Binding''' setup and '''GroovyShell''' evaluation under the surface. '''Eval.me(script)''' evaluates a script with no variables. '''Eval.x(x,script)''', '''Eval.xy(x,y,script)''', or '''Eval.xyz(x,y,z,script)''' each evaluates a script with 1, 2, or 3 variables, respectively. Here is an example with start and end years as script variables ''x'' and ''y''.
<langsyntaxhighlight lang="groovy">def years5 = Eval.xy(2008, 2121, '''
(x..y).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
Line 569 ⟶ 653:
''')
 
println years5</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">10 LINE INPUT "Type an expression: ",A$
20 OPEN "CHAIN.TMP" FOR OUTPUT AS #1
30 PRINT #1, "70 LET Y=("+A$+")"
Line 581 ⟶ 665:
80 PRINT X,Y
90 NEXT X
100 GOTO 10</langsyntaxhighlight>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="harbour">
Procedure Main()
local bAdd := {|Label,n1,n2| Qout( Label ), QQout( n1 + n2 )}
Line 594 ⟶ 678:
5+5 = 10
5-5 = 0
</syntaxhighlight>
</lang>
 
=={{header|HicEst}}==
XEQ invokes the interpreter on a string of HicEst code, but keeps the current dictionary and stack state. Blocks of expressions are not possible.
<langsyntaxhighlight HicEstlang="hicest">value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6
! temp is undefined outside XEQ, if it was not defined before.
 
Line 605 ⟶ 689:
OPEN(FIle="my_file.txt")
READ(FIle="my_file.txt", Row=6) string
XEQ( string ) ! executes row 6 of my_file.txt</langsyntaxhighlight>
 
=={{Header|Insitux}}==
 
All valid Insitux code can be evaluated at runtime using <code>eval</code>, including function definitions which remain in global scope, with access to global scope but not local.
 
<syntaxhighlight lang="insitux">
(var x 123)
[
(eval "(var y 100) (+ x y)")
y
]
</syntaxhighlight>
 
{{out}}
 
<pre>
[223 100]
</pre>
 
Error messages differ between normal code and evaluated code.
 
<b>Normal invocation error output:</b>
 
<pre>
1:6 (let time 1)
Parse Error: "time" cannot be redefined: already exists.
</pre>
 
<b><code>eval</code> invocation error output:</b>
 
<pre>
1:2 (eval "(let time 1)")
Eval Error: error within evaluated code.
Parse Error: 1695133413649 eval line 1 col 6: "time" cannot be redefined: already exists
</pre>
 
=={{header|J}}==
Use monadic [http://www.jsoftware.com/help/dictionary/d601.htm <code>".</code>] (''Do'') to execute a string.
 
<langsyntaxhighlight lang="j">". 'a =: +/ 1 2 3' NB. execute a string to sum 1, 2 and 3 and assign to noun a</langsyntaxhighlight>
 
Only J expressions are allowed in strings used as as arguments for <code>".</code> (control words and blocks of expressions are not allowed).
Line 616 ⟶ 735:
Alterntively, you can use the conjunction [http://www.jsoftware.com/help/dictionary/d310n.htm <code>:</code>] (''Explicit Definition'') to create various kinds of functions and evaluate them. Arguments have names, such as "y", which are specified by the language definition. For example:
 
<langsyntaxhighlight lang="j">monad :'+/y' 1 2 3</langsyntaxhighlight>
 
Rules of scope for such functions match those described on the [[Scope modifiers]] page. Also, control words (like if. or for. or while.) and blocks of expressions are allowed in strings which are evaluated in this fashion.
Line 625 ⟶ 744:
 
J relies on the OS for sandboxing and does not offer any additional resource constraints.
 
 
=={{header|Java}}==
You can kind-of do this in Java. The compiler has the relevant APIs, so it is "considered part of your language/library/platform". You have to get a compiler (which may fail), make a pseudo-file-system, compile your class, and make a class loader that will load it. Then you can use regular Java reflection to make an instance and call methods on it.
 
Longest "Hello world" program ever?<langsyntaxhighlight Javalang="java">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
Line 715 ⟶ 833:
}
}
}</langsyntaxhighlight>
 
{{Out}}
Line 722 ⟶ 840:
at Evaluator.eval(Evaluator.java:33)
at Evaluator.main(Evaluator.java:21)</pre>
 
===Java REPL===
Java has a REPL called jshell which can be used for runtime evaluation. It is started by entering the jshell command from the command line. Here is a typical session:
<pre>
C:\Program Files\JDK\bin> .\jshell
| Welcome to JShell -- Version 20
| For an introduction type: /help intro
 
jshell> double value = 12.0
value ==> 12.0
 
jshell> value * 3
$2 ==> 36.0
 
jshell> List<Integer> items = List.of( 1, 2, 3 )
items ==> [1, 2, 3]
 
jshell> for ( int item : items ) { System.out.print(item * item + " "); }
1 4 9
 
jshell> void helloWorld() { System.out.println("Hello World"); }
| created method helloWorld()
 
jshell> helloWorld()
Hello World
 
jshell> /exit
| Goodbye
</pre>
 
=={{header|JavaScript}}==
The eval method handles statements and expressions well:
<langsyntaxhighlight lang="javascript">
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
Line 731 ⟶ 878:
typeof foo; // 'object'
typeof bar; // 'string'
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Runtime evaluation, in Jsish */
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
Line 751 ⟶ 898:
bar ==> Hello, world!
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 765 ⟶ 912:
To run an entire script in the current env:
 
<langsyntaxhighlight lang="julia">include("myfile.jl")</langsyntaxhighlight>
 
To run a string in the current env:
 
<langsyntaxhighlight lang="julia">include_string("""
x = sum([1, 2, 3])
@show x
""")
 
@show typeof(x) # Int64</langsyntaxhighlight>
 
=={{header|Kotlin}}==
Line 796 ⟶ 943:
48
>>> :quit
</pre>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
# Simple assignements are used so that rvalues are parsed as TEXT values
$code=fn.println(Hello World!)
# Returns VOID unless return or throw is explicitly used
fn.exec($code)
 
$code=return Hello World!
fn.println(fn.exec($code))
 
$code=throw $LANG_ERROR_DIV_BY_ZERO
# Will print "Dividing by 0" in the Standard Lang implementation (Error texts are not standardized)
fn.println(fn.errorText(fn.exec($code)))
 
$code=parser.op(20//0)
# Will return VOID because no error was thrown explicitly
fn.println(fn.exec($code))
</syntaxhighlight>
This is the output for the Standard Lang implementation.
{{out}}
<pre>
Hello World!
Hello World!
An error occured [error output: redacted]
Dividing by 0
An error occured [error output: redacted]
 
</pre>
 
Line 813 ⟶ 989:
the third parameter in the sourcefile invocation.
 
<langsyntaxhighlight Lassolang="lasso">//code, fragment name, autocollect, inplaintext
local(mycode = "'Hello world, it is '+date")
sourcefile('['+#mycode+']','arbritraty_name', true, true)->invoke
Line 842 ⟶ 1,018:
local(mycode = "var(x) *= var(z)")
sourcefile(#mycode,'arbritraty_name', false, false)->invoke
'var x is now: '+$x</langsyntaxhighlight>
 
{{out}}
Line 853 ⟶ 1,029:
=={{header|Liberty BASIC}}==
Liberty BASIC has the ability to evaluate arrays using a string for the array name and a variable for the element.
<syntaxhighlight lang="lb">
<lang lb>
'Dimension a numerical and string array
Dim myArray(5)
Line 873 ⟶ 1,049:
Print Eval$(numArrayName$ + "(" + str$(i) + ")")
Print Eval$(strArrayName$ + "$(" + str$(i) + ")")
Next i </langsyntaxhighlight>
 
An example using a struct and a pointer.
<syntaxhighlight lang="lb">
<lang lb>
Struct myStruct, value As long, _
string As ptr
Line 890 ⟶ 1,066:
'Pay close attention that this is EVAL() because we are
'retrieving the PTR to the string which is essentially a ulong
Print Winstring(Eval(structName$ + "." + strElement$ + "." + "struct")) </langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">f = loadstring(s) -- load a string as a function. Returns a function.
 
one = loadstring"return 1" -- one() returns 1
 
two = loadstring"return ..." -- two() returns the arguments passed to it</langsyntaxhighlight>
 
In Lua 5.2 the <code>loadstring</code> function is superseded by the more general <code>load</code> function, which can be used in a compatible way. Nevertheless, <code>loadstring</code> is still available.
Line 903 ⟶ 1,079:
{{works with|Lua|5.2}}
 
<langsyntaxhighlight lang="lua">f = load("return 42")
f() --> returns 42</langsyntaxhighlight>
 
In Lua 5.3+ (5.3, 5.4) <code>loadstring</code> is no longer available, use <code>load</code> instead.
<syntaxhighlight lang="lua">> f = load("return 42")
> f()
42
> n = load("return 42")()
> n
42</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module checkit {
Module dummy {
Line 943 ⟶ 1,127:
}
CheckIt
</syntaxhighlight>
</lang>
 
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica's <code>ToExpression</code> evaluates an expression string as if it were placed directly in the code. Statements are just <code>CompoundExpression</code>s, so they also work. Any evaluation can be limited with <code>TimeConstrained</code> and <code>MemoryConstrained</code>.
<langsyntaxhighlight Mathematicalang="mathematica">Print[ToExpression["1 + 1"]];
Print[ToExpression["Print[\"Hello, world!\"]; 10!"]];
x = 5;
Line 956 ⟶ 1,139:
Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]];
Print[TimeConstrained[ToExpression["Pause[1]; True"], 2, False]];
Print[TimeConstrained[ToExpression["Pause[60]; True"], 2, False]];</langsyntaxhighlight>
{{out}}
<pre>2
Line 971 ⟶ 1,154:
The eval and evalin functions handles any kind of code. It can handle multi-line code, although it needs the lines to be separated by the newline character. It can even allow you to program at runtime, as illustrated in the last example in the code and output below.
Errors can occur when mixing eval statements with regular code, especially "compile-time" errors if the code appears to be missing key elements (ending brackets or end statements, etc). Some of these are also demonstrated.
<langsyntaxhighlight MATLABlang="matlab">function testEval
fprintf('Expressions:\n')
x = eval('5+10^2')
Line 1,007 ⟶ 1,190:
end
eval(codeBlock)
end</langsyntaxhighlight>
{{out}}
<pre>Expressions:
Line 1,049 ⟶ 1,232:
=={{header|Maxima}}==
 
<langsyntaxhighlight lang="maxima">/* Here is how to create a function and return a value at runtime. In the first example,
the function is made global, i.e. it still exists after the statement is run. In the second example, the function
is declared local. The evaluated string may read or write any variable defined before eval_string is run. */
Line 1,065 ⟶ 1,248:
 
fundef(f);
/* f(x) := x^2 + 1 */</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
The exec() function runs code contained within a string as if it were being read from a file, so any valid code may be run.
<langsyntaxhighlight lang="nanoquery">exec("println \"hello, world\"")
exec("a = 1\nif a = 1\nprintln \"a is 1\"\nend\nprintln \"test\"")</langsyntaxhighlight>
{{out}}
<pre>hello, world
a is 1
test</pre>
=={{header|Nim}}==
'''File: runtime_eval.nim'''
<syntaxhighlight lang="nim">import ../compiler/[nimeval, llstream, ast], strformat, os
 
let std = findNimStdLibCompileTime()
let modules = [std, std / "pure", std / "std", std / "core"]
var intr = createInterpreter("script", modules)
 
#dynamic variable
let varname = commandLineParams()[0]
let expr = commandLineParams()[1]
 
#wrap the naked variable name and expression in a definition and proc,respectively to create valid code
#for simplicity, the variable will always be an int, but one could of course define the type at runtime
#globals and procs must be exported with * to be accessable
#we also need to import any modules needed by the runtime code
intr.evalScript(llStreamOpen(&"import math,sugar; var {varname}*:int; proc output*():auto = {expr}"))
 
for i in 0..2:
#set 'varname' to a value
intr.getGlobalValue(intr.selectUniqueSymbol(varname)).intval = i
#evaluate the expression and get the result
let output = intr.callRoutine(intr.selectRoutine("output"), [])
#depending on the expression, the result could be any type
#as an example, here we check for int,float,or string
case output.kind
of nkIntLit:
echo expr, " = ", output.intval
of nkFloatLit:
echo expr, " = ", output.floatval
of nkStrLit:
echo expr, " = ", output.strval
else:
discard
 
destroyInterpreter(intr)</syntaxhighlight>
'''Usage'''
<pre>nim c runtime_eval.nim
./runtime_eval bar 'exp(bar.float)'
./runtime_eval foo 'sum(collect(for i in 1..foo+1: i*i))'
./runtime_eval baz '["hello","dynamic","world"][baz]'</pre>
{{out}}
The second example works only with development version 1.5.x. Other examples work with version 1.4.x.
<pre>
exp(bar.float) = 1.0
exp(bar.float) = 2.718281828459045
exp(bar.float) = 7.38905609893065
sum(collect(for i in 1..foo+1: i*i)) = 1
sum(collect(for i in 1..foo+1: i*i)) = 5
sum(collect(for i in 1..foo+1: i*i)) = 14
["hello","dynamic","world"][baz] = hello
["hello","dynamic","world"][baz] = dynamic
["hello","dynamic","world"][baz] = world</pre>
 
=={{header|Oforth}}==
Line 1,082 ⟶ 1,318:
In order to restrict evaluation, perform is used on strings. With perform, only objects can be evaluated. If a function or a method is included into the string an exception is raised and the function is not evaluated.
 
<langsyntaxhighlight Oforthlang="oforth">"[ [ $a, 12], [$b, 1.2], [ $c, [ $aaa, $bbb, $ccc ] ], [ $torun, #first ] ]" perform .s
[1] (List) [[a, 12], [b, 1.2], [c, [aaa, bbb, ccc]], [torun, #first]]
 
"12 13 +" perform
[1:interpreter] ExCompiler : Can't evaluate <+></langsyntaxhighlight>
 
 
In order to evaluate any Oforth code, eval can be used. This method should not be used on unsafe strings.
 
<langsyntaxhighlight Oforthlang="oforth">"12 13 + println" eval
25
": newFunction(a) a + ; 12 10 newFunction println" eval
22</langsyntaxhighlight>
 
=={{header|ooRexx}}==
The ooRexx INTERPRET instruction allows execution of dynamically constructed code. Almost any well-formed code can be executed dynamically, including multiple instructions at a time. The instructions are executed in the local context where the interpret instruction executes, so full access to the current variable context is available. For example:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
a = .array~of(1, 2, 3)
ins = "loop num over a; say num; end"
interpret ins
</syntaxhighlight>
</lang>
Executes the LOOP instruction, displaying the contents of the array pointed to by variable A.
 
Line 1,110 ⟶ 1,346:
This demo produces tables of Y values, given a formula, and a range of X values to step through.
 
<langsyntaxhighlight lang="oxygenbasic">
 
function ExecSeries(string s,double b,e,i) as string
Line 1,163 ⟶ 1,399:
print ExecSeries "y=sqrt x",1, 9 , 1
 
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% simplest case: just evaluate expressions without bindings
R1 = {Compiler.virtualStringToValue "{Abs ~42}"}
Line 1,182 ⟶ 1,418:
{Engine enqueue(setSwitch(expression false))} %% statements instead of expr.
{Engine enqueue(mergeEnv(env('A':42 'System':System)))}
{Engine enqueue(feedVirtualString("{System.show A}"))}</langsyntaxhighlight>
 
By restricting the environment it is possible to restrict what kind of programs can be run.
Line 1,189 ⟶ 1,425:
Since GP is usually run from the [[wp:Read–eval–print loop|REPL]] gp, it is trivial to evaluate programs at runtime (most are run this way). Slightly less trivial is passing code around as a first-class object:
 
<langsyntaxhighlight lang="parigp">runme(f)={
f()
};
 
runme( ()->print("Hello world!") )</langsyntaxhighlight>
 
One facility designed for restricting such embedded programs is <code>default(secure,1)</code> which denies scripts the ability to run <code>system</code> and <code>extern</code>. This cannot be turned off except interactively.
Line 1,203 ⟶ 1,439:
* If the subprogram throws an exception, <code>eval</code> returns <code>undef</code>. The text of the exception is assigned to <code>$@</code>. (When the subprogram terminates without an exception, <code>$@</code> is set to the null string instead.)
 
<langsyntaxhighlight lang="perl">my ($a, $b) = (-5, 7);
$ans = eval 'abs($a * $b)'; # => 35</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
The eval() function can be used to run fragments of code. The code is run in a brand new context and
Any syntactically valid sequence of statements may be run, and the snippet to be run can see its outer lexical scope at the point of the <tt>eval</tt>:
hence must be valid in a standalone sense, and cannot directly reference any external identifiers.
<lang perl6>use MONKEY-SEE-NO-EVAL;
Any existing data that needs to be accessed must be provided via the ival and/or iset parameters, and
any results must be explicitly requested via the rset parameter, and any updates applied/extracted
once eval() returns. Passing large tables into and out of the eval context is actually quite efficient,
though some careful refcount management may improve performance, as detailed in the docs.<br>
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Runtime_evaluation.exw</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">include</span> <span style="color: #7060A8;">eval</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- (not an autoinclude, pulls in around 90% of the interpreter/compiler proper)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">code</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
integer i = 0
bool r_init = false
sequence r
if not r_init then r = {} end if
for k=1 to 4 do
i += k
r &= k
end for
"""</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #000000;">code</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"i"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- prints {10,{1,2,3,4}}</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #000000;">code</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">},{{</span><span style="color: #008000;">"r_init"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}}})</span> <span style="color: #000080;font-style:italic;">-- prints {5,1,2,3,4}</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #000000;">code</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"i"</span><span style="color: #0000FF;">},{{</span><span style="color: #008000;">"i"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">}})</span> <span style="color: #000080;font-style:italic;">-- prints {25}</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`puts(1,"Hello World\n")`</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- prints Hello World</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{10,{1,2,3,4}}
{{5,1,2,3,4}}
{25}
Hello World
</pre>
 
===Evaluating expressions===
my ($a, $b) = (-5, 7);
Just as a bare (say) "3+4" in a normal source code file would trigger a syntax error, so too would
my $ans = EVAL 'abs($a * $b)'; # => 35</lang>
passing that directly to the eval() function. However it is of course trivial to assign the result
Unlike in Perl 5, <tt>eval</tt> in Perl 6 only compiles and executes the string, but does not trap exceptions. You must say <tt>try eval</tt> to get that behavior (or supply a <tt>CATCH</tt> block within the text to be evaluated).
of an expression to a (newly declared) variable and return that:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">eval_expression</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">expr</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"object x = %s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">expr</span><span style="color: #0000FF;">}),{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">eval_expression</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3+4"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- prints 7</span>
<!--</syntaxhighlight>-->
 
===Sandboxing===
It is perfectly possible to add a "with safe_mode" prefix to the code passed to eval(), however any runtime error message generated appears to use the wrong symbol table, and therefore is largely gibberish, but at least it blocks dangerous things properly. Slightly better or more readable error messages may be produced by compiling the program, as in the one that invokes eval(), instead of interpreting it.
 
=={{header|PHP}}==
The [http://www.php.net/eval eval construct] allow string evaluation as PHP code. Opening and closing tags are not required. Return statements immediatly terminates evaluation . Eval returns NULL, unless return is called in evalued code.
<langsyntaxhighlight lang="php">
<?php
$code = 'echo "hello world"';
Line 1,222 ⟶ 1,501:
$code = 'return "hello world"';
print eval($code);
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
Line 1,252 ⟶ 1,531:
=={{header|Pike}}==
Pike provides [http://pike.ida.liu.se/doc/compile_string() <code>compile_string()</code>] and [http://pike.ida.liu.se/doc/compile_file() <code>compile_file()</code>] which can compile code into a class that can be instantiated:
<langsyntaxhighlight Pikelang="pike">program demo = compile_string(#"
string name=\"demo\";
string hello()
Line 1,260 ⟶ 1,539:
 
demo()->hello();
Result: "hello, i am demo"</langsyntaxhighlight>
 
an actual application of this is shown in [[Simple database]].
Line 1,266 ⟶ 1,545:
=={{header|PowerShell}}==
Evaluate an expression:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$test2plus2 = '2 + 2 -eq 4'
Invoke-Expression $test2plus2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,275 ⟶ 1,554:
</pre>
Evaluate a <code>[scriptblock]</code> (a statement or group of statements) with code surrounded by curly braces using the '''&''' ('''call''') operator:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$say = {"Hello, world!"}
& $say
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,284 ⟶ 1,563:
</pre>
Scriptblocks behave just as functions so they may have parameters:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$say = {param ([string]$Subject) "Hello, $Subject!"}
& $say -Subject "my friend"
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,293 ⟶ 1,572:
</pre>
A slightly more complex example:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$say = {param ([string]$Exclamation, [string]$Subject) "$Exclamation, $Subject!"}
& $say -Exclamation "Goodbye" -Subject "cruel world"
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,302 ⟶ 1,581:
</pre>
To reverse the normal behaviour of a <code>[scriptblock]</code> use the '''GetNewClosure''' method. This makes the scriptblock self-contained or closed; ie, the variable will only be read when the scriptblock is initialised:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$title = "Dong Work For Yuda"
$scriptblock = {$title}
Line 1,309 ⟶ 1,588:
& $scriptblock
& $closedScriptblock
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,316 ⟶ 1,595:
</pre>
Change the variable and execute the scriptblock, the closed version will not reflect the change:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$title = "I'm Too Sexy"
& $scriptblock
& $closedScriptblock
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,332 ⟶ 1,611:
The [http://docs.python.org/reference/simple_stmts.html#exec exec statement] allows the optional passing in of global and local names via mappings (See the link for full syntax). The example below shows exec being used to parse and execute a string containing two statements:
 
<langsyntaxhighlight lang="python">>>> exec '''
x = sum([1,2,3,4])
print x
'''
10</langsyntaxhighlight>
 
{{works with|Python|3.x}}
Note that in Python 3.x [http://docs.python.org/py3k/library/functions.html#exec exec] is a function:
 
<langsyntaxhighlight lang="python">>>> exec('''
x = sum([1,2,3,4])
print(x)
''')
10</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Quackery includes the word <code>build</code> which takes a string of Quackery code and returns evaluable code, which can be evaluated with <code>do</code>. These two functionalities are combined in the word <code>quackery</code>, defined as <code>[ build do ] is quackery</code>, neatly summarising the way Quackery works.
 
Any Quackery code fragment can be passed as a string to <code>quackery</code>, with parameters and results being passed via the stack. In the sample code, the string <code>"1 swap times [ i 1+ * ]"</code>, when compiled and evaluated by <code>quackery</code>, will take the <code>10</code> placed on the stack beforehand, compute its factorial and leave the result on the stack for <code>echo</code> to echo to the screen.
 
<syntaxhighlight lang="text">10 $ "1 swap times [ i 1+ * ]" quackery echo</syntaxhighlight>
 
{{out}}
 
<pre>3628800</pre>
 
=={{header|R}}==
Line 1,356 ⟶ 1,647:
Thus all these three are equivalent.
 
<langsyntaxhighlight lang="r">expr1 <- quote(a+b*c)
expr2 <- parse(text="a+b*c")[[1]]
expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))</langsyntaxhighlight>
 
<tt>eval()</tt> evaluates a quoted expression. <tt>evalq()</tt> is a version of <tt>eval()</tt> which quotes its first argument.
 
<langsyntaxhighlight lang="r">> a <- 1; b <- 2; c <- 3
> eval(expr1)
[1] 7</langsyntaxhighlight>
 
<tt>eval()</tt> has an optional second environment which is the lexical environment to evaluate in.
 
<langsyntaxhighlight lang="r">> env <- as.environment(list(a=1, b=3, c=2))
> evalq(a, env)
[1] 1
Line 1,378 ⟶ 1,669:
> assign("b", 5, env) # assign() can assign into environments
> eval(expr1, env)
[1] 11</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,384 ⟶ 1,675:
Racket has the usual <tt>eval</tt> that is demonstrated [[Runtime_evaluation/In_an_environment#Racket|here]], and in addition, it has a sandbox environment that provides a safe evaluator that is restricted from accessing files, network, etc.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require racket/sandbox)
Line 1,393 ⟶ 1,684:
;; (e '(delete-file "/etc/passwd"))
;; --> delete-file: `delete' access denied for /etc/passwd
</syntaxhighlight>
</lang>
 
And, of course, both of these methods can use Racket's multilingual capabilities and evaluate the code in a language with different semantics.
 
=={{header|Raku}}==
(formerly Perl 6)
Any syntactically valid sequence of statements may be run, and the snippet to be run can see its outer lexical scope at the point of the <tt>eval</tt>:
<syntaxhighlight lang="raku" line>use MONKEY-SEE-NO-EVAL;
 
my ($a, $b) = (-5, 7);
my $ans = EVAL 'abs($a * $b)'; # => 35</syntaxhighlight>
Unlike in Perl 5, <tt>eval</tt> in Raku only compiles and executes the string, but does not trap exceptions. You must say <tt>try eval</tt> to get that behavior (or supply a <tt>CATCH</tt> block within the text to be evaluated).
 
=={{header|REBOL}}==
Line 1,401 ⟶ 1,701:
 
It performs the fundamental interpretive action of the Rebol language and is used internally within many other functions such as <tt>if, case, while, loop, repeat, foreach</tt>, and others.
<langsyntaxhighlight lang="rebol">a: -5
b: 7
answer: do [abs a * b] ; => 35</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,409 ⟶ 1,709:
:::* &nbsp; &nbsp; run-time evaluation of an internal expression, &nbsp; and
:::* &nbsp; &nbsp; run-time evaluation of a user-prompted expression.
<langsyntaxhighlight lang="rexx">/*REXX program illustrates the ability to execute code entered at runtime (from C.L.)*/
numeric digits 10000000 /*ten million digits should do it. */
bee=51
Line 1,428 ⟶ 1,728:
say 'length of result='length(?)
say ' left 50 bytes of result='left(?,50)"···"
say 'right 50 bytes of result=···'right(?, 50) /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the input: <tt> 2**44497 - 1 </tt>
<br>which happens to be the 27th Mersenne prime.
Line 1,447 ⟶ 1,747:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Eval("nOutput = 5+2*5 " )
See "5+2*5 = " + nOutput + nl
Line 1,453 ⟶ 1,753:
Eval("func test see 'message from test!' ")
test()
</syntaxhighlight>
</lang>
Output :
<langsyntaxhighlight lang="ring">
5+2*5 = 15
1
Line 1,468 ⟶ 1,768:
10
message from test!
</syntaxhighlight>
</lang>
 
We can create simple interactive programming environment using the next program
<langsyntaxhighlight lang="ring">
while true
see nl + "code:> "
Line 1,481 ⟶ 1,781:
done
end
</syntaxhighlight>
</lang>
 
Output
<langsyntaxhighlight lang="ring">
code:> see "hello world"
hello world
Line 1,505 ⟶ 1,805:
 
code:> bye
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
 
The <tt>eval</tt> method evaluates a string as code and returns the resulting object. With one argument, it evaluates in the current context:
<langsyntaxhighlight lang="ruby">a, b = 5, -7
ans = eval "(a * b).abs" # => 35</langsyntaxhighlight>
 
With two arguments, <tt>eval</tt> runs in the given <tt>Binding</tt> or <tt>Proc</tt> context:
<langsyntaxhighlight lang="ruby">def first(main_var, main_binding)
foo = 42
second [[main_var, main_binding], ["foo", binding]]
Line 1,531 ⟶ 1,831:
 
hello = "world"
first "hello", binding</langsyntaxhighlight>
<pre>value of hello is world
value of foo is 42
Line 1,539 ⟶ 1,839:
In Scheme, the expression passed to eval is evaluated in the current interaction environment, unless otherwise specified. The result is read back as a Scheme value.
 
<langsyntaxhighlight lang="scheme">> (define x 37)
> (eval '(+ x 5))
42
Line 1,550 ⟶ 1,850:
> (display (eval (read)))
(+ 4 5) ;; this is input from the user.
9</langsyntaxhighlight>
 
=={{header|Sidef}}==
The eval method evaluates a string as code and returns the resulting object.
 
<langsyntaxhighlight lang="ruby">var (a, b) = (-5, 7);
say eval '(a * b).abs'; # => 35
say (a * b -> abs); # => 35</langsyntaxhighlight>
 
=={{header|Slate}}==
 
In Slate, programs are represented as Syntax Node trees, with methods defined on the various syntactic types. The backtick syntax provides a convenient quoting mechanism, and as objects, they have convenient methods defined for evaluation or evaluation within a specific environment:
<langsyntaxhighlight lang="slate">`(4 + 5) evaluate.
`(4 + 5) evaluateIn: prototypes.</langsyntaxhighlight>
 
You can also explicitly invoke the Parser on a String, to convert it into syntactic objects:
<langsyntaxhighlight lang="slate">(Syntax Parser newOn: '4 + 5') upToEnd do: [| :each | print: each evaluate]</langsyntaxhighlight>
 
You can construct a program using externally-specified values using <tt>`unquote</tt> within a quoted expression:
<langsyntaxhighlight lang="slate">define: #x -> 4.
`(x `unquote + 5) evaluate.</langsyntaxhighlight>
 
Or you can obviously construct a string:
<langsyntaxhighlight lang="slate">define: #x -> 4.
(Syntax Parser newOn: x printString ; ' + 5')</langsyntaxhighlight>
 
The <tt>evaluate</tt> method also takes into consideration the current lexical scope, unless another environment is specified. The following returns 10, no matter what binding <tt>x</tt> has in the local namespace:
<langsyntaxhighlight lang="slate">define: #x -> 4.
[| x | x: 5. `(x `unquote + 5) evaluate] do.</langsyntaxhighlight>
 
Slate can sandbox via constructing a fresh namespace and evaluating within it, but this mechanism is not strongly secure yet.
 
=={{header|Slope}}==
You can create a list via quoted symbols and then evaluate:
<syntaxhighlight lang="slope">(eval (list '+ 1 2 3 4 5))</syntaxhighlight>
 
Or, you can evaluate a string as code:
<syntaxhighlight lang="slope">(eval "(+ 1 2 3 4 5)" #t)</syntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">[ 4 + 5 ] value.</langsyntaxhighlight>
Evaluating an expression without bindings:
<langsyntaxhighlight lang="smalltalk">e := ' 123 degreesToRadians sin '.
Transcript show: (Compiler evaluate: e) .</langsyntaxhighlight>
To get local bindings (x, y),
evaluate an expression which yields a block given as a string, then call the resulting block:
<langsyntaxhighlight lang="smalltalk">e := '[ :x :y | (x*x + (y*y)) sqrt ]'.
Transcript show: ((Compiler evaluate: e) value: 3 value: 4).</langsyntaxhighlight>
this could be wrapped into a utility, which expects the names to bind as argument, if required.
 
Line 1,597 ⟶ 1,904:
The built in function eval() evaluates SNOBOL4 expressions and returns the value. The expression is evaluated in the current environment and has access to then-current variables.
 
<langsyntaxhighlight lang="snobol4"> expression = "' page ' (i + 1)"
i = 7
output = eval(expression)
end</langsyntaxhighlight>
 
{{out}}
Line 1,610 ⟶ 1,917:
Programs of type CODE are executed by a variant of the goto clause:
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> compiled = code(' output = "Hello, world."') :s<compiled>
end</langsyntaxhighlight>
 
When passing programs to code(), semicolons are used to separate lines.
Line 1,618 ⟶ 1,925:
Likewise, the code compiled at runtime has access to not just variables, but also files, functions, etc., that are in the already-compiled program.
 
=={{Headerheader|Sparkling}}==
 
In Sparkling, the standard library provides functions to compile expressions and statements into functions. Each such function is considered a different top-level program, running in the execution context of it's "parent" program (i. e. the piece of code from within which it was created). Consequently, functions compiled at runtime share their environment (e. g. all globals) with their parent program.
Line 1,628 ⟶ 1,935:
===Evaluating expressions===
====Simple====
<langsyntaxhighlight lang="sparkling">let fn = exprtofn("13 + 37");
fn() // -> 50</langsyntaxhighlight>
 
====With arguments====
<langsyntaxhighlight lang="sparkling">let fn = exprtofn("#0 * #1");
fn(3, 4) // -> 12</langsyntaxhighlight>
 
===Evaluating statements===
<langsyntaxhighlight lang="sparkling">let fn = compile("for (var i = 0; i < 10; i++) { print(i); }");
fn(); // result: 0 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|Tcl}}==
===Simple Evaluation===
Evaluation in the current interpreter:
<langsyntaxhighlight lang="tcl">set four 4
set result1 [eval "expr {$four + 5}"] ;# string input
 
set result2 [eval [list expr [list $four + 5]]] ;# list input</langsyntaxhighlight>
 
===Evaluation in a restricted context===
Tcl handles sandboxing by creating new interpreters. Each interpreter is strongly isolated from all other interpreters except in that the interpreter that creates a sub-interpreter retains management control over that “slave” interpreter. The exact capabilities exposed in the slave are controlled by what commands exist in it; commands in the slave may be aliases for other commands in the master interpreter, which allows for trapping into a more highly authorized context (which can be considered analogous to a system call to an OS kernel).
<langsyntaxhighlight lang="tcl"># Create an interpreter with a default set of restrictions
interp create -safe restrictedContext
 
Line 1,669 ⟶ 1,976:
return "there are [doubleSecret] words in the secret: the magic number is [expr {4 + 5}]"
}]; # --> there are 2 words in the secret: the magic number is 9
puts $v; # --> secret secret</langsyntaxhighlight>
As can be seen, the result of the overall evaluation is the same as the result of the evaluation in the slave.
 
Line 1,678 ⟶ 1,985:
Even stronger protection of the master interpreter is available from Tcl 8.5 onwards through the setting of resource limits on the slaves.
These allow the master to prevent the evaluated script from going berserk:
<langsyntaxhighlight lang="tcl">set i [interp create]
interp limit $i commands -value [expr [$i eval info cmdcount]+20] -granularity 1
interp eval $i {
Line 1,685 ⟶ 1,992:
puts "Counting up... [incr x]"
}
}</langsyntaxhighlight>
{{out}} (the last line is an error message):
<pre>Counting up... 1
Line 1,706 ⟶ 2,013:
 
TODO: Is there a way to execute statements as well as evaluate expressions? [[Category:TI-89 BASIC examples needing attention]]
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule : {
str: "(textout \"eval output: \" (+ 1 1))",
 
_start: (λ
(eval str)
)
}</syntaxhighlight>
{{out}}
<pre>
eval output: 2
</pre>
 
=={{header|UNIX Shell}}==
<tt>eval</tt> is the command to use:
<langsyntaxhighlight lang="bash">$ a=42
$ b=a
$ eval "echo \$$b"
42</langsyntaxhighlight>
 
=={{header|Ursa}}==
The eval statement in Ursa takes a string and evaluates it as a command, redirecting the console to the specified I/O device.
<langsyntaxhighlight lang="ursa"># writes hello world to the console
eval "out \"hello world\" endl console" console
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
Firstly, Wren has a REPL which is started from the command line by running Wren-cli without any parameters.
 
Any valid Wren code can then be entered and immediately evaluated.
 
To quit the REPL just type Ctrl-C or Ctrl-D.
 
The examples in the Kotlin entry would look like this in the Wren REPL:
<pre>
$ wren-cli
\\/"-
\_/ wren v0.4.0
> 20 + 22
42
> 5 * 81.sqrt
45
> var triple = Fn.new { |x| x * 3 }
> triple.call(16)
48
>
</pre>
 
Secondly, Wren has the ''Meta.eval'' method which can be used from within a script to execute any valid Wren code (presented to it in string form) at runtime. The string could be constructed within the script, obtained from a file or input by the user. Here's a very simple example:
<syntaxhighlight lang="wren">import "meta" for Meta
 
var s = "for (i in 0..4) System.print(i)"
Meta.eval(s)</syntaxhighlight>
 
{{out}}
<pre>
0
1
2
3
4
</pre>
 
=={{header|zkl}}==
In zkl, the compiler is part of the language and compiling a chunk of code returns an executable (which how the REPL works), so <langsyntaxhighlight lang="zkl">Compiler.Compiler.compileText(
"fcn f(text){text.len()}").f("foobar")
//-->6</langsyntaxhighlight>
All language constructs are allowed, the only sand boxing is the new code can only touch global resources or items explicitly passed in ("foobar" in the example).
 
9,476

edits