tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,5 @@
Demonstrate your language's ability for programs to execute code written in the language provided at runtime. Show us what kind of program fragments are permitted (e.g. expressions vs. statements), how you get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].

View file

@ -0,0 +1 @@
print(evaluate("4.0*arctan(1.0)"))

View file

@ -0,0 +1,32 @@
; requires AutoHotkey_H or AutoHotkey.dll
msgbox % eval("3 + 4")
msgbox % eval("4 + 4")
return
eval(expression)
{
global script
script =
(
expression(){
return %expression%
}
)
renameFunction("expression", "") ; remove any previous expressions
gosub load ; cannot use addScript inside a function yet
exp := "expression"
return %exp%()
}
load:
DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt")
return
renameFunction(funcName, newname){
static
x%newname% := newname ; store newname in a static variable so its memory is not freed
strput(newname, &x%newname%, strlen(newname) + 1)
if fnp := FindFunc(funcName)
numput(&x%newname%, fnp+0, 0, "uint")
}

View file

@ -0,0 +1,2 @@
10 REM load the next program
20 LOAD "PROG2"

View file

@ -0,0 +1,2 @@
expr$ = "PI^2 + 1"
PRINT EVAL(expr$)

View file

@ -0,0 +1,16 @@
exec$ = "PRINT ""Hello world!"""
bbc$ = FNtokenise(exec$)
tmpfile$ = @tmp$+"temp.bbc"
tmpfile% = OPENOUT(tmpfile$)
BPUT#tmpfile%, bbc$+CHR$0
CLOSE #tmpfile%
CALL tmpfile$
END
DEF FNtokenise(A$)
LOCAL A%
A% = EVAL("0:"+A$)
A$ = $(!332+2)
= CHR$(LENA$+4) + CHR$0 + CHR$0 + A$ + CHR$13

View file

@ -0,0 +1,2 @@
blsq ) {5 5 .+}e!
10

View file

@ -0,0 +1,4 @@
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}

View file

@ -0,0 +1,2 @@
blsq ) 1 10r@"5.+"psm[
{6 7 8 9 10 11 12 13 14 15}

View file

@ -0,0 +1,2 @@
blsq ) "[m}+.5{@r01 1"<-pe
{6 7 8 9 10 11 12 13 14 15}

View file

@ -0,0 +1,2 @@
blsq ) {3 2}(?*)[+e!
6

View file

@ -0,0 +1,8 @@
blsq ) ?+
ERROR: Burlesque: (.+) Invalid arguments!
blsq ) ?+to
"Error"
blsq ) (?+)
?+
blsq ) (?+)to
"Ident"

View file

@ -0,0 +1 @@
(eval '(+ 4 5)) ; returns 9

View file

@ -0,0 +1,2 @@
(defun add-four-complicated (a-number)
(eval `(+ 4 ',a-number)))

View file

@ -0,0 +1,2 @@
(defun add-four-by-function (a-number)
(funcall (eval '(lambda (n) (+ 4 n)))) a-number)

View file

@ -0,0 +1 @@
(eval (read-from-string "(+ 4 5)"))

View file

@ -0,0 +1,3 @@
(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))))

View file

@ -0,0 +1,2 @@
(let ((x 11) (y 22))
(format t "~%x + y = ~a" (eval `(+ ,x ,y))))

View file

@ -0,0 +1 @@
(system:run-shell-command ...)

View file

@ -0,0 +1 @@
(find-symbol "FOO" "BAR")

View file

@ -0,0 +1,2 @@
? e`1 + 1`.eval(safeScope)
# value: 2

View file

@ -0,0 +1,5 @@
? def [value, env] := e`def x := 1 + 1`.evalToPair(safeScope)
# value: [2, ...]
? e`x`.eval(env)
# value: 2

View file

@ -0,0 +1,5 @@
? def prog := <elang:syntax.makeEParser>.run("1 + 1")
# value: e`1.add(1)`
? prog.eval(safeScope)
# value: 2

