forked from MacRuby/MacRuby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript.rb
More file actions
executable file
·68 lines (55 loc) · 1.62 KB
/
Copy pathjavascript.rb
File metadata and controls
executable file
·68 lines (55 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/local/bin/macruby
# -*- coding: utf-8 -*-
framework "JavaScriptCore"
module JSC
module_function
def eval(program)
kJSPropertyAttributeNone = 0 unless(kJSPropertyAttributeNone)
callback = Proc.new do |ctx, obj, this, len, args, exp|
if(len > 0)
tmp = args.cast!('^{OpaqueJSValue=}')
string = JSValueToStringCopy(ctx, tmp[0], exp)
size = JSStringGetMaximumUTF8CStringSize(string)
buffer = Pointer.new('c', size)
ret = JSStringGetUTF8CString(string, buffer, size)
JSStringRelease(string)
ary = []
(ret - 1).times { |i| ary << buffer[i] }
puts ary.pack('c*')
end
nil
end
ctx = JSGlobalContextCreate(nil)
global = JSContextGetGlobalObject(ctx)
print = JSStringCreateWithUTF8CString("print")
print_f = JSObjectMakeFunctionWithCallback(ctx, print, callback)
JSObjectSetProperty(ctx, global, print, print_f, kJSPropertyAttributeNone, nil)
JSStringRelease(print)
source = JSStringCreateWithUTF8CString(program)
exception = Pointer.new('^{OpaqueJSValue}')
if(JSCheckScriptSyntax(ctx, source, nil, 0, exception))
JSEvaluateScript(ctx, source, nil, nil, 0, exception)
else
raise "Syntax error."
end
JSStringRelease(source)
JSGlobalContextRelease(ctx)
end
end
if($0 == __FILE__)
program =<<EOS
var sum = 0;
for(var i = 1; i <= 10; i++) {
sum += i;
}
print("sum : " + sum);
function fib(n) {
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
var ret = fib(7);
print("fib(7) : " + ret);
EOS
JSC.eval(program)
end