forked from servo/rust-mozjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrust.rs
313 lines (269 loc) · 9.86 KB
/
rust.rs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#[doc = "Rust wrappers around the raw JS apis"];
use bg = jsapi::bindgen;
use libc::types::os::arch::c95::{size_t, c_uint};
use std::map::HashMap;
export rt;
export cx;
export jsobj;
export methods;
export compartment;
// ___________________________________________________________________________
// friendly Rustic API to runtimes
pub type rt = @rt_rsrc;
pub struct rt_rsrc {
ptr : *JSRuntime,
drop {
JS_Finish(self.ptr);
}
}
pub fn new_runtime(p : {ptr: *JSRuntime}) -> rt {
return @rt_rsrc {
ptr: p.ptr
}
}
impl rt {
fn cx() -> cx {
new_context({ ptr: JS_NewContext(self.ptr, default_stacksize as size_t),
rt: self})
}
}
pub fn rt() -> rt {
return new_runtime({ptr: JS_Init(default_heapsize)})
}
// ___________________________________________________________________________
// contexts
pub type cx = @cx_rsrc;
pub struct cx_rsrc {
ptr : *JSContext,
rt: rt,
classes: HashMap<~str, @JSClass>,
drop {
JS_DestroyContext(self.ptr);
}
}
pub fn new_context(rec : {ptr: *JSContext, rt: rt}) -> cx {
return @cx_rsrc {
ptr: rec.ptr,
rt: rec.rt,
classes: HashMap()
}
}
impl cx {
fn rooted_obj(obj: *JSObject) -> jsobj {
let jsobj = @jsobj_rsrc {cx: self, cxptr: self.ptr, ptr: obj};
JS_AddObjectRoot(self.ptr, ptr::to_unsafe_ptr(&jsobj.ptr));
jsobj
}
fn set_default_options_and_version() {
self.set_options(JSOPTION_VAROBJFIX | JSOPTION_METHODJIT |
JSOPTION_TYPE_INFERENCE);
self.set_version(JSVERSION_LATEST);
}
fn set_options(v: c_uint) {
JS_SetOptions(self.ptr, v);
}
fn set_version(v: i32) {
JS_SetVersion(self.ptr, v);
}
fn set_logging_error_reporter() {
JS_SetErrorReporter(self.ptr, reportError);
}
fn set_error_reporter(reportfn: *u8) {
JS_SetErrorReporter(self.ptr, reportfn);
}
fn new_compartment(globclsfn: fn(name_pool) -> JSClass) -> Result<compartment,()> {
let np = name_pool();
let globcls = @globclsfn(np);
let globobj = JS_NewGlobalObject(self.ptr, ptr::to_unsafe_ptr(&*globcls), null());
result(JS_InitStandardClasses(self.ptr, globobj)).chain(|_ok| {
let compartment = @{cx: self,
name_pool: np,
mut global_funcs: ~[],
mut global_props: ~[],
global_class: globcls,
global_obj: self.rooted_obj(globobj),
global_protos: HashMap()
};
self.set_cx_private(ptr::to_unsafe_ptr(&*compartment) as *());
Ok(compartment)
})
}
fn evaluate_script(glob: jsobj, bytes: ~[u8], filename: ~str, line_num: uint)
-> Result<(),()> {
vec::as_imm_buf(bytes, |bytes_ptr, bytes_len| {
str::as_c_str(filename, |filename_cstr| {
let bytes_ptr = bytes_ptr as *c_char;
let rval: jsval = JSVAL_NULL;
#debug["Evaluating script from %s with bytes %?", filename, bytes];
if JS_EvaluateScript(self.ptr, glob.ptr,
bytes_ptr, bytes_len as c_uint,
filename_cstr, line_num as c_uint,
ptr::to_unsafe_ptr(&rval)) == ERR {
#debug["...err!"];
Err(())
} else {
// we could return the script result but then we'd have
// to root it and so forth and, really, who cares?
#debug["...ok!"];
Ok(())
}
})
})
}
fn lookup_class_name(s: ~str) -> @JSClass {
option::expect(&self.classes.find(s),
#fmt("Class %s not found in class table", s))
}
unsafe fn get_cx_private() -> *() {
cast::reinterpret_cast(&JS_GetContextPrivate(self.ptr))
}
unsafe fn set_cx_private(data: *()) {
JS_SetContextPrivate(self.ptr, cast::reinterpret_cast(&data));
}
unsafe fn get_obj_private(obj: *JSObject) -> *() {
cast::reinterpret_cast(&JS_GetPrivate(obj))
}
unsafe fn set_obj_private(obj: *JSObject, data: *()) {
JS_SetPrivate(obj, cast::reinterpret_cast(&data));
}
}
pub extern fn reportError(_cx: *JSContext, msg: *c_char, report: *JSErrorReport) {
unsafe {
let fnptr = (*report).filename;
let fname = if fnptr.is_not_null() {from_c_str(fnptr)} else {~"none"};
let lineno = (*report).lineno;
let msg = from_c_str(msg);
#error["Error at %s:%?: %s\n", fname, lineno, msg];
}
}
// ___________________________________________________________________________
// compartment
pub type bare_compartment = {
cx: cx,
name_pool: name_pool,
mut global_funcs: ~[@~[JSFunctionSpec]],
mut global_props: ~[@~[JSPropertySpec]],
global_class: @JSClass,
global_obj: jsobj,
global_protos: HashMap<~str, jsobj>
};
pub trait methods {
fn define_functions(specfn: fn(name_pool) -> ~[JSFunctionSpec]) -> Result<(),()>;
fn define_properties(specfn: fn() -> ~[JSPropertySpec]) -> Result<(),()>;
fn define_property(name: ~str, value: jsval, getter: JSPropertyOp,
setter: JSStrictPropertyOp, attrs: c_uint) -> Result<(),()>;
fn new_object(class_name: ~str, proto: *JSObject, parent: *JSObject) -> Result<jsobj, ()>;
fn new_object_with_proto(class_name: ~str, proto_name: ~str, parent: *JSObject)
-> Result<jsobj, ()>;
fn register_class(class_fn: fn(bare_compartment) -> JSClass);
fn get_global_proto(name: ~str) -> jsobj;
fn stash_global_proto(name: ~str, proto: jsobj);
fn add_name(name: ~str) -> *c_char;
}
pub type compartment = @bare_compartment;
impl bare_compartment : methods {
fn define_functions(specfn: fn(name_pool) -> ~[JSFunctionSpec]) -> Result<(),()> {
let specvec = @specfn(self.name_pool);
vec::push(&mut self.global_funcs, specvec);
vec::as_imm_buf(*specvec, |specs, _len| {
result(JS_DefineFunctions(self.cx.ptr, self.global_obj.ptr, specs))
})
}
fn define_properties(specfn: fn() -> ~[JSPropertySpec]) -> Result<(),()> {
let specvec = @specfn();
vec::push(&mut self.global_props, specvec);
vec::as_imm_buf(*specvec, |specs, _len| {
result(JS_DefineProperties(self.cx.ptr, self.global_obj.ptr, specs))
})
}
fn define_property(name: ~str, value: jsval, getter: JSPropertyOp, setter: JSStrictPropertyOp,
attrs: c_uint)
-> Result<(),()> {
result(JS_DefineProperty(self.cx.ptr, self.global_obj.ptr, self.add_name(name),
value, getter, setter, attrs))
}
fn new_object(class_name: ~str, proto: *JSObject, parent: *JSObject)
-> Result<jsobj, ()> {
let classptr = self.cx.lookup_class_name(class_name);
let obj = self.cx.rooted_obj(JS_NewObject(self.cx.ptr, ptr::to_unsafe_ptr(&*classptr),
proto, parent));
result_obj(obj)
}
fn new_object_with_proto(class_name: ~str, proto_name: ~str, parent: *JSObject)
-> Result<jsobj, ()> {
let classptr = self.cx.lookup_class_name(class_name);
let proto = option::expect(&self.global_protos.find(proto_name),
#fmt("new_object_with_proto: expected to find %s in the proto \
table", proto_name));
let obj = self.cx.rooted_obj(JS_NewObject(self.cx.ptr, ptr::to_unsafe_ptr(&*classptr),
proto.ptr, parent));
result_obj(obj)
}
fn get_global_proto(name: ~str) -> jsobj {
self.global_protos.get(name)
}
fn stash_global_proto(name: ~str, proto: jsobj) {
if !self.global_protos.insert(name, proto) {
fail ~"Duplicate global prototype registered; you're gonna have a bad time."
}
}
fn register_class(class_fn: fn(bare_compartment) -> JSClass) {
let classptr = @class_fn(self);
if !self.cx.classes.insert(
unsafe { str::raw::from_c_str(classptr.name) },
classptr) {
fail ~"Duplicate JSClass registered; you're gonna have a bad time."
}
}
fn add_name(name: ~str) -> *c_char {
self.name_pool.add(copy name)
}
}
// ___________________________________________________________________________
// objects
pub type jsobj = @jsobj_rsrc;
pub struct jsobj_rsrc {
cx : cx,
cxptr : *JSContext,
ptr : *JSObject,
drop {
JS_RemoveObjectRoot(self.cxptr, ptr::to_unsafe_ptr(&self.ptr));
}
}
impl jsobj_rsrc {
fn new_object(rec : {cx: cx, cxptr: *JSContext, ptr: *JSObject}) -> jsobj {
return @jsobj_rsrc {
cx: rec.cx,
cxptr: rec.cxptr,
ptr: rec.ptr
}
}
}
// ___________________________________________________________________________
// random utilities
pub trait to_jsstr {
fn to_jsstr(cx: cx) -> *JSString;
}
impl ~str : to_jsstr {
fn to_jsstr(cx: cx) -> *JSString {
str::as_buf(self, |buf, len| {
let cbuf = unsafe { cast::reinterpret_cast(&buf) };
bg::JS_NewStringCopyN(cx.ptr, cbuf, len as size_t)
})
}
}
#[cfg(test)]
pub mod test {
#[test]
pub fn dummy() {
let rt = rt();
let cx = rt.cx();
cx.set_default_options_and_version();
cx.set_logging_error_reporter();
cx.new_compartment(global::global_class).chain(|comp| {
comp.define_functions(global::debug_fns);
let bytes = str::to_bytes(~"debug(22);");
cx.evaluate_script(comp.global_obj, bytes, ~"test", 1u)
});
}
}