View file

@ -0,0 +1,8 @@
1> {ok, Tokens, _} = erl_scan:string("X + 4 * lists:sum([1,2,3,4]).").
...
2> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
...
3> Bindings = erl_eval:add_binding('X', 17, erl_eval:new_bindings()).
[{'X',17}]
4> {value, Value, _} = erl_eval:expr(Form, Bindings).
{value,57,[{'X',17}]}

View file

@ -0,0 +1,4 @@
s" variable foo 1e fatan 4e f*" evaluate
f. \ 3.14159...
1 foo !

View file

@ -0,0 +1,10 @@
unused . \ show how much dictionary space is available
marker restore
create foo 30 allot
: my-def 30 0 do cr i . ." test" loop ;
unused . \ lower than before
restore
unused . \ same as first unused; restore, foo, and my-def no longer defined

View file

@ -0,0 +1,10 @@
10 LINE INPUT "Type an expression: ",A$
20 OPEN "CHAIN.TMP" FOR OUTPUT AS #1
30 PRINT #1, "70 LET Y=("+A$+")"
40 CLOSE #1
50 CHAIN MERGE "CHAIN.TMP",60,ALL
60 FOR X=0 TO 5
70 REM
80 PRINT X,Y
90 NEXT X
100 GOTO 10

View file

@ -0,0 +1,25 @@
package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val) //prints, well, 3
}

View file

