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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::PrototypeList;
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
use dom::bindings::node;
use dom::node::{AbstractNode, ScriptView};
use script_task::page_from_context;
use std::cast;
use std::hashmap::HashMap;
use std::libc;
use std::ptr;
use std::ptr::{null, to_unsafe_ptr};
use std::result;
use std::str;
use std::uint;
use std::unstable::intrinsics;
use js::glue::*;
use js::glue::{DefineFunctionWithReserved, GetObjectJSClass, RUST_OBJECT_TO_JSVAL};
use js::glue::{js_IsObjectProxyClass, js_IsFunctionProxyClass, IsProxyHandlerFamily};
use js::glue::{PROPERTY_STUB, STRICT_PROPERTY_STUB, ENUMERATE_STUB, CONVERT_STUB, RESOLVE_STUB};
use js::jsapi::{JS_AlreadyHasOwnProperty, JS_NewObject, JS_NewFunction, JS_GetGlobalObject};
use js::jsapi::{JS_DefineProperties, JS_WrapValue, JS_ForwardGetPropertyTo};
use js::jsapi::{JS_EncodeString, JS_free, JS_GetStringCharsAndLength};
use js::jsapi::{JS_GetClass, JS_LinkConstructorAndPrototype};
use js::jsapi::{JS_GetFunctionPrototype, JS_InternString, JS_GetFunctionObject};
use js::jsapi::{JS_HasPropertyById, JS_GetPrototype, JS_GetGlobalForObject};
use js::jsapi::{JS_NewStringCopyN, JS_DefineFunctions, JS_DefineProperty};
use js::jsapi::{JS_ValueToString, JS_GetReservedSlot, JS_SetReservedSlot};
use js::jsapi::{JSContext, JSObject, JSBool, jsid, JSClass, JSNative};
use js::jsapi::{JSFunctionSpec, JSPropertySpec, JSVal, JSPropertyDescriptor};
use js::jsfriendapi::bindgen::JS_NewObjectWithUniqueType;
use js::rust::Compartment;
use js::{JSCLASS_HAS_RESERVED_SLOTS, JSPROP_ENUMERATE, JSVAL_NULL};
use js::{JSPROP_PERMANENT, JSID_VOID, JSPROP_NATIVE_ACCESSORS, JSPROP_GETTER};
use js::{JSPROP_SETTER, JSVAL_VOID, JSVAL_TRUE, JSVAL_FALSE};
use js::{JS_THIS_OBJECT, JSFUN_CONSTRUCTOR, JS_CALLEE, JSPROP_READONLY};
use js;
static TOSTRING_CLASS_RESERVED_SLOT: u64 = 0;
static TOSTRING_NAME_RESERVED_SLOT: u64 = 1;
struct GlobalStaticData {
proxy_handlers: HashMap<uint, *libc::c_void>,
attribute_ids: HashMap<uint, ~[jsid]>,
method_ids: HashMap<uint, ~[jsid]>,
constant_ids: HashMap<uint, ~[jsid]>
}
pub fn GlobalStaticData() -> GlobalStaticData {
GlobalStaticData {
proxy_handlers: HashMap::new(),
attribute_ids: HashMap::new(),
method_ids: HashMap::new(),
constant_ids: HashMap::new()
}
}
extern fn InterfaceObjectToString(cx: *JSContext, _argc: uint, vp: *mut JSVal) -> JSBool {
unsafe {
let callee = RUST_JSVAL_TO_OBJECT(*JS_CALLEE(cx, cast::transmute(&vp)));
let obj = JS_THIS_OBJECT(cx, cast::transmute(&vp));
if obj.is_null() {
//XXXjdm figure out JSMSG madness
/*JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO,
"null", "object");*/
return 0;
}
let v = GetFunctionNativeReserved(callee, TOSTRING_CLASS_RESERVED_SLOT);
let clasp: *JSClass = cast::transmute(RUST_JSVAL_TO_PRIVATE(*v));
let v = GetFunctionNativeReserved(callee, TOSTRING_NAME_RESERVED_SLOT);
if GetObjectJSClass(obj) != clasp {
/*let jsname: *JSString = RUST_JSVAL_TO_STRING(*v);
let length = 0;
let name = JS_GetInternedStringCharsAndLength(jsname, &length);*/
//XXXjdm figure out JSMSG madness
/*JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_PROTO,
NS_ConvertUTF16toUTF8(name).get(), "toString",
"object");*/
return 0;
}
let name = jsval_to_str(cx, *v).get();
let retval = str(~"function " + name + "() {\n [native code]\n}");
*vp = domstring_to_jsval(cx, &retval);
return 1;
}
}
#[deriving(Clone)]
pub enum DOMString {
str(~str),
null_string
}
impl DOMString {
pub fn to_str(&self) -> ~str {
match *self {
str(ref s) => s.clone(),
null_string => ~""
}
}
pub fn get_ref<'a>(&'a self) -> &'a str {
match *self {
str(ref s) => s.as_slice(),
null_string => &'a "",
}
}
}
pub struct rust_box<T> {
rc: uint,
td: *intrinsics::TyDesc,
next: *(),
prev: *(),
payload: T
}
fn is_dom_class(clasp: *JSClass) -> bool {
unsafe {
((*clasp).flags & js::JSCLASS_IS_DOMJSCLASS) != 0
}
}
pub fn is_dom_proxy(obj: *JSObject) -> bool {
unsafe {
(js_IsObjectProxyClass(obj) || js_IsFunctionProxyClass(obj)) &&
IsProxyHandlerFamily(obj)
}
}
pub unsafe fn unwrap<T>(obj: *JSObject) -> T {
let clasp = JS_GetClass(obj);
let slot = if is_dom_class(clasp) {
DOM_OBJECT_SLOT
} else {
assert!(is_dom_proxy(obj));
DOM_PROXY_OBJECT_SLOT
} as u32;
let val = JS_GetReservedSlot(obj, slot);
cast::transmute(RUST_JSVAL_TO_PRIVATE(val))
}
pub unsafe fn get_dom_class(obj: *JSObject) -> Result<DOMClass, ()> {
let clasp = JS_GetClass(obj);
if is_dom_class(clasp) {
debug!("plain old dom object");
let domjsclass: *DOMJSClass = cast::transmute(clasp);
return Ok((*domjsclass).dom_class);
}
if is_dom_proxy(obj) {
debug!("proxy dom object");
let dom_class: *DOMClass = cast::transmute(GetProxyHandlerExtra(obj));
return Ok(*dom_class);
}
debug!("not a dom object");
return Err(());
}
pub fn unwrap_object<T>(obj: *JSObject, proto_id: PrototypeList::id::ID, proto_depth: uint) -> Result<T, ()> {
unsafe {
do get_dom_class(obj).chain |dom_class| {
if dom_class.interface_chain[proto_depth] == proto_id {
debug!("good prototype");
Ok(unwrap(obj))
} else {
debug!("bad prototype");
Err(())
}
}
}
}
pub fn unwrap_value<T>(val: *JSVal, proto_id: PrototypeList::id::ID, proto_depth: uint) -> Result<T, ()> {
unsafe {
let obj = RUST_JSVAL_TO_OBJECT(*val);
unwrap_object(obj, proto_id, proto_depth)
}
}
pub unsafe fn squirrel_away<T>(x: @mut T) -> *rust_box<T> {
let y: *rust_box<T> = cast::transmute(x);
cast::forget(x);
y
}
//XXX very incomplete
pub fn jsval_to_str(cx: *JSContext, v: JSVal) -> Result<~str, ()> {
unsafe {
let jsstr;
if RUST_JSVAL_IS_STRING(v) == 1 {
jsstr = RUST_JSVAL_TO_STRING(v)
} else {
jsstr = JS_ValueToString(cx, v);
if jsstr.is_null() {
return Err(());
}
}
let strbuf = JS_EncodeString(cx, jsstr);
let buf = str::raw::from_buf(strbuf as *u8);
JS_free(cx, strbuf as *libc::c_void);
Ok(buf)
}
}
pub unsafe fn domstring_to_jsval(cx: *JSContext, string: &DOMString) -> JSVal {
match string {
&null_string => {
JSVAL_NULL
}
&str(ref s) => {
str::as_buf(*s, |buf, len| {
let cbuf = cast::transmute(buf);
RUST_STRING_TO_JSVAL(JS_NewStringCopyN(cx, cbuf, len as libc::size_t))
})
}
}
}
pub fn get_compartment(cx: *JSContext) -> @mut Compartment {
unsafe {
let page = page_from_context(cx);
let compartment = (*page).js_info.get_ref().js_compartment;
assert!(cx == compartment.cx.ptr);
compartment
}
}
extern fn has_instance(_cx: *JSContext, obj: **JSObject, v: *JSVal, bp: *mut JSBool) -> JSBool {
//XXXjdm this is totally broken for non-object values
unsafe {
let mut o = RUST_JSVAL_TO_OBJECT(*v);
let obj = *obj;
*bp = 0;
while o.is_not_null() {
if o == obj {
*bp = 1;
break;
}
o = JS_GetPrototype(o);
}
return 1;
}
}
pub fn prototype_jsclass(name: ~str) -> @fn(compartment: @mut Compartment) -> JSClass {
let f: @fn(@mut Compartment) -> JSClass = |compartment: @mut Compartment| {
unsafe {
JSClass {
name: compartment.add_name(name.to_owned()),
flags: 0,
addProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
delProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
getProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
setProperty: GetJSClassHookStubPointer(STRICT_PROPERTY_STUB) as *u8,
enumerate: GetJSClassHookStubPointer(ENUMERATE_STUB) as *u8,
resolve: GetJSClassHookStubPointer(RESOLVE_STUB) as *u8,
convert: GetJSClassHookStubPointer(CONVERT_STUB) as *u8,
finalize: null(),
checkAccess: null(),
call: null(),
hasInstance: has_instance,
construct: null(),
trace: null(),
reserved: (null(), null(), null(), null(), null(), // 05
null(), null(), null(), null(), null(), // 10
null(), null(), null(), null(), null(), // 15
null(), null(), null(), null(), null(), // 20
null(), null(), null(), null(), null(), // 25
null(), null(), null(), null(), null(), // 30
null(), null(), null(), null(), null(), // 35
null(), null(), null(), null(), null()) // 40
}
}
};
return f;
}
pub fn instance_jsclass(name: ~str, finalize: *u8, trace: *u8)
-> @fn(compartment: @mut Compartment) -> JSClass {
let f: @fn(@mut Compartment) -> JSClass = |compartment: @mut Compartment| {
unsafe {
JSClass {
name: compartment.add_name(name.to_owned()),
flags: JSCLASS_HAS_RESERVED_SLOTS(1) | js::JSCLASS_IS_DOMJSCLASS,
addProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
delProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
getProperty: GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
setProperty: GetJSClassHookStubPointer(STRICT_PROPERTY_STUB) as *u8,
enumerate: GetJSClassHookStubPointer(ENUMERATE_STUB) as *u8,
resolve: GetJSClassHookStubPointer(RESOLVE_STUB) as *u8,
convert: GetJSClassHookStubPointer(CONVERT_STUB) as *u8,
finalize: finalize,
checkAccess: null(),
call: null(),
hasInstance: has_instance,
construct: null(),
trace: trace,
reserved: (null(), null(), null(), null(), null(), // 05
null(), null(), null(), null(), null(), // 10
null(), null(), null(), null(), null(), // 15
null(), null(), null(), null(), null(), // 20
null(), null(), null(), null(), null(), // 25
null(), null(), null(), null(), null(), // 30
null(), null(), null(), null(), null(), // 35
null(), null(), null(), null(), null()) // 40
}
}
};
return f;
}
pub fn define_empty_prototype(name: ~str, proto: Option<~str>, compartment: @mut Compartment)
-> js::rust::jsobj {
compartment.register_class(prototype_jsclass(name.to_owned()));
//TODO error checking
let obj = result::unwrap(
match proto {
Some(s) => compartment.new_object_with_proto(name.to_owned(),
s,
compartment.global_obj.ptr),
None => compartment.new_object(name.to_owned(), null(), compartment.global_obj.ptr)
});
unsafe {
compartment.define_property(name.to_owned(), RUST_OBJECT_TO_JSVAL(obj.ptr),
GetJSClassHookStubPointer(PROPERTY_STUB) as *u8,
GetJSClassHookStubPointer(STRICT_PROPERTY_STUB) as *u8,
JSPROP_ENUMERATE);
compartment.stash_global_proto(name, obj);
return obj;
}
}
// We use slot 0 for holding the raw object. This is safe for both
// globals and non-globals.
pub static DOM_OBJECT_SLOT: uint = 0;
static DOM_PROXY_OBJECT_SLOT: uint = js::JSSLOT_PROXY_PRIVATE as uint;
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
static DOM_PROTO_INSTANCE_CLASS_SLOT: u32 = 0;
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub static DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
// NOTE: This is baked into the Ion JIT as 0 in codegen for LGetDOMProperty and
// LSetDOMProperty. Those constants need to be changed accordingly if this value
// changes.
static JSCLASS_DOM_GLOBAL: u32 = js::JSCLASS_USERBIT1;
pub struct NativeProperties {
staticMethods: *JSFunctionSpec,
staticMethodIds: *jsid,
staticMethodsSpecs: *JSFunctionSpec,
staticAttributes: *JSPropertySpec,
staticAttributeIds: *jsid,
staticAttributeSpecs: *JSPropertySpec,
methods: *JSFunctionSpec,
methodIds: *jsid,
methodsSpecs: *JSFunctionSpec,
attributes: *JSPropertySpec,
attributeIds: *jsid,
attributeSpecs: *JSPropertySpec,
unforgeableAttributes: *JSPropertySpec,
unforgeableAttributeIds: *jsid,
unforgeableAttributeSpecs: *JSPropertySpec,
constants: *ConstantSpec,
constantIds: *jsid,
constantSpecs: *ConstantSpec
}
pub struct NativePropertyHooks {
resolve_own_property: *u8,
resolve_property: *u8,
enumerate_own_properties: *u8,
enumerate_properties: *u8,
proto_hooks: *NativePropertyHooks
}
pub struct JSNativeHolder {
native: js::jsapi::JSNative,
propertyHooks: *NativePropertyHooks
}
#[deriving(Clone)]
pub enum ConstantVal {
IntVal(i32),
UintVal(u32),
DoubleVal(f64),
BoolVal(bool),
NullVal,
VoidVal
}
#[deriving(Clone)]
pub struct ConstantSpec {
name: *libc::c_char,
value: ConstantVal
}
pub struct DOMClass {
// A list of interfaces that this object implements, in order of decreasing
// derivedness.
interface_chain: [PrototypeList::id::ID, ..MAX_PROTO_CHAIN_LENGTH],
unused: bool, // DOMObjectIsISupports (always false)
native_hooks: *NativePropertyHooks
}
pub struct DOMJSClass {
base: JSClass,
dom_class: DOMClass
}
pub fn GetProtoOrIfaceArray(global: *JSObject) -> **JSObject {
unsafe {
/*assert ((*JS_GetClass(global)).flags & JSCLASS_DOM_GLOBAL) != 0;*/
cast::transmute(RUST_JSVAL_TO_PRIVATE(JS_GetReservedSlot(global, DOM_PROTOTYPE_SLOT)))
}
}
pub fn CreateInterfaceObjects2(cx: *JSContext, global: *JSObject, receiver: *JSObject,
protoProto: *JSObject, protoClass: *JSClass,
constructorClass: *JSClass, constructor: JSNative,
ctorNargs: u32,
domClass: *DOMClass,
methods: *JSFunctionSpec,
properties: *JSPropertySpec,
constants: *ConstantSpec,
staticMethods: *JSFunctionSpec,
name: &str) -> *JSObject {
let mut proto = ptr::null();
if protoClass.is_not_null() {
proto = CreateInterfacePrototypeObject(cx, global, protoProto,
protoClass, methods,
properties, constants);
if proto.is_null() {
return ptr::null();
}
unsafe {
JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT,
RUST_PRIVATE_TO_JSVAL(domClass as *libc::c_void));
}
}
let mut interface = ptr::null();
if constructorClass.is_not_null() || constructor.is_not_null() {
interface = do str::as_c_str(name) |s| {
CreateInterfaceObject(cx, global, receiver, constructorClass,
constructor, ctorNargs, proto,
staticMethods, constants, s)
};
if interface.is_null() {
return ptr::null();
}
}
if protoClass.is_not_null() {
proto
} else {
interface
}
}
fn CreateInterfaceObject(cx: *JSContext, global: *JSObject, receiver: *JSObject,
constructorClass: *JSClass, constructorNative: JSNative,
ctorNargs: u32, proto: *JSObject,
staticMethods: *JSFunctionSpec,
constants: *ConstantSpec,
name: *libc::c_char) -> *JSObject {
unsafe {
let constructor = if constructorClass.is_not_null() {
let functionProto = JS_GetFunctionPrototype(cx, global);
if functionProto.is_null() {
ptr::null()
} else {
JS_NewObject(cx, constructorClass, functionProto, global)
}
} else {
assert!(constructorNative.is_not_null());
let fun = JS_NewFunction(cx, constructorNative, ctorNargs,
JSFUN_CONSTRUCTOR, global, name);
if fun.is_null() {
ptr::null()
} else {
JS_GetFunctionObject(fun)
}
};
if constructor.is_null() {
return ptr::null();
}
if staticMethods.is_not_null() &&
!DefineMethods(cx, constructor, staticMethods) {
return ptr::null();
}
if constructorClass.is_not_null() {
let toString = do str::as_c_str("toString") |s| {
DefineFunctionWithReserved(cx, constructor, s,
InterfaceObjectToString,
0, 0)
};
if toString.is_null() {
return ptr::null();
}
let toStringObj = JS_GetFunctionObject(toString);
SetFunctionNativeReserved(toStringObj, TOSTRING_CLASS_RESERVED_SLOT,
&RUST_PRIVATE_TO_JSVAL(constructorClass as *libc::c_void));
let s = JS_InternString(cx, name);
if s.is_null() {
return ptr::null();
}
SetFunctionNativeReserved(toStringObj, TOSTRING_NAME_RESERVED_SLOT,
&RUST_STRING_TO_JSVAL(s));
}
if constants.is_not_null() &&
!DefineConstants(cx, constructor, constants) {
return ptr::null();
}
if proto.is_not_null() && JS_LinkConstructorAndPrototype(cx, constructor, proto) == 0 {
return ptr::null();
}
let alreadyDefined = 0;
if JS_AlreadyHasOwnProperty(cx, receiver, name, &alreadyDefined) == 0 {
return ptr::null();
}
if alreadyDefined == 0 &&
JS_DefineProperty(cx, receiver, name, RUST_OBJECT_TO_JSVAL(constructor),
ptr::null(), ptr::null(), 0) == 0 {
return ptr::null();
}
return constructor;
}
}
fn DefineConstants(cx: *JSContext, obj: *JSObject, constants: *ConstantSpec) -> bool {
let mut i = 0;
loop {
unsafe {
let spec = *constants.offset(i);
if spec.name.is_null() {
return true;
}
let jsval = match spec.value {
NullVal => JSVAL_NULL,
IntVal(i) => RUST_INT_TO_JSVAL(i),
UintVal(u) => RUST_UINT_TO_JSVAL(u),
DoubleVal(d) => RUST_DOUBLE_TO_JSVAL(d),
BoolVal(b) if b => JSVAL_TRUE,
BoolVal(_) => JSVAL_FALSE,
VoidVal => JSVAL_VOID
};
if JS_DefineProperty(cx, obj, spec.name,
jsval, ptr::null(),
ptr::null(),
JSPROP_ENUMERATE | JSPROP_READONLY |
JSPROP_PERMANENT) == 0 {
return false;
}
}
i += 1;
}
}
fn DefineMethods(cx: *JSContext, obj: *JSObject, methods: *JSFunctionSpec) -> bool {
unsafe {
JS_DefineFunctions(cx, obj, methods) != 0
}
}
fn DefineProperties(cx: *JSContext, obj: *JSObject, properties: *JSPropertySpec) -> bool {
unsafe {
JS_DefineProperties(cx, obj, properties) != 0
}
}
fn CreateInterfacePrototypeObject(cx: *JSContext, global: *JSObject,
parentProto: *JSObject, protoClass: *JSClass,
methods: *JSFunctionSpec,
properties: *JSPropertySpec,
constants: *ConstantSpec) -> *JSObject {
unsafe {
let ourProto = JS_NewObjectWithUniqueType(cx, protoClass, parentProto, global);
if ourProto.is_null() {
return ptr::null();
}
if methods.is_not_null() && !DefineMethods(cx, ourProto, methods) {
return ptr::null();
}
if properties.is_not_null() && !DefineProperties(cx, ourProto, properties) {
return ptr::null();
}
if constants.is_not_null() && !DefineConstants(cx, ourProto, constants) {
return ptr::null();
}
return ourProto;
}
}
pub extern fn ThrowingConstructor(_cx: *JSContext, _argc: uint, _vp: *JSVal) -> JSBool {
//XXX should trigger exception here
return 0;
}
pub fn initialize_global(global: *JSObject) {
let protoArray = @mut ([0 as *JSObject, ..52]);
assert!(protoArray.len() == PrototypeList::id::_ID_Count as uint);
unsafe {
//XXXjdm we should be storing the box pointer instead of the inner
let box = squirrel_away(protoArray);
let inner = ptr::to_unsafe_ptr(&(*box).payload);
JS_SetReservedSlot(global,
DOM_PROTOTYPE_SLOT,
RUST_PRIVATE_TO_JSVAL(inner as *libc::c_void));
}
}
pub trait CacheableWrapper {
fn get_wrappercache(&mut self) -> &mut WrapperCache;
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject;
}
pub struct WrapperCache {
wrapper: *JSObject
}
impl WrapperCache {
pub fn get_wrapper(&self) -> *JSObject {
unsafe { cast::transmute(self.wrapper) }
}
pub fn set_wrapper(&mut self, wrapper: *JSObject) {
self.wrapper = wrapper;
}
pub fn get_rootable(&self) -> **JSObject {
return to_unsafe_ptr(&self.wrapper);
}
pub fn new() -> WrapperCache {
WrapperCache {
wrapper: ptr::null()
}
}
}
pub fn WrapNewBindingObject(cx: *JSContext, scope: *JSObject,
mut value: @mut CacheableWrapper,
vp: *mut JSVal) -> bool {
unsafe {
let cache = value.get_wrappercache();
let obj = cache.get_wrapper();
if obj.is_not_null() /*&& js::GetObjectCompartment(obj) == js::GetObjectCompartment(scope)*/ {
*vp = RUST_OBJECT_TO_JSVAL(obj);
return true;
}
let obj = value.wrap_object_shared(cx, scope);
if obj.is_null() {
return false;
}
// MOZ_ASSERT(js::IsObjectInContextCompartment(scope, cx));
cache.set_wrapper(obj);
*vp = RUST_OBJECT_TO_JSVAL(obj);
return JS_WrapValue(cx, cast::transmute(vp)) != 0;
}
}
pub fn WrapNativeParent(cx: *JSContext, scope: *JSObject, mut p: Option<@mut CacheableWrapper>) -> *JSObject {
match p {
Some(ref mut p) => {
let cache = p.get_wrappercache();
let wrapper = cache.get_wrapper();
if wrapper.is_not_null() {
return wrapper;
}
let wrapper = p.wrap_object_shared(cx, scope);
cache.set_wrapper(wrapper);
wrapper
}
None => unsafe { JS_GetGlobalObject(cx) }
}
}
pub trait BindingObject {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper>;
}
pub fn GetPropertyOnPrototype(cx: *JSContext, proxy: *JSObject, id: jsid, found: *mut bool,
vp: *JSVal) -> bool {
unsafe {
//let proto = GetObjectProto(proxy);
let proto = JS_GetPrototype(proxy);
if proto.is_null() {
*found = false;
return true;
}
let hasProp = 0;
if JS_HasPropertyById(cx, proto, id, ptr::to_unsafe_ptr(&hasProp)) == 0 {
return false;
}
*found = hasProp != 0;
let no_output = vp.is_null();
if hasProp == 0 || no_output {
return true;
}
JS_ForwardGetPropertyTo(cx, proto, id, proxy, vp) != 0
}
}
pub fn GetArrayIndexFromId(_cx: *JSContext, id: jsid) -> Option<u32> {
unsafe {
if RUST_JSID_IS_INT(id) != 0 {
return Some(RUST_JSID_TO_INT(id) as u32);
}
return None;
}
// if id is length atom, -1, otherwise
/*return if JSID_IS_ATOM(id) {
let atom = JSID_TO_ATOM(id);
//let s = *GetAtomChars(id);
if s > 'a' && s < 'z' {
return -1;
}
let i = 0;
let str = AtomToLinearString(JSID_TO_ATOM(id));
return if StringIsArray(str, &mut i) != 0 { i } else { -1 }
} else {
IdToInt32(cx, id);
}*/
}
pub fn XrayResolveProperty(cx: *JSContext,
wrapper: *JSObject,
id: jsid,
desc: *mut JSPropertyDescriptor,
_methods: Option<~[(JSFunctionSpec, jsid)]>,
attributes: Option<~[(JSPropertySpec, jsid)]>,
_constants: Option<~[(ConstantSpec, jsid)]>) -> bool
{
unsafe {
match attributes {
Some(attrs) => {
for attrs.iter().advance |&elem| {
let (attr, attr_id) = elem;
if attr_id == JSID_VOID || attr_id != id {
loop;
}
(*desc).attrs = (attr.flags & !(JSPROP_NATIVE_ACCESSORS as u8)) as u32;
let global = JS_GetGlobalForObject(cx, wrapper);
let fun = JS_NewFunction(cx, attr.getter.op, 0, 0, global, ptr::null());
if fun.is_null() {
return false;
}
RUST_SET_JITINFO(fun, attr.getter.info);
let funobj = JS_GetFunctionObject(fun);
(*desc).getter = funobj as *u8;
(*desc).attrs |= JSPROP_GETTER;
if attr.setter.op.is_not_null() {
let fun = JS_NewFunction(cx, attr.setter.op, 1, 0, global, ptr::null());
if fun.is_null() {
return false
}
RUST_SET_JITINFO(fun, attr.setter.info);
let funobj = JS_GetFunctionObject(fun);
(*desc).setter = funobj as *u8;
(*desc).attrs |= JSPROP_SETTER;
} else {
(*desc).setter = ptr::null();
}
}
}
None => ()
}
return true;
}
}
fn InternJSString(cx: *JSContext, chars: *libc::c_char) -> Option<jsid> {
unsafe {
let s = JS_InternString(cx, chars);
if s.is_not_null() {
Some(RUST_INTERNED_STRING_TO_JSID(cx, s))
} else {
None
}
}
}
pub fn InitIds(cx: *JSContext, specs: &[JSPropertySpec], ids: &mut [jsid]) -> bool {
let mut rval = true;
for specs.iter().enumerate().advance |(i, spec)| {
if spec.name.is_null() == true {
break;
}
match InternJSString(cx, spec.name) {
Some(id) => ids[i] = id,
None => {
rval = false;
return false;
}
}
}
rval
}
pub trait DerivedWrapper {
fn wrap(&mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32;
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32;
}
impl DerivedWrapper for AbstractNode<ScriptView> {
fn wrap(&mut self, cx: *JSContext, _scope: *JSObject, vp: *mut JSVal) -> i32 {
let cache = self.get_wrappercache();
let wrapper = cache.get_wrapper();
if wrapper.is_not_null() {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(wrapper) };
return 1;
}
unsafe { *vp = RUST_OBJECT_TO_JSVAL(node::create(cx, self)) };
return 1;
}
fn wrap_shared(@mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
fail!(~"nyi")
}
}
#[deriving(ToStr)]
pub enum Error {
FailureUnknown
}
pub type ErrorResult = Result<(), Error>;
pub struct EnumEntry {
value: &'static str,
length: uint
}
pub fn FindEnumStringIndex(cx: *JSContext,
v: JSVal,
values: &[EnumEntry]) -> Result<uint, ()> {
unsafe {
let jsstr = JS_ValueToString(cx, v);
if jsstr.is_null() {
return Err(());
}
let length = 0;
let chars = JS_GetStringCharsAndLength(cx, jsstr, ptr::to_unsafe_ptr(&length));
if chars.is_null() {
return Err(());
}
for values.iter().enumerate().advance |(i, value)| {
if value.length != length as uint {
loop;
}
let mut equal = true;
for uint::iterate(0, length as uint) |j| {
if value.value[j] as u16 != *chars.offset(j) {
equal = false;
break;
}
};
if equal {
return Ok(i);
}
}
return Err(()); //XXX pass in behaviour for value not found
}
}
pub fn HasPropertyOnPrototype(cx: *JSContext, proxy: *JSObject, id: jsid) -> bool {
// MOZ_ASSERT(js::IsProxy(proxy) && js::GetProxyHandler(proxy) == handler);
let mut found = false;
return !GetPropertyOnPrototype(cx, proxy, id, &mut found, ptr::null()) || found;
}
|