/
spidermonkey.c
1942 lines (1649 loc) · 56.5 KB
/
spidermonkey.c
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define JS_C_STRINGS_ARE_UTF8
#include <ruby.h>
//#define DEBUG
#if defined NEED_MOZJS_PREFIX
# include <mozjs/jsapi.h>
# include <mozjs/jshash.h>
# include <mozjs/jsobj.h>
#elif defined NEED_SMJS_PREFIX
# include <smjs/jsapi.h>
# include <smjs/jshash.h>
# include <smjs/jsobj.h>
#else
# include <jsapi.h>
# include <jshash.h>
# include <jsobj.h>
#endif
// Default stack size
#define JS_STACK_CHUNK_SIZE 16384
// SETTING THIS TOO LOW RESULTS IN SEGFAULTS!
// More specifically, having the runtime actually reach its maximum
// memory allocation appears to cause segfaults (JS_NewObject returns a
// bad pointer, then JS_DefineFunction segfaults). It is thus quite
// important to call JS_GC frequently... we call JS_MaybeGC before
// evaluating a script to reduce the problem.
#define JS_RUNTIME_MAXBYTES 0x300000L
#define RBSMJS_DEFAULT_CONTEXT "@@defaultContext"
#define RBSMJS_VALUES_CONTEXT "@context"
#define RBSMJS_CONTEXT_GLOBAL "global"
#define RBSMJS_CONTEXT_BINDINGS "bindings"
#define RBSMJS_RUBY_TO_JS_MAP "$mozjs_mapping"
#define RBSM_CONVERT_SHALLOW 1
#define RBSM_CONVERT_DEEP 0
#ifdef WIN32
# ifdef DEBUG
# define trace printf("\n"); printf
# else
# define trace(msg)
# endif
#elif defined DEBUG
# define trace(format, ...) do { printf(format, ## __VA_ARGS__); printf("\n"); } while (0)
#else
# define trace(format, ...)
#endif
#define ZERO_ARITY_METHOD_IS_PROPERTY
VALUE rb_cDate;
VALUE eJSError;
VALUE eJSConvertError;
VALUE eJSEvalError;
VALUE cJSValue;
VALUE cJSContext;
VALUE cJSFunction;
VALUE cSMJS;
JSRuntime* gSMJS_runtime;
#ifdef DEBUG
int alloc_count_js2rb;
int alloc_count_rb2js;
#endif
// RubyObject/RubyFunction Properties
typedef struct{
VALUE rbobj;
jsval jsv;
}sSMJS_Class;
// RubyException Error
typedef struct{
int status;
jsval erval;
VALUE errinfo;
}sSMJS_Error;
// SpiderMonkey::Context -- Structure containing instance data
typedef struct{
JSContext* cx;
jsval last_exception; // Last JS Exception
char last_message[BUFSIZ]; // Last Error Message
JSObject* store; // "JS Store for the pair-GC"
JSHashTable* id2rbval; // JS-VALUE for Ruby-Object#__id__
}sSMJS_Context;
// SpiderMonkey::Value -- Structure containing instance data
typedef struct{
jsval value;
sSMJS_Context* cs;
}sSMJS_Value;
// Data required for yield methods
typedef struct{
JSContext* cx;
JSObject* obj;
jsint id;
jsval val;
jsval key;
JSIdArray* ida;
int i;
void* data;
char* keystr;
}sSMJS_Enumdata;
typedef void(* RBSMJS_YIELD)( sSMJS_Enumdata* enm );
typedef VALUE(* RBSMJS_Convert)( JSContext* cx, jsval val );
static VALUE RBSMContext_FROM_JsContext( JSContext* cx );
static JSBool rbsm_class_get_property( JSContext* cx, JSObject* obj, jsval id, jsval* vp );
static JSBool rbsm_class_set_property( JSContext* cx, JSObject* obj, jsval id, jsval* vp );
static JSBool rbsm_resolve( JSContext* cx, JSObject *obj, jsval id, uintN flags, JSObject **objp );
static int rbsm_check_ruby_property(JSContext* cx, JSObject* obj, jsval id);
static JSBool rbsm_error_get_property( JSContext* cx, JSObject* obj, jsval id, jsval* vp );
static void rbsm_class_finalize ( JSContext* cx, JSObject* obj );
static JSBool rb_smjs_value_object_callback( JSContext* cx, JSObject* thisobj, uintN argc, jsval* argv, jsval* rval );
static JSBool rb_smjs_value_function_callback( JSContext* cx, JSObject* thisobj, uintN argc, jsval* argv, jsval* rval );
static JSObject* rbsm_proc_to_function( JSContext* cx, VALUE proc );
static void rbsm_rberror_finalize ( JSContext* cx, JSObject* obj );
static JSObject* rbsm_ruby_to_jsobject( JSContext* cx, VALUE obj );
static JSBool rbsm_rubyexception_to_string( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
static JSBool rbsm_class_to_string( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
static JSBool rbsm_class_no_such_method( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
static VALUE rb_smjs_convertvalue( JSContext* cx, jsval value );
static VALUE rb_smjs_convert_prim( JSContext* cx, jsval value );
static JSBool rbsm_rubystring_to_jsval( JSContext* cx, VALUE rval, jsval* jval );
static JSBool rbsm_get_ruby_property( JSContext* cx, JSObject* obj, jsval id, jsval* vp, VALUE rbobj );
static VALUE rbsm_evalerror_new( VALUE context, VALUE erval );
static VALUE rbsm_evalerror_new_jsval( VALUE context, jsval jsvalerror );
static VALUE rb_smjs_value_new_jsval( VALUE context, jsval value );
static VALUE rb_smjs_value_get_prototype( VALUE self );
static void* rbsm_each( JSContext* cx, jsval value, RBSMJS_YIELD yield, void* data );
static JSObjectOps* rbsm_class_get_object_ops( JSContext* cx, JSClass* clasp );
static void rb_smjs_context_errorhandle( JSContext* cx, const char* message, JSErrorReport* report );
static VALUE rb_smjs_context_flush( VALUE self );
static VALUE rb_smjs_value_call_with_this(int argc, VALUE* rargv, VALUE self);
typedef enum RBSMErrNum{
#define MSG_DEF( name, number, count, exception, format ) \
name = number,
#include "rbsm.msg"
#undef MSG_DEF
RBSMErr_Limit
#undef MSGDEF
} RBSMErrNum;
JSErrorFormatString rbsm_ErrorFormatString[RBSMErr_Limit] = {
#define MSG_DEF( name, number, count, exception, format ) { format, count },
#include "rbsm.msg"
#undef MSG_DEF
{0, 0}
};
#ifndef JSCLASS_GLOBAL_FLAGS
#define JSCLASS_GLOBAL_FLAGS 0
#endif
static JSClass global_class = {
"global", JSCLASS_NEW_RESOLVE | JSCLASS_GLOBAL_FLAGS,
JS_PropertyStub, JS_PropertyStub,
JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub,
JSCLASS_NO_OPTIONAL_MEMBERS
};
static JSClass JSRubyObjectClass = {
"RubyObject", JSCLASS_HAS_PRIVATE | JSCLASS_NEW_RESOLVE,
/*addp*/JS_PropertyStub, /*delpr*/JS_PropertyStub,
/*getp*/rbsm_class_get_property, /*setp*/rbsm_class_set_property,
JS_EnumerateStub, (JSResolveOp)rbsm_resolve, JS_ConvertStub, rbsm_class_finalize,
/* getObjectOps */NULL, /*checkAccess */NULL, /*call*/rb_smjs_value_object_callback,
/* construct*/NULL, /* xdrObject*/NULL, /* hasInstance*/NULL, /* mark*/NULL,
/* spare*/0
};
static JSClass JSRubyFunctionClass = {
"RubyFunction", JSCLASS_HAS_PRIVATE,
/*addp*/JS_PropertyStub, /*delpr*/JS_PropertyStub,
/*getp*/rbsm_class_get_property, /*setp*/JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, rbsm_class_finalize,
/* getObjectOps */rbsm_class_get_object_ops, /*checkAccess */NULL, /*call*/rb_smjs_value_function_callback,
/* construct*/NULL, /* xdrObject*/NULL, /* hasInstance*/NULL, /* mark*/NULL,
/* spare*/0
};
static JSFunctionSpec JSRubyObjectFunctions[] = {
{"__noSuchMethod__", rbsm_class_no_such_method, 2},
{"toString", rbsm_class_to_string, 0},
{0}
};
static JSFunctionSpec JSRubyExceptionFunctions[] = {
{"toString", rbsm_rubyexception_to_string, 0},
{0}
};
static JSClass JSRubyExceptionClass = {
"RubyException", JSCLASS_HAS_PRIVATE,
/*addp*/JS_PropertyStub, /*delpr*/JS_PropertyStub,
/*getp*/rbsm_error_get_property, /*setp*/JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, rbsm_rberror_finalize,
JSCLASS_NO_OPTIONAL_MEMBERS
};
static JSObjectOps rbsm_FunctionOps;
// convert -------------------------------------------------------
// Convert a JS object to a Ruby String
static VALUE
rb_smjs_to_s( JSContext* cx, jsval value ){
JSString* str = JS_ValueToString( cx, value );
return rb_str_new( JS_GetStringBytes( str ), JS_GetStringLength( str ) );
}
// Convert a JS object to a Ruby Boolean
static VALUE
rb_smjs_to_bool( JSContext* cx, jsval value ){
JSBool bp;
if( !JS_ValueToBoolean( cx, value, &bp ) ){
rb_raise( eJSConvertError, "can't convert to boolean" );
}
return bp ? Qtrue : Qfalse;
}
// Convert a JS object to a Ruby Array
static VALUE
rb_smjs_to_a( JSContext* cx, jsval value, int shallow ){
VALUE ary;
VALUE r;
if( JSVAL_IS_OBJECT( value ) ){
JSObject* jo = JSVAL_TO_OBJECT( value );
if( JSVAL_IS_NULL( value ) ) return rb_ary_new( );
if( JS_IsArrayObject( cx, jo ) ){
jsuint length;
if( JS_HasArrayLength( cx, jo, &length ) ){
jsuint i;
ary = rb_ary_new2( length );
for( i = 0 ; i < length ; i++ ){
jsval v;
if( JS_GetElement( cx, jo, i, &v ) ){
VALUE va;
if( shallow ){
va = rb_smjs_convert_prim( cx, v );
}else{
va = rb_smjs_convertvalue( cx, v );
}
rb_ary_store( ary, i, va );
}else{
rb_raise( eJSConvertError, "Fail convert to array[]" );
}
}
return ary;
}
}
}
r = rb_smjs_convertvalue( cx, value );
return rb_funcall( r, rb_intern( "to_a" ), 0 );
}
typedef struct{
VALUE value;
int shallow;
}sRBSM_toHash;
static void
rb_smjs_to_h_yield( sSMJS_Enumdata* enm ){
sRBSM_toHash* dat;
VALUE val;
dat = (sRBSM_toHash*)(enm->data);
if( dat->shallow ){
val = rb_smjs_convertvalue( enm->cx, enm->val );
}else{
val = rb_smjs_convert_prim( enm->cx, enm->val );
}
rb_hash_aset( dat->value, rb_smjs_convertvalue( enm->cx, enm->key ), val );
}
static VALUE
rb_smjs_to_h( JSContext* cx, jsval value, int shallow ){
sRBSM_toHash edat;
VALUE ret = rb_hash_new( );
if( !JSVAL_IS_OBJECT( value ) ){
rb_raise( eJSConvertError, "Value is not an object" );
}else{
if( JSVAL_IS_NULL( value ) ){
return ret;
}
}
edat.shallow = shallow;
edat.value = ret;
rbsm_each( cx, value, rb_smjs_to_h_yield, (void*)&edat );
return edat.value;
}
static VALUE
rb_smjs_to_i( JSContext* cx, jsval value ){
jsint ip;
if( JS_ValueToInt32( cx, value, &ip ) ){
return INT2NUM( ip );
}else{
rb_raise( eJSConvertError, "Failed to convert value to integer" );
}
}
static VALUE
rb_smjs_to_f( JSContext* cx, jsval value ){
jsdouble d;
if( JS_ValueToNumber( cx, value, &d ) ){
return rb_float_new( d );
}else{
rb_raise( eJSConvertError, "Failed to convert value to float" );
}
}
static VALUE
rb_smjs_to_num( JSContext* cx, jsval value ){
if( JSVAL_IS_INT( value ) ){
return rb_smjs_to_i( cx, value );
}else if( JSVAL_IS_DOUBLE( value ) ){
return rb_smjs_to_f( cx, value );
}else{
rb_raise( eJSConvertError, "Value is not a number" );
}
}
static VALUE
rb_smjs_convertvalue( JSContext* cx, jsval value ){
JSObject* jo;
sSMJS_Class* so;
JSType t = JS_TypeOfValue( cx, value );
switch( t ){
case JSTYPE_VOID: return Qnil;
case JSTYPE_STRING: return rb_smjs_to_s( cx, value );
case JSTYPE_BOOLEAN: return rb_smjs_to_bool( cx, value );
case JSTYPE_OBJECT:
if( JSVAL_IS_NULL( value ) ) return Qnil;
jo = JSVAL_TO_OBJECT( value );
so = JS_GetInstancePrivate( cx, jo, &JSRubyObjectClass, NULL );
if( so ){
return so->rbobj;
}
if( JS_IsArrayObject( cx, JSVAL_TO_OBJECT( value ) ) )
return rb_smjs_to_a( cx, value, RBSM_CONVERT_DEEP );
return rb_smjs_to_h( cx, value, RBSM_CONVERT_DEEP );
case JSTYPE_NUMBER:
return rb_smjs_to_num( cx, value );
case JSTYPE_FUNCTION:
rb_raise ( eJSConvertError, "Unsupported: cannot convert JavaScript function to Ruby" ); break;
default:
rb_raise ( eJSConvertError, "Unsupported object type" );
break;
}
}
// Ruby String to JavaScript String
static JSBool
rbsm_rubystring_to_jsval( JSContext* cx, VALUE rval, jsval* jval ){
JSString* jsstr;
if( (jsstr = JS_NewStringCopyZ( cx, StringValuePtr( rval ) ) ) ){
*jval = STRING_TO_JSVAL( jsstr );
return JS_TRUE;
}
return JS_FALSE;
}
// Ruby Object to JS Object
static JSBool
rb_smjs_ruby_to_js( JSContext* cx, VALUE rval, jsval* jval ){
if( rb_obj_is_instance_of( rval, cJSValue ) ){
sSMJS_Value* sv;
Data_Get_Struct( rval, sSMJS_Value, sv );
*jval = sv->value;
return JS_TRUE;
}
switch( TYPE( rval ) ){
case T_STRING: return rbsm_rubystring_to_jsval( cx, rval, jval );
case T_FIXNUM:
if( NUM2LONG( rval ) >= INT_MIN && NUM2LONG( rval ) <= INT_MAX && INT_FITS_IN_JSVAL( NUM2INT( rval ) ) ){
*jval = INT_TO_JSVAL( NUM2INT( rval ) );
break;
}
case T_FLOAT:
case T_BIGNUM: return JS_NewDoubleValue( cx, NUM2DBL( rval ), jval );
case T_TRUE: *jval = JSVAL_TRUE; break;
case T_FALSE: *jval = JSVAL_FALSE; break;
case T_NIL: *jval = JSVAL_NULL; break;
default:
*jval = OBJECT_TO_JSVAL( rbsm_ruby_to_jsobject( cx, rval ) );
}
return JS_TRUE;
}
static VALUE
rb_smjs_convert_prim( JSContext* cx, jsval value ){
JSObject* jo;
sSMJS_Class* so;
JSType t = JS_TypeOfValue( cx, value );
VALUE context;
switch( t ){
case JSTYPE_VOID: return Qnil;
case JSTYPE_STRING: return rb_smjs_to_s( cx, value );
case JSTYPE_BOOLEAN: return rb_smjs_to_bool( cx, value );
case JSTYPE_NUMBER: return rb_smjs_to_num( cx, value );
case JSTYPE_OBJECT:
if( JSVAL_IS_NULL( value ) ) return Qnil;
jo = JSVAL_TO_OBJECT( value );
so = JS_GetInstancePrivate( cx, jo, &JSRubyObjectClass, NULL );
if( so ){
return so->rbobj;
}
if( JS_IsArrayObject( cx, jo ) )
return rb_smjs_to_a( cx, value, RBSM_CONVERT_SHALLOW );
default:
context = RBSMContext_FROM_JsContext( cx );
return rb_smjs_value_new_jsval( context, value );
}
}
// etc ------------------------------------------------------------------
static VALUE
RBSMContext_FROM_JsContext( JSContext* cx ){
return (VALUE)JS_GetContextPrivate( cx );
}
static VALUE
rb_smjs_context_get_global( VALUE self ){
return rb_iv_get( self, RBSMJS_CONTEXT_GLOBAL );
}
// Convert a JavaScript Exception to Ruby Exception
static void
rb_smjs_raise_ruby( JSContext* cx ){
sSMJS_Error* se;
JSObject* jo;
jsval jsvalerror = 0;
VALUE context = RBSMContext_FROM_JsContext( cx );
VALUE self;
if( !(JS_IsExceptionPending( cx ) && JS_GetPendingException( cx, &jsvalerror ) ) ){
sSMJS_Context* cs;
char tmpmsg[BUFSIZ];
Data_Get_Struct( context, sSMJS_Context, cs );
jsvalerror = cs->last_exception;
if( !jsvalerror ){
rb_raise( eJSError, "No exception for error: %s", cs->last_message );
}
cs->last_exception = 0;
strncpy( tmpmsg, cs->last_message, BUFSIZ );
sprintf( cs->last_message, "Exception already passed to Ruby: %s", tmpmsg );
}
JS_ClearPendingException( cx );
if( JSVAL_IS_OBJECT( jsvalerror ) &&
( jo = JSVAL_TO_OBJECT( jsvalerror ) ) ) {
// If it was originally a Ruby exception, we continue that.
se = JS_GetInstancePrivate( cx, jo, &JSRubyExceptionClass, NULL );
if( se ){
int st = se->status;
se->status = 0;
rb_jump_tag( st );
}
}
// If the exception originated with JavaScript, we build and throw an
// EvalError to Ruby.
self = rbsm_evalerror_new_jsval( context, jsvalerror );
rb_exc_raise( self );
}
// Throw a Ruby exception as a JavaScript exception.
static JSBool
rb_smjs_raise_js( JSContext* cx, int status ){
JSObject* jo;
sSMJS_Error* se;
sSMJS_Value* sv;
jsval stack_string;
VALUE rb_g;
VALUE rb_e = rb_gv_get( "$!" );
VALUE context = RBSMContext_FROM_JsContext( cx );
sSMJS_Context* cs;
Data_Get_Struct( context, sSMJS_Context, cs );
trace("rb_smjs_raise_js(cx=%x, status=%x)", cx, status);
jo = JS_NewObject( cx, &JSRubyExceptionClass, NULL, NULL );
JS_DefineFunctions( cx, jo, JSRubyExceptionFunctions );
rb_g = rb_iv_get( context, RBSMJS_CONTEXT_GLOBAL );
Data_Get_Struct( rb_g, sSMJS_Value, sv );
if( JS_CallFunctionName( cx, JSVAL_TO_OBJECT( sv->value ), "__getStack__", 0, NULL, &stack_string ) ){
VALUE rb_stack = rb_smjs_to_s( cx, stack_string );
VALUE stack_list = rb_iv_get( rb_e, "@all_stacks" );
if( !RTEST( stack_list ) ){
stack_list = rb_ary_new();
rb_iv_set( rb_e, "@all_stacks", stack_list );
}
JS_SetProperty( cx, jo, "stack", &stack_string );
{
VALUE new_entry = rb_ary_new();
rb_ary_push( new_entry, ID2SYM( rb_intern( "js" ) ) );
rb_ary_push( new_entry, rb_stack );
rb_ary_push( stack_list, new_entry );
}
{
VALUE new_entry = rb_ary_new();
rb_ary_push( new_entry, ID2SYM( rb_intern( "ruby" ) ) );
rb_ary_push( new_entry, rb_funcall( Qnil, rb_intern( "caller" ), 0) );
rb_ary_push( stack_list, new_entry );
}
} else {
trace("Failure calling __getStack__!");
}
se = JS_malloc( cx, sizeof( sSMJS_Error ) );
se->status = status;
se->errinfo = rb_obj_dup( rb_e );
JS_SetPrivate( cx, jo, (void*)se );
cs->last_exception = OBJECT_TO_JSVAL( jo );
JS_SetPendingException( cx, cs->last_exception );
return JS_FALSE;
}
static const JSErrorFormatString*
rbsm_GetErrorMessage( void* userRef, const char* locale, const uintN errorNumber ){
return &rbsm_ErrorFormatString[errorNumber];
}
// Convert a Ruby Exception to a JS String
static JSBool
rbsm_rubyexception_to_string( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ){
sSMJS_Error* se;
VALUE msg;
se = JS_GetInstancePrivate( cx, obj, &JSRubyExceptionClass, NULL );
if( !se ){
// TODO: The function name should be the Object name
JS_ReportErrorNumber( cx, rbsm_GetErrorMessage, NULL, RBSMMSG_INCOMPATIBLE_PROTO, "RubyException", "toString", "Object" );
return JS_FALSE;
}
msg = rb_funcall( se->errinfo, rb_intern( "to_s" ), 0 );
rbsm_rubystring_to_jsval( cx, msg, rval );
return JS_TRUE;
}
// jsval -> RubyObject Hash
static JSHashNumber
jsid2hash( const void* key ){
return (JSHashNumber)key;
}
static intN
jsidCompare( const void* v1, const void* v2 ){
return (jsid)v1 == (jsid)v2;
}
static intN
rbobjCompare( const void* v1, const void* v2 ){
return (VALUE)v1 == (VALUE)v2;
}
static void
rbsm_set_jsval_to_rbval( sSMJS_Context* cs, VALUE self, jsval value ){
char pname[10];
JSHashEntry* x = JS_HashTableAdd( cs->id2rbval, (const void*)value, (void*)rb_obj_id( self ) );
if( !x ) rb_raise( eJSError, "fail to set rbval to HashTable" );
// Setting value to the one for JS-GC measure store
sprintf( pname, "%x", (int)value );
JS_SetProperty( cs->cx, cs->store, pname, &value );
}
static VALUE
rbsm_get_jsval_to_rbval( sSMJS_Context* cs, jsval value ){
VALUE rid = (VALUE)JS_HashTableLookup( cs->id2rbval, (const void*)value );
return rb_funcall( rb_const_get( rb_cObject, rb_intern( "ObjectSpace" ) ), rb_intern( "_id2ref" ), 1, rid );
}
static JSBool
rbsm_lookup_jsval_to_rbval( sSMJS_Context* cs, jsid value ){
return NULL != JS_HashTableLookup( cs->id2rbval, (const void*)value );
}
static JSBool
rbsm_remove_jsval_to_rbval( sSMJS_Context* cs, jsval value ){
char pname[10];
sprintf( pname, "%x", (int)value );
JS_DeleteProperty( cs->cx, cs->store, pname );
return JS_HashTableRemove( cs->id2rbval, (const void*)value );
}
static JSContext*
RBSMContext_TO_JsContext( VALUE context ){
sSMJS_Context* cs;
Data_Get_Struct( context, sSMJS_Context, cs );
return cs->cx;
}
static jsval
rb_smjs_evalscript( sSMJS_Context* cs, JSObject* obj, int argc, VALUE* argv ){
char* source;
char* filename;
int lineno;
jsval value;
JSBool ok;
VALUE code;
VALUE file;
VALUE line;
rb_scan_args( argc, argv, "12", &code, &file, &line );
SafeStringValue( code );
source = StringValuePtr( code );
if (NIL_P(file)) {
filename = NULL;
} else {
SafeStringValue( file );
filename = StringValuePtr( file );
}
if (NIL_P(line))
lineno = 1;
else
lineno = NUM2INT( line );
//cs->last_exception = 0;
ok = JS_EvaluateScript( cs->cx, obj, source, strlen( source ), filename, lineno, &value );
if( !ok ) rb_smjs_raise_ruby( cs->cx );
return value;
}
static jsval
rb_smjs_value_evalscript( int argc, VALUE* argv, VALUE self ){
sSMJS_Value* sv;
Data_Get_Struct( self, sSMJS_Value, sv );
return rb_smjs_evalscript( sv->cs, JSVAL_TO_OBJECT( sv->value ), argc, argv );
}
static void
rbsm_each_raise( sSMJS_Enumdata* enm, const char* msg ){
JS_DestroyIdArray( enm->cx, enm->ida );
rb_raise( eJSConvertError, "%s", msg );
}
static void*
rbsm_each( JSContext* cx, jsval value, RBSMJS_YIELD yield, void* data ){
sSMJS_Enumdata enmdata;
sSMJS_Enumdata* enm;
JSObject* jo;
enm = &enmdata;
enm->data = data;
enm->cx = cx;
enm->ida = NULL;
enm->obj = JSVAL_TO_OBJECT( value );
if( JSVAL_IS_PRIMITIVE( value ) ){
if( JSVAL_IS_STRING( value ) ){
return enm->data;
//rb_raise ( eJSConvertError, "can't enumerate" );
}else{
return enm->data;
}
}else{
enm->ida = JS_Enumerate( enm->cx, enm->obj );
}
if( !enm->ida ){
rb_raise( eJSConvertError, "Unable to enumerate" );
}
for( enm->i = 0; enm->i < enm->ida->length; enm->i++ ){
enm->id = enm->ida->vector[enm->i];
if( JS_IdToValue( enm->cx, enm->id, &enm->key ) ){
//enm->keystr = JS_GetStringBytes( JS_ValueToString( cx, enm->key ) );
//if( JS_GetProperty( enm->cx, enm->obj, enm->keystr, &enm->val ) ){
if( OBJ_GET_PROPERTY( enm->cx, enm->obj, enm->id, &enm->val ) ){
yield( enm );
}else{
rbsm_each_raise( enm, "Unable to get property" );
}
}else{
rbsm_each_raise( enm, "Unable to get key name" );
}
}
JS_DestroyIdArray( enm->cx, enm->ida );
jo = JS_GetPrototype( enm->cx, enm->obj );
if( jo ){
return rbsm_each( enm->cx, OBJECT_TO_JSVAL( jo ), yield, enm->data );
}
return enm->data;
}
static VALUE
rbsm_value_each( VALUE self, RBSMJS_YIELD yield, void* data ){
sSMJS_Value* sv;
Data_Get_Struct( self, sSMJS_Value, sv );
return (VALUE)rbsm_each( sv->cs->cx, sv->value, yield, data );
}
static void
rb_smjs_value_each_yield( sSMJS_Enumdata* enm ){
rb_yield( rb_smjs_convert_prim( enm->cx, enm->val ) );
}
static void
rb_smjs_value_each_with_index_yield( sSMJS_Enumdata* enm ){
rb_yield_values( 2, rb_smjs_convertvalue( enm->cx, enm->key ), rb_smjs_convert_prim( enm->cx, enm->val ) );
}
// Calls a Proc from inside protect; args is a Ruby array with the Proc
// appended.
static VALUE
rb_smjs_ruby_proc_caller( VALUE args ){
// The proc to execute
VALUE proc;
proc = rb_ary_pop( args );
return rb_apply( proc, rb_intern( "call" ), args );
}
static VALUE
rb_smjs_ruby_proc_caller3( VALUE proc ){
return rb_funcall( proc, rb_intern( "call" ), 0 );
}
static VALUE
rb_smjs_ruby_string_caller( VALUE obj ){
return rb_funcall( obj, rb_intern( "to_s" ), 0 );
}
// used by Object#[] below
static VALUE
rb_smjs_ruby_box_caller( VALUE args ){
VALUE obj;
obj = rb_ary_pop( args );
return rb_apply( obj, rb_intern( "[]" ), args );
}
static VALUE
rb_smjs_ruby_missing_caller( VALUE args ){
VALUE obj;
obj = rb_ary_pop( args );
return rb_apply( obj, rb_intern( "method_missing" ), args );
}
#ifdef ZERO_ARITY_METHOD_IS_PROPERTY
struct{
char* keyname;
jsval val;
}g_last0arity;
#endif
// Ruby Object#[] called in JS as JSObject()
static JSBool
rb_smjs_value_object_callback( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ){
JSObject* fobj;
VALUE rargs, res;
uintN i;
int status;
sSMJS_Class* so;
fobj = JSVAL_TO_OBJECT( argv[-2] );
// If we are trying to invoke this object as a zero-param method, and
// it was just retrieved as a 0-arity "method as property", we
// silently return the object itself; the likihood that we actually
// meant to invoke :[] with no arguments is very low.
if (argc == 0 && OBJECT_TO_JSVAL(fobj) == g_last0arity.val) {
*rval = g_last0arity.val;
return JS_TRUE;
}
so = (sSMJS_Class*)JS_GetPrivate( cx, fobj );
// Argument in SpiderMonkey::Value
rargs = rb_ary_new2( argc + 1 );
for( i = 0 ; i < argc ; i++ )
rb_ary_store( rargs, i, rb_smjs_convert_prim( cx, argv[i] ) );
rb_ary_store( rargs, i, so->rbobj );
// Execute the proc
res = rb_protect( rb_smjs_ruby_box_caller, rargs, &status );
// Check the Ruby function execution result; if an exception was
// thrown, we raise a corresponding error in JavaScript.
if( status != 0 )
return rb_smjs_raise_js( cx, status );
return rb_smjs_ruby_to_js( cx, res, rval );
}
// Ruby method called from JavaScript
static JSBool
rb_smjs_value_function_callback( JSContext* cx, JSObject* thisobj, uintN argc, jsval* argv, jsval* rval ){
JSObject* fobj;
VALUE rargs, res;
uintN i;
int status;
sSMJS_Class* so;
fobj = JSVAL_TO_OBJECT( argv[-2] );
so = (sSMJS_Class*)JS_GetPrivate( cx, fobj );
rargs = rb_ary_new2( argc + 1 );
for( i = 0 ; i < argc ; i++ )
rb_ary_store( rargs, i, rb_smjs_convert_prim( cx, argv[i] ) );
rb_ary_store( rargs, i, so->rbobj );
// Run proc
res = rb_protect( rb_smjs_ruby_proc_caller, rargs, &status );
// If a Ruby exception was thrown, raise a JS exception
if( status != 0 )
return rb_smjs_raise_js( cx, status );
return rb_smjs_ruby_to_js( cx, res, rval );
}
static VALUE
rb_smjs_ruby_proc_caller2( VALUE args ){
ID mname;
VALUE obj;
obj = rb_ary_pop( args );
mname = rb_ary_pop( args );
return rb_apply( obj, mname, args );
}
static JSBool
rbsm_class_no_such_method( JSContext* cx, JSObject* thisobj, uintN argc, jsval* argv, jsval* rval ){
char* keyname;
sSMJS_Class* so;
VALUE rargs, res;
int status;
keyname = JS_GetStringBytes( JS_ValueToString( cx, argv[0] ) );
trace("_noSuchMethod__(cx=%x, keyname=%s)", cx, keyname );
so = JS_GetInstancePrivate( cx, JSVAL_TO_OBJECT( argv[-2] ), &JSRubyObjectClass, NULL );
if( !so ){
so = JS_GetInstancePrivate( cx, thisobj, &JSRubyObjectClass, NULL );
if( !so ){
JS_ReportErrorNumber( cx, rbsm_GetErrorMessage, NULL, RBSMMSG_NOT_FUNCTION, keyname );
return JS_FALSE;
}
}
#ifdef ZERO_ARITY_METHOD_IS_PROPERTY
if( strcmp( keyname, g_last0arity.keyname ) == 0 ){
trace(" == g_last0arity.keyname" );
*rval = g_last0arity.val;
return JS_TRUE;
}
trace(" != g_last0arity.keyname [%s]", g_last0arity.keyname );
#endif
if (argc != 2)
return JS_FALSE;
rargs = rb_smjs_convertvalue( cx, argv[1] );
rb_ary_unshift( rargs, ID2SYM( rb_intern( keyname ) ) );
rb_ary_push( rargs, so->rbobj );
// Call method_missing
res = rb_protect( rb_smjs_ruby_missing_caller, rargs, &status );
// If an exception was thrown, raise a JS exception
if( status != 0 )
return rb_smjs_raise_js( cx, status );
return rb_smjs_ruby_to_js( cx, res, rval );
}
static JSBool
rbsm_class_to_string( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval ){
sSMJS_Class* so;
VALUE res;
int status;
so = JS_GetInstancePrivate( cx, JSVAL_TO_OBJECT( argv[-2] ), &JSRubyObjectClass, NULL );
if( !so ){
so = JS_GetInstancePrivate( cx, obj, &JSRubyObjectClass, NULL );
if( !so ){
JS_ReportErrorNumber( cx, rbsm_GetErrorMessage, NULL, RBSMMSG_INCOMPATIBLE_PROTO, "RubyObject", "toString", "Object" );
return JS_FALSE;
}
}
res = rb_protect( rb_smjs_ruby_string_caller, so->rbobj, &status );
// Check the Ruby function execution result; if an exception was
// thrown, we raise a corresponding error in JavaScript.
if( status != 0 )
return rb_smjs_raise_js( cx, status );
return rb_smjs_ruby_to_js( cx, res, rval );
}
static JSObjectOps*
rbsm_class_get_object_ops( JSContext* cx, JSClass* clasp ){
return &rbsm_FunctionOps;
}
static JSBool
rbsm_error_get_property( JSContext* cx, JSObject* obj, jsval id, jsval* vp ){
sSMJS_Error* se;
se = JS_GetInstancePrivate( cx, obj, &JSRubyExceptionClass, NULL );
if( !se ){
// TODO: Use the object's name as the function name
char* keyname = JS_GetStringBytes( JS_ValueToString( cx, id ) );
JS_ReportErrorNumber( cx, rbsm_GetErrorMessage, NULL, RBSMMSG_INCOMPATIBLE_PROTO, "RubyObject", keyname, "Object" );
return JS_FALSE;
}
return rbsm_get_ruby_property( cx, obj, id, vp, se->errinfo );
}
static void
rbsm_rberror_finalize( JSContext* cx, JSObject* obj ){
sSMJS_Error* se;
se = (sSMJS_Error*)JS_GetPrivate( cx, obj );
if( se ){
JS_free( cx, se );
}
}
static sSMJS_Class*
rbsm_wrap_class( JSContext* cx, VALUE rbobj ){
sSMJS_Class* so;
VALUE context;
so = (sSMJS_Class*)malloc( sizeof( sSMJS_Class ) );
so->rbobj = rbobj;
context = RBSMContext_FROM_JsContext( cx );
rb_hash_aset( rb_iv_get( context, RBSMJS_CONTEXT_BINDINGS ), rb_obj_id( rbobj ), rbobj );
return so;
}
// Convert a Ruby Proc to a JS function
static JSObject*
rbsm_proc_to_function( JSContext* cx, VALUE proc ){
JSObject* jo;
sSMJS_Class* so;
so = rbsm_wrap_class( cx, proc );
jo = JS_NewObject( cx, &JSRubyFunctionClass, NULL, NULL );
trace("rbsm_proc_to_function(cx=%x, obj=%x); [count %d -> %d]", cx, jo, alloc_count_rb2js, ++alloc_count_rb2js);
so->jsv = OBJECT_TO_JSVAL( jo );
JS_SetPrivate( cx, jo, (void*)so );
return jo;
}
static JSBool
rbsm_resolve( JSContext* cx, JSObject *obj, jsval id, uintN flags, JSObject **objp ) {
if(!rbsm_check_ruby_property(cx, obj, id)) {
return JS_TRUE;
}
char *keyname = JS_GetStringBytes(JS_ValueToString( cx, id ));
trace( "rbsm_resolve(cx=%x, keyname=%s)", cx, keyname );
JS_DefineProperty(cx, obj, keyname, JSVAL_TRUE,
rbsm_class_get_property, rbsm_class_set_property, JSPROP_ENUMERATE);
*objp = obj;
return JS_TRUE;
}
static int
rbsm_check_ruby_property(JSContext* cx, JSObject* obj, jsval id) {
sSMJS_Class *so = JS_GetInstancePrivate( cx, obj, &JSRubyObjectClass, NULL );
VALUE rbobj = so->rbobj;
ID brackets = rb_intern("[]");
ID key_meth = rb_intern("key?");
ID array_like = rb_intern("array_like?");
int keynumber;