-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
2103 lines (1842 loc) · 65 KB
/
lib.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
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
//! # Rust MuJS bindings
//!
//! [MuJS](http://dev.mujs.com) is a lightweight implementation of the
//! Javascript language in a library. MuJS is licensed under ISC
//! license which is FSF approved and compatible with GPL. MuJS rust
//! bindings are licensed under GPLv3.
//!
//! Its primary purpose and design is for embedding in other software
//! to add scripting capability to those programs, but it can also be
//! used as an extensible scripting language.
//!
//! In contrast to other programs that are large and complex, MuJS was
//! designed with a focus on small size, correctness and
//! simplicity. MuJS is written in portable C and implements
//! ECMAScript as specified by ECMA-262.
//!
//! The interface for binding with native code is designed to be as
//! simple as possible to use, and is similar to Lua.
//!
//! For more indepth information about MuJS see [MuJS Reference
//! Manual](http://dev.mujs.com/docs/reference.html).
#[macro_use]
extern crate bitflags;
extern crate libc;
#[link(name = "mujs", kind="static")]
use std::ffi::{CStr, CString};
use libc::{
c_int,
c_double,
c_void,
c_char
};
trait ToCString {
fn to_cstring(self: &Self) -> Result<CString, std::ffi::NulError>;
}
impl ToCString for str {
fn to_cstring(self: &str) -> Result<CString, std::ffi::NulError> {
match CString::new(self) {
Err(e) => Err(e),
Ok(cstr) => Ok(cstr)
}
}
}
extern {
fn js_newstate(alloc: *const c_void, context: *const c_void, flags: c_int) -> *const c_void;
fn js_freestate(J: *const c_void);
fn js_setcontext(J: *const c_void, uctx: *const c_void);
fn js_getcontext(J: *const c_void) -> *const c_void;
fn js_atpanic(J: *const c_void, panic: Option<extern fn(J: *const c_void)>) -> *const c_void;
fn js_gc(J: *const c_void, report: c_int);
fn js_ploadstring(J: *const c_void, filename: *const c_char, source: *const c_char) -> c_int;
fn js_pcall(J: *const c_void, n: c_int) -> c_int;
fn js_pconstruct(J: *const c_void, n: c_int) -> c_int;
// fn js_call(J: *const c_void, n: c_int) -> c_int;
fn js_dostring(J: *const c_void, source: *const c_char) -> c_int;
fn js_newobject(J: *const c_void);
fn js_newarray(J: *const c_void);
fn js_newboolean(J: *const c_void, v: c_int);
fn js_newnumber(J: *const c_void, v: c_double);
fn js_newstring(J: *const c_void, v: *const c_char);
fn js_newregexp(J: *const c_void, pattern: *const c_char, flags: c_int);
fn js_newuserdata(J: *const c_void, tag: *const c_char, data: *mut c_void,
finalize: Option<extern fn(J: *const c_void, data: *mut c_void)>);
fn js_touserdata(J: *const c_void, idx: c_int, tag: *const c_char)-> *mut c_void;
fn js_isobject(J: *const c_void, idx: c_int) -> c_int;
fn js_isarray(J: *const c_void, idx: c_int) -> c_int;
fn js_iscallable(J: *const c_void, idx: c_int) -> c_int;
fn js_isregexp(J: *const c_void, idx: c_int) -> c_int;
fn js_hasproperty(J: *const c_void, idx: c_int, name: *const c_char) -> c_int;
fn js_getproperty(J: *const c_void, idx: c_int, name: *const c_char);
fn js_setproperty(J: *const c_void, idx: c_int, name: *const c_char);
fn js_defproperty(J: *const c_void, idx: c_int, name: *const c_char, attrs: c_int);
fn js_defaccessor(J: *const c_void, idx: c_int, name: *const c_char, attrs: c_int);
fn js_delproperty(J: *const c_void, idx: c_int, name: *const c_char);
fn js_getlength(J: *const c_void, idx: c_int) -> c_int;
fn js_setlength(J: *const c_void, idx: c_int, length: c_int);
fn js_hasindex(J: *const c_void, idx: c_int, i: c_int) -> c_int;
fn js_getindex(J: *const c_void, idx: c_int, i: c_int);
fn js_setindex(J: *const c_void, idx: c_int, i: c_int);
fn js_delindex(J: *const c_void, idx: c_int, i: c_int);
fn js_currentfunction(J: *const c_void);
fn js_pushglobal(J: *const c_void);
fn js_getglobal(J: *const c_void, name: *const c_char);
fn js_setglobal(J: *const c_void, name: *const c_char);
fn js_defglobal(J: *const c_void, name: *const c_char, attrs: c_int);
fn js_newcfunction(J: *const c_void, func: Option<extern fn(J: *const c_void)>,
name: *const c_char,length: c_int);
fn js_pushundefined(J: *const c_void);
fn js_pushnull(J: *const c_void);
fn js_pushboolean(J: *const c_void, v: c_int);
fn js_pushnumber(J: *const c_void, v: c_double);
fn js_pushstring(J: *const c_void, v: *const c_char);
fn js_isdefined(J: *const c_void, idx: c_int) -> c_int;
fn js_isundefined(J: *const c_void, idx: c_int) -> c_int;
fn js_isnull(J: *const c_void, idx: c_int) -> c_int;
fn js_isboolean(J: *const c_void, idx: c_int) -> c_int;
fn js_isnumber(J: *const c_void, idx: c_int) -> c_int;
fn js_isstring(J: *const c_void, idx: c_int) -> c_int;
fn js_isprimitive(J: *const c_void, idx: c_int) -> c_int;
fn js_throw(J: *const c_void);
fn js_newerror(J: *const c_void, message: *const c_char);
fn js_newevalerror(J: *const c_void, message: *const c_char);
fn js_newrangeerror(J: *const c_void, message: *const c_char);
fn js_newreferenceerror(J: *const c_void, message: *const c_char);
fn js_newsyntaxerror(J: *const c_void, message: *const c_char);
fn js_newtypeerror(J: *const c_void, message: *const c_char);
fn js_newurierror(J: *const c_void, message: *const c_char);
fn js_gettop(J: *const c_void) -> c_int;
fn js_pop(J: *const c_void, n: c_int);
fn js_copy(J: *const c_void, idx: c_int);
fn js_rot(J: *const c_void, n: c_int);
fn js_remove(J: *const c_void, idx: c_int);
fn js_tostring(J: *const c_void, idx: i32) -> *const c_char;
fn js_toboolean(J: *const c_void, idx: i32) -> c_int;
fn js_tonumber(J: *const c_void, idx: i32) -> c_double;
fn js_getregistry(J: *const c_void, name: *const c_char);
fn js_setregistry(J: *const c_void, name: *const c_char);
fn js_delregistry(J: *const c_void, name: *const c_char);
}
bitflags! {
pub struct PropertyAttributes: c_int {
/// Read only property attribute
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newobject();
/// state.pushnumber(32.0);
/// state.setproperty(-2, "age");
/// state.defglobal("me", mujs::JS_READONLY);
/// ```
///
/// The above example defines an object in global space named
/// ```me```, which can not be assigned another object due to the
/// read only flag.
const JS_READONLY = 1;
const JS_DONTENUM = 2;
const JS_DONTCONF = 4;
}
}
bitflags! {
pub struct StateFlags: c_int {
/// Compile and run code using ES5 strict mode.
const JS_STRICT = 1;
}
}
bitflags! {
/// Regular expression (RegExp) flags
pub struct RegExpFlags: c_int {
/// Global match
///
/// Finds all matches rather than stopping after first match.
const JS_REGEXP_G = 1;
/// Ingore case
const JS_REGEXP_I = 2;
/// Multiline
///
/// Treat beginning and end characters (^ and $) as working
/// over multiple lines
const JS_REGEXP_M = 4;
}
}
struct InternalState {
state: *const c_void,
memctx: *const c_void,
}
/// Interpreter state contains the value stack, protected environments
/// and environment records.
pub struct State {
internal: Box<InternalState>,
ptr: *mut InternalState,
}
static CLOSURE_TAG: &'static str = "__RustClosure__";
impl State {
/// Constructs a new State.
///
/// # Examples
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
/// ```
pub fn new(flags: StateFlags) -> State {
let mut state = State {
internal: Box::new(InternalState{
state: std::ptr::null(),
memctx: std::ptr::null(),
}),
ptr: std::ptr::null_mut(),
};
state.ptr = state.internal.as_mut() as *mut _;
unsafe {
(*state.ptr).memctx = state.ptr as *const c_void;
(*state.ptr).state = js_newstate(std::ptr::null(), (*state.ptr).memctx, flags.bits);
js_setcontext((*state.ptr).state, (*state.ptr).memctx);
js_atpanic((*state.ptr).state, Some(State::_panic));
};
state
}
extern fn _panic(js: *const c_void) {
let top = unsafe { js_gettop(js) };
let res_c_str = unsafe { js_tostring(js, top - 1) };
let err = unsafe { CStr::from_ptr(res_c_str).to_string_lossy().into_owned() };
eprintln!("");
eprintln!("MuJS stack\n============================");
for i in 0..top {
eprintln!("{}: {}", i, unsafe { CStr::from_ptr(js_tostring(js, i)).to_string_lossy().into_owned() });
}
eprintln!("");
panic!("{:?}", err);
}
/// Run garbage collector.
///
/// # Arguments
///
/// * `report` - Boolean to control report output of GC statistics to stdout
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.gc(true);
/// ```
///
pub fn gc(self: &State, report: bool) {
match report {
true => unsafe { js_gc((*self.ptr).state, 1) },
false => unsafe { js_gc((*self.ptr).state, 0) }
}
}
/// Compile a script with result push on top of stack as a
/// function. This function can then be executed using
/// call() method.
///
/// # Arguments
///
/// * `filename` - A virtual filename for the source
/// * `source` - A string slice with source to compile
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
/// let source = "Math.sin(1.234)";
///
/// state.loadstring("myscript", source).unwrap();
/// state.newobject();
/// state.call(0).unwrap();
///
/// println!("{:?}", state.tostring(0).unwrap());
/// ```
///
pub fn loadstring(self: &State, filename: &str, source: &str) -> Result<(), String> {
match unsafe {
js_ploadstring((*self.ptr).state,
filename.to_cstring().unwrap().as_ptr(),
source.to_cstring().unwrap().as_ptr())
} {
0 => Ok(()),
_ => {
let err = self.tostring(-1);
assert!(err.is_ok());
Err(err.ok().unwrap())
}
}
}
/// Call a function pushed on stack
///
/// Pop the function, this value and all arguments then executes
/// the function. The return value is then pushed onto the stack.
///
/// Follow these steps to perform a function call:
///
/// 1. push the function to call onto the stack
///
/// 2. push this value to be used by the function
///
/// 3. push the arguments to the function in order
///
/// 4. call State::call() with the numbers of arguments pushed
/// onto the stack
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// assert!(state.loadstring("myscript", "Math.sin(3.2);").is_ok());
/// state.newobject();
/// assert!(state.call(0).is_ok());
///
/// println!("Sin(3.2) = {:?}", state.tonumber(0).unwrap());
///
/// ```
///
pub fn call(self: &State, n: i32) -> Result<(), String> {
match unsafe { js_pcall((*self.ptr).state, n) } {
0 => Ok(()),
_ => {
let err = self.tostring(-1);
assert!(err.is_ok());
Err(err.ok().unwrap())
}
}
}
/// Call constructor pushed on stack
///
/// This is similar to State::call(), but without pushing a this
/// value.
///
/// 1. push the constructure function to call onto the strack
/// 2. push the arguments to the constructor function in order
/// 3. finallt, call construct() with the number of arguments
/// pushed on the stack
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.dostring("function Car(make, model, year) { \
/// this.make = make; \
/// this.model = model; \
/// this.year = year; \
/// }").unwrap();
///
/// state.getglobal("Car");
/// state.pushstring("Volvo");
/// state.pushstring("V50");
/// state.pushnumber(2010.0);
/// assert!(state.construct(3).is_ok());
///
/// state.getproperty(0, "model");
/// println!("Model: {:?}", state.tostring(1).unwrap());
///
/// ```
pub fn construct(self: &State, n: i32) -> Result<(), String> {
match unsafe { js_pconstruct((*self.ptr).state, n) } {
0 => Ok(()),
_ => {
let err = self.tostring(-1);
assert!(err.is_ok());
Err(err.ok().unwrap())
}
}
}
pub fn dostring(self: &State, source: &str) -> Result<(), String> {
match unsafe {js_dostring((*self.ptr).state, source.to_cstring().unwrap().as_ptr()) } {
0 => Ok(()),
_ => {
let err = self.tostring(-1);
assert!(err.is_ok());
Err(err.ok().unwrap())
}
}
}
/// Throws error on stack
///
/// Pop the error object on the top of the stack and return
/// control flow to the most recent protected environment.
///
/// # Examples
///
/// ```rust,should_panic
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newerror("Lets create an error");
/// state.throw();
/// ```
pub fn throw(self: &State) {
unsafe { js_throw((*self.ptr).state) };
}
/// Push a Error onto the stack
pub fn newerror(self: &State, message: &str) {
unsafe { js_newerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) };
}
/// Push an EvaluationError onto the stack
pub fn newevalerror(self: &State, message: &str) {
unsafe { js_newevalerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Push a RangeError onto the stack
pub fn newrangeerror(self: &State, message: &str) {
unsafe { js_newrangeerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Push a ReferenceError onto the stack
pub fn newreferenceerror(self: &State, message: &str) {
unsafe { js_newreferenceerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Push a SyntaxError onto the stack
pub fn newsyntaxerror(self: &State, message: &str) {
unsafe { js_newsyntaxerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Push a TypeError onto the stack
pub fn newtypeerror(self: &State, message: &str) {
unsafe { js_newtypeerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Push a URIError onto the stack
pub fn newurierror(self: &State, message: &str) {
unsafe { js_newurierror((*self.ptr).state, message.to_cstring().unwrap().as_ptr()) }
}
/// Throws an Error in the executing environment
pub fn error(self: &State, message: &str) {
unsafe {
js_newerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
};
}
/// Throws an EvalError in the executing environment
pub fn evalerror(self: &State, message: &str) {
unsafe {
js_newevalerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Throws an RangeError in the executing environment
pub fn rangeerror(self: &State, message: &str) {
unsafe {
js_newrangeerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Throws an ReferenceError in the executing environment
pub fn referenceerror(self: &State, message: &str) {
unsafe {
js_newreferenceerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Throws an SyntaxError in the executing environment
pub fn syntaxerror(self: &State, message: &str) {
unsafe {
js_newsyntaxerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Throws an TypeError in the executing environment
pub fn typeerror(self: &State, message: &str) {
unsafe {
js_newtypeerror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Throws an URIError in the executing environment
pub fn urierror(self: &State, message: &str) {
unsafe {
js_newurierror((*self.ptr).state, message.to_cstring().unwrap().as_ptr());
js_throw((*self.ptr).state);
}
}
/// Get top index of stack
pub fn gettop(self: &State) -> i32 {
unsafe { js_gettop((*self.ptr).state) }
}
/// Pop items off the stack
///
/// # Arguments
///
/// * `n` - Number of items to pop off the stack
///
pub fn pop(self: &State, n: i32) {
unsafe { js_pop((*self.ptr).state, n) }
}
/// Rotate items on stack
///
/// For example, let say your stack contains `[A, B, C]` and after
/// a call to this function it will be `[C, B, A]`.
///
/// # Arguments
///
/// * `n` - Number of items to rotate on the stack
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
/// state.pushnumber(1.0);
/// state.pushnumber(2.0);
/// state.pushnumber(3.0);
///
/// state.rot(3);
///
/// println!("Number: {:?}", state.tonumber(0).unwrap());
/// ```
///
/// The above example will print `Number: 3` which now is moved
/// from stack index 2 to index 0.
///
pub fn rot(self: &State, n: i32) {
unsafe { js_rot((*self.ptr).state, n) }
}
/// Copy stack item and push on top of stack
pub fn copy(self: &State, idx: i32) {
unsafe { js_copy((*self.ptr).state, idx) }
}
/// Remove specified item from stack
pub fn remove(self: &State, idx: i32) {
unsafe { js_remove((*self.ptr).state, idx) }
}
/// Create a new object and push onto stack
pub fn newobject(self: &State) {
unsafe { js_newobject((*self.ptr).state) };
}
/// Create an array and push onto stack
///
/// # Examples
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
/// state.newarray();
///
/// state.pushstring("Hello");
/// state.setindex(-2, 0);
///
/// state.pushstring("world!");
/// state.setindex(-2, 1);
///
/// state.setlength(-1, 2);
/// state.setglobal("arr");
///
/// assert!(state.loadstring("script", " \
/// arr[2] = 'Third item'; \
/// arr[3] = 2.43; \
/// arr[1];").is_ok());
/// state.pushundefined();
/// assert!(state.call(0).is_ok());
///
/// assert_eq!(state.tostring(0).unwrap(), "world!");
/// ```
///
pub fn newarray(self: &State) {
unsafe { js_newarray((*self.ptr).state) };
}
/// Create a new boolean and push on top of stack
pub fn newboolean(self: &State, value: bool) {
match value {
true => unsafe { js_newboolean((*self.ptr).state, 1) },
false => unsafe { js_newboolean((*self.ptr).state, 0) }
}
}
/// Create a new number and push on top of stack
pub fn newnumber(self: &State, value: f64) {
unsafe { js_newnumber((*self.ptr).state, value) };
}
/// Create a new string and push on top of stack
pub fn newstring(self: &State, value: &str) {
unsafe { js_newstring((*self.ptr).state, value.to_cstring().unwrap().as_ptr()) };
}
/// Create a new regular expression and push on top of stack
///
/// # Example
///
/// Following example will create a regular expression object and
/// get the test function onto the stack. Then copy the this on
/// stack and a string to test expression against. Then call the
/// test() function which returns a boolean onto the stack.
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newregexp("^Hello (.*)!$", mujs::JS_REGEXP_G);
/// state.getproperty(0, "test");
/// state.copy(0);
/// state.pushstring("Hello World!");
/// state.call(1).unwrap();
///
/// assert_eq!(state.toboolean(1).unwrap(), true);
/// ```
pub fn newregexp(self: &State, pattern: &str, flags: RegExpFlags) {
unsafe { js_newregexp((*self.ptr).state, pattern.to_cstring().unwrap().as_ptr(), flags.bits) };
}
/// Test if stack item is an object
pub fn isobject(self: &State, idx: i32) -> bool {
match unsafe { js_isobject((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if stack item is an array
pub fn isarray(self: &State, idx: i32) -> bool {
match unsafe { js_isarray((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if stack item is callable
pub fn iscallable(self: &State, idx: i32) -> bool {
match unsafe { js_iscallable((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if stack item is regexp
pub fn isregexp(self: &State, idx: i32) -> bool {
match unsafe { js_isregexp((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Push undefined primitive value onto the stack
pub fn pushundefined(self: &State) {
unsafe { js_pushundefined((*self.ptr).state) };
}
/// Push null primitive value onto the stack
pub fn pushnull(self: &State) {
unsafe { js_pushnull((*self.ptr).state) };
}
/// Push boolean primitive value onto the stack
pub fn pushboolean(self: &State, value: bool) {
match value {
false => unsafe { js_pushboolean((*self.ptr).state, 0) },
true => unsafe { js_pushboolean((*self.ptr).state, 1) }
}
}
/// Push number primitive value onto the stack
pub fn pushnumber(self: &State, value: f64) {
unsafe { js_pushnumber((*self.ptr).state, value) }
}
/// Push string primitive value onto the stack
pub fn pushstring(self: &State, value: &str) {
unsafe { js_pushstring((*self.ptr).state, value.to_cstring().unwrap().as_ptr()) }
}
/// Test if object on stack has named property
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
/// state.newobject();
/// state.pushnumber(1.234);
/// state.setproperty(0, "value");
///
/// if state.hasproperty(0, "value") {
/// println!("Value: {:?}", state.tostring(1).unwrap());
/// }
///
pub fn hasproperty(self: &State, idx: i32, name: &str) -> bool {
match unsafe { js_hasproperty((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr()) } {
0 => false,
_ => true
}
}
/// Pop the value on top of stack and assigns it to named property
pub fn setproperty(self: &State, idx: i32, name: &str) {
unsafe { js_setproperty((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr()) };
}
/// Push the value of named property of object on top of stack
pub fn getproperty(self: &State, idx: i32, name: &str) {
unsafe { js_getproperty((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr()) };
}
/// Define named property of object
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newobject();
/// state.pushstring("A value");
/// state.defproperty(0, "value", mujs::JS_DONTCONF);
///
/// ```
pub fn defproperty(self: &State, idx: i32, name: &str, attrs: PropertyAttributes) {
unsafe { js_defproperty((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr(), attrs.bits) };
}
/// Define a getter and setter attribute og a property of object on stack
///
/// Pop the two getter and setter functions from the stack. Use
/// null instead of a function object if you want to leave any of
/// the functions unset.
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newobject();
///
/// state.newfunction( move |x| { x.pushnumber(25.0) }, "age.getter", 0);
/// state.pushnull();
///
/// state.defaccessor(0, "age", mujs::JS_DONTENUM);
///
/// ```
pub fn defaccessor(self: &State, idx: i32, name: &str, attrs: PropertyAttributes) {
unsafe { js_defaccessor((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr(), attrs.bits) };
}
/// Delete named property of object
pub fn delproperty(self: &State, idx: i32, name: &str) {
unsafe { js_delproperty((*self.ptr).state, idx, name.to_cstring().unwrap().as_ptr()) };
}
/// Get length of an array
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let state = mujs::State::new(mujs::JS_STRICT);
///
/// assert!(state.loadstring("script", "[1,2,3,4,5,6]").is_ok());
/// state.pushundefined();
/// assert!(state.call(0).is_ok());
///
/// println!("Length: {:?}", state.getlength(0));
///
/// ```
pub fn getlength(self: &State, idx: i32) -> i32 {
unsafe { js_getlength((*self.ptr).state, idx) }
}
/// Set length of an array
pub fn setlength(self: &State, idx: i32, length: i32) {
unsafe { js_setlength((*self.ptr).state, idx, length) }
}
/// Test if array has specified index
pub fn hasindex(self: &State, idx: i32, i: i32) -> bool {
match unsafe { js_hasindex((*self.ptr).state, idx, i) } {
0 => false,
_ => true
}
}
/// Get item from array index on top of stack
pub fn getindex(self: &State, idx: i32, i: i32) {
unsafe { js_getindex((*self.ptr).state, idx, i) }
}
/// Set array index with item on top of stack
pub fn setindex(self: &State, idx: i32, i: i32) {
unsafe { js_setindex((*self.ptr).state, idx, i) }
}
/// Delete item from array at specified index
pub fn delindex(self: &State, idx: i32, i: i32) {
unsafe { js_delindex((*self.ptr).state, idx, i) }
}
/// Push object representing the global environment record
pub fn pushglobal(self: &State) {
unsafe { js_pushglobal((*self.ptr).state) }
}
/// Get named global variable
pub fn getglobal(self: &State, name: &str) {
unsafe { js_getglobal((*self.ptr).state, name.to_cstring().unwrap().as_ptr()) }
}
/// Set named variable with object on top of stack
pub fn setglobal(self: &State, name: &str) {
unsafe { js_setglobal((*self.ptr).state, name.to_cstring().unwrap().as_ptr()) }
}
/// Define named global variable
pub fn defglobal(self: &State, name: &str, attrs: PropertyAttributes) {
unsafe { js_defglobal((*self.ptr).state, name.to_cstring().unwrap().as_ptr(), attrs.bits) }
}
extern fn _newcfunction_trampoline(js: *const c_void) {
let s_ptr: *const State = unsafe { js_getcontext(js) as *const State };
let state: &State = unsafe{ &(*s_ptr) };
let cb_ptr = unsafe {
js_currentfunction(js);
js_getproperty(js, -1, CLOSURE_TAG.to_cstring().unwrap().as_ptr());
js_touserdata(js, -1, CLOSURE_TAG.to_cstring().unwrap().as_ptr())
};
let func: &mut Box<FnMut(&State)> = unsafe { std::mem::transmute(cb_ptr) };
func(state);
}
extern fn _finalize(_: *const c_void, _: *mut c_void) {
}
/// push a function object wrapping a rustc closure
///
/// # Examples
///
/// ```
/// use mujs;
///
/// let mut state = mujs::State::new(mujs::JS_STRICT);
///
/// state.newfunction( move |x| {
/// println!("Hello World!");
/// }, "myfunc", 0);
/// state.setglobal("myfunc");
///
/// state.getglobal("myfunc");
/// state.pushundefined();
/// state.call(0);
/// ```
pub fn newfunction<F>(self: &State, func: F, name: &str, length: i32)
where F: FnMut(&State),
F: 'static
{
let cb: Box<Box<FnMut(&State)>> = Box::new(Box::new(func));
let cb_ptr = Box::into_raw(cb) as *mut _;
unsafe {
js_newcfunction((*self.ptr).state, Some(::State::_newcfunction_trampoline),
name.to_cstring().unwrap().as_ptr(),length);
js_pushnull((*self.ptr).state);
js_newuserdata((*self.ptr).state,CLOSURE_TAG.to_cstring().unwrap().as_ptr(),
cb_ptr, Some(::State::_finalize));
js_defproperty((*self.ptr).state, -2, CLOSURE_TAG.to_cstring().unwrap().as_ptr(),
(::JS_READONLY | ::JS_DONTENUM | ::JS_DONTCONF).bits);
};
}
/// Test if item on stack is defined
pub fn isdefined(self: &State, idx: i32) -> bool {
match unsafe { js_isdefined((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is undefined
pub fn isundefined(self: &State, idx: i32) -> bool {
match unsafe { js_isundefined((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is null
pub fn isnull(self: &State, idx: i32) -> bool {
match unsafe { js_isnull((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is boolean
pub fn isboolean(self: &State, idx: i32) -> bool {
match unsafe { js_isboolean((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is number
pub fn isnumber(self: &State, idx: i32) -> bool {
match unsafe { js_isnumber((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is string
pub fn isstring(self: &State, idx: i32) -> bool {
match unsafe { js_isstring((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Test if item on stack is primitive
pub fn isprimitive(self: &State, idx: i32) -> bool {
match unsafe { js_isprimitive((*self.ptr).state, idx) } {
0 => false,
_ => true
}
}
/// Convert value on stack to string
pub fn tostring(self: &State, idx: i32) -> Result<String, String> {
let c_buf: *const c_char = unsafe { js_tostring((*self.ptr).state, idx) };
if c_buf == std::ptr::null() {
return Err("Null string".to_string())
}
Ok(unsafe {
CStr::from_ptr(c_buf).to_string_lossy().into_owned()
})
}
/// Convert value on stack to boolean
pub fn toboolean(self: &State, idx: i32) -> Result<bool, String> {
match unsafe { js_toboolean((*self.ptr).state, idx) } {
0 => Ok(false),
_ => Ok(true)
}
}
/// Convert value on stack to number