@ -0,0 +1,7 @@
def years1 = new GroovyShell().evaluate('''
(2008..2121).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')
println years1

View file

@ -0,0 +1,9 @@
def startYear = 2008
def endYear = 2121
def years2 = new GroovyShell().evaluate("""
(${startYear}..${endYear}).findAll {
Date.parse("yyyy-MM-dd", "\${it}-12-25").format("EEE") == "Sun"
}
""")
println years2

View file

@ -0,0 +1,8 @@
def context = new B inding()
context.startYear = 2008
context.endYear = 2121
def years3 = new GroovyShell(context).evaluate('''
(startYear..endYear).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')

View file

@ -0,0 +1,7 @@
def years4 = new GroovyShell( new B inding(startYear: 2008, endYear: 2121) ).evaluate('''
(startYear..endYear).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')
println years4

View file

@ -0,0 +1,8 @@
def binding = new B inding(startYear: 2008, endYear: 2121)
new GroovyShell( binding ).evaluate('''
yearList = (startYear..endYear).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')
println binding.yearList

View file

@ -0,0 +1,7 @@
def years5 = Eval.xy(2008, 2121, '''
(x..y).findAll {
Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun"
}
''')
println years5

View file

@ -0,0 +1,8 @@
value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6
! temp is undefined outside XEQ, if it was not defined before.
XEQ(" WRITE(Messagebox) 'Hello World !' ")
OPEN(FIle="my_file.txt")
READ(FIle="my_file.txt", Row=6) string
XEQ( string ) ! executes row 6 of my_file.txt

View file

@ -0,0 +1 @@
". 'a =: +/ 1 2 3' NB. execute a string to sum 1, 2 and 3 and assign to noun a

View file

@ -0,0 +1 @@
monad :'+/y' 1 2 3

View file

@ -0,0 +1,5 @@
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');
typeof foo; // 'object'
typeof bar; // 'string'

View file

@ -0,0 +1,20 @@
'Dimension a numerical and string array
Dim myArray(5)
Dim myStringArray$(5)
'Fill both arrays with the appropriate data
For i = 0 To 5
myArray(i) = i
myStringArray$(i) = "String - " + str$(i)
Next i
'Set two variables with the names of each array
numArrayName$ = "myArray"
strArrayName$ = "myStringArray"
'Retrieve the array data by evaluating a string
'that correlates to the array
For i = 0 To 5
Print Eval$(numArrayName$ + "(" + str$(i) + ")")
Print Eval$(strArrayName$ + "$(" + str$(i) + ")")
Next i

View file

@ -0,0 +1,14 @@
Struct myStruct, value As long, _
string As ptr
myStruct.value.struct = 10
myStruct.string.struct = "Hello World!"
structName$ = "myStruct"
numElement$ = "value"
strElement$ = "string"
Print Eval$(structName$ + "." + numElement$ + "." + "struct")
'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"))

View file

@ -0,0 +1,5 @@
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

View file

@ -0,0 +1,17 @@
/* 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. */
kill(f)$
eval_string("block(f(x) := x^2 + 1, f(2))");
5
fundef(f);
/* f(x) := x^2 + 1 */
eval_string("block([f], local(f), f(x) := x^3 + 1, f(2))");
9
fundef(f);
/* f(x) := x^2 + 1 */

View file

@ -0,0 +1,50 @@
function ExecSeries(string s,double b,e,i) as string
'===================================================
'
sys a,p
string v,u,tab,cr,er
'
'PREPARE OUTPUT BUFFER
'
p=1
cr=chr(13) chr(10)
tab=chr(9)
v=nuls 4096
mid v,p,s+cr+cr
p+=4+len s
'
double x,y,z 'shared variables
'
'COMPILE
'
a=compile s
er=error
if er then
print "runtime error: " er : exit function
end if
'
'EXECUTE
'
for x=b to e step i
if p+128>=len v then
v+=nuls len(v) 'extend buffer
end if
call a
u=str(x) tab str(y) cr
mid v,p,u : p+=len u
next
'
freememory a 'release compiled code
'
return left v,p-1 'results
'
end function
'=====
'TESTS
'=====
'Expression, StartVal, EndVal stepVal, Increment
print ExecSeries "y=x*x*x", 1, 10, 1
print ExecSeries "y=sqrt x",1, 9 , 1

View file

@ -0,0 +1,17 @@
declare
%% simplest case: just evaluate expressions without bindings
R1 = {Compiler.virtualStringToValue "{Abs ~42}"}
{Show R1}
%% eval expressions with additional bindings and
%% the possibility to kill the evaluation by calling KillProc
KillProc
R2 = {Compiler.evalExpression "{Abs A}" unit('A':~42) ?KillProc}
{Show R2}
%% full control: add and remove bindings, eval expressions or
%% statements, set compiler switches etc.
Engine = {New Compiler.engine init}
{Engine enqueue(setSwitch(expression false))} %% statements instead of expr.
{Engine enqueue(mergeEnv(env('A':42 'System':System)))}
{Engine enqueue(feedVirtualString("{System.show A}"))}

View file

@ -0,0 +1,5 @@
<?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);

View file

@ -0,0 +1,2 @@
my ($a, $b) = (-5, 7);
my $ans = eval 'abs($a * $b)'; # => 35

View file

@ -0,0 +1,2 @@
my ($a, $b) = (-5, 7);
$ans = eval 'abs($a * $b)'; # => 35

View file

@ -0,0 +1,9 @@
program demo = compile_string(#"
string name=\"demo\";
string hello()
{
return(\"hello, i am \"+name);
}");
demo()->hello();
Result: "hello, i am demo"

View file

@ -0,0 +1,5 @@
>>> exec '''
x = sum([1,2,3,4])
print x
'''
10

View file

@ -0,0 +1,5 @@
>>> exec('''
x = sum([1,2,3,4])
print(x)
''')
10

View file

@ -0,0 +1,3 @@
expr1 <- quote(a+b*c)
expr2 <- parse(text="a+b*c")[[1]]
expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))

View file

@ -0,0 +1,3 @@
> a <- 1; b <- 2; c <- 3
> eval(expr1)
[1] 7

View file

@ -0,0 +1,11 @@
> env <- as.environment(list(a=1, b=3, c=2))
> evalq(a, env)
[1] 1
> eval(expr1, env) #this fails; env has only emptyenv() as a parent so can't find "+"
Error in eval(expr, envir, enclos) : could not find function "+"
> parent.env(env) <- sys.frame()
> eval(expr1, env) # eval in env, enclosed in the current context
[1] 7
> assign("b", 5, env) # assign() can assign into environments
> eval(expr1, env)
[1] 11

View file

@ -0,0 +1,22 @@
/*REXX program to illustrate ability to execute code written at runtime.*/
numeric digits 10000000
bee=51
stuff='bee=min(-2,44); say 13*2 "[from inside the box."; abc=abs(bee)'
interpret stuff
say 'bee=' bee
say 'abc=' abc
say
say 'enter an expression:'
pull expression
say
say 'expression entered is:' expression
interpret '?='expression
say
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 done.*/

View file

@ -0,0 +1,2 @@
a, b = 5, -7
ans = eval "(a * b).abs" # => 35

View file

@ -0,0 +1,18 @@
def first(main_var, main_binding)
foo = 42
second [[main_var, main_binding], ["foo", binding]]
end
def second(args)
sqr = lambda {|x| x**2}
deref(args << ["sqr", binding])
end
def deref(stuff)
stuff.each do |varname, context|
puts "value of #{varname} is #{eval varname, context}"
end
end
hello = "world"
first "hello", binding

View file

@ -0,0 +1,4 @@
expression = "' page ' (i + 1)"
i = 7
output = eval(expression)
end

View file

@ -0,0 +1,2 @@
compiled = code(' output = "Hello, world."') :s<compiled>
end

View file

@ -0,0 +1,12 @@
> (define x 37)
> (eval '(+ x 5))
42
> (eval '(+ x 5) (interaction-environment))
42
> (eval '(+ x 5) (scheme-report-environment 5)) ;; provides R5RS definitions
Error: identifier not visible x.
Type (debug) to enter the debugger.
> (display (eval (read)))
(+ 4 5) ;; this is input from the user.
9

View file

@ -0,0 +1,2 @@
`(4 + 5) evaluate.
`(4 + 5) evaluateIn: prototypes.

View file

@ -0,0 +1 @@
(Syntax Parser newOn: '4 + 5') upToEnd do: [| :each | print: each evaluate]

View file

@ -0,0 +1,2 @@
define: #x -> 4.
`(x `unquote + 5) evaluate.

View file

@ -0,0 +1,2 @@
define: #x -> 4.
(Syntax Parser newOn: x printString ; ' + 5')

View file

@ -0,0 +1,2 @@
define: #x -> 4.
[| x | x: 5. `(x `unquote + 5) evaluate] do.

View file

@ -0,0 +1 @@
[ 4 + 5 ] value.

View file

@ -0,0 +1,2 @@
e := ' 123 degreesToRadians sin '.
Transcript show: (Compiler evaluate: e) .

View file

@ -0,0 +1,2 @@
e := '[ :x :y | (x*x + (y*y)) sqrt ]'.
Transcript show: ((Compiler evaluate: e) value: 3 value: 4).

View file

@ -0,0 +1,4 @@
set four 4
set result1 [eval "expr {$four + 5}"] ;# string input
set result2 [eval [list expr [list $four + 5]]] ;# list input

View file

@ -0,0 +1,21 @@
# Create an interpreter with a default set of restrictions
interp create -safe restrictedContext
# Our secret variable
set v "secret"
# Allow some guarded access to the secret from the restricted context.
interp alias restrictedContext doubleSecret {} example
proc example {} {
global v
lappend v $v
return [llength $v]
}
# Evaluate a script in the restricted context
puts [restrictedContext eval {
append v " has been leaked"
catch {file delete yourCriticalFile.txt} ;# Will be denied!
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

View file

@ -0,0 +1,8 @@
set i [interp create]
interp limit $i commands -value [expr [$i eval info cmdcount]+20] -granularity 1
interp eval $i {
set x 0
while {1} { # Infinite loop! Bwahahahaha!
puts "Counting up... [incr x]"
}
}