boop-gtk 1.6.0

A scriptable scratchpad for developers Port of @IvanMathy's Boop to GTK
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
use crate::{scripts::Scripts, PROJECT_DIRS};
use dirty2::Dirty;
use rusty_v8 as v8;
use simple_error::SimpleError;
use std::{
    cell::RefCell,
    convert::TryFrom,
    env,
    error::Error,
    fmt::{Debug, Display},
    fs::File,
    io::Read,
    rc::Rc,
    sync::Once,
    time::Instant,
};

static BOOP_WRAPPER_START: &str = "
/***********************************
*     Start of Boop's wrapper      *
***********************************/
            
(function() {
    var module = {
        exports: {}
    };
            
    const moduleWrapper = (function (exports, module) {

/***********************************
*      End of Boop's wrapper      *
***********************************/

";

static BOOP_WRAPPER_END: &str = "
            
/***********************************
*     Start of Boop's wrapper      *
***********************************/
            
    }).apply(module.exports, [module.exports, module]);

    return module.exports;
})();
            
/***********************************
*      End of Boop's wrapper      *
***********************************/
";

static INIT_V8: Once = Once::new();

pub struct Executor {
    isolate: v8::OwnedIsolate,
}

impl Debug for Executor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Executor{{}}")
    }
}

struct ExecutorState {
    global_context: Option<v8::Global<v8::Context>>,
    main_function: Option<v8::Global<v8::Function>>,
}

#[derive(Clone, Debug, Default)]
pub struct ExecutionStatus {
    // true if text was selected when execution began
    is_text_selected: bool,

    info: Option<String>,
    error: Option<String>,

    insert: Vec<String>,
    full_text: Dirty<String>,
    text: Dirty<String>,
    selection: Dirty<String>,
}

impl ExecutionStatus {
    fn reset(&mut self) {
        self.info = None;
        self.error = None;
        self.insert.clear();
        self.full_text.write().clear();
        Dirty::clear(&mut self.full_text);
        self.text.write().clear();
        Dirty::clear(&mut self.text);
    }

    pub fn info(&self) -> Option<&String> {
        self.info.as_ref()
    }

    pub fn error(&self) -> Option<&String> {
        self.error.as_ref()
    }

    pub fn into_replacement(self) -> TextReplacement {
        // not quite sure what the correct behaviour here should be
        // right now the order of presidence is:
        // 0. insertion
        // 1. fullText
        // 2. selection
        // 3. text (with select)
        // 4. text (without selection)
        // TODO: move into ExecutionStatus
        if !self.insert.is_empty() {
            info!("found insertion");
            TextReplacement::Insert(self.insert)
        } else if self.full_text.dirty() {
            info!("found full_text replacement");
            TextReplacement::Full(self.full_text.unwrap())
        } else if self.selection.dirty() {
            info!("found selection replacement");
            TextReplacement::Selection(self.selection.unwrap())
        } else if self.is_text_selected && self.text.dirty() {
            info!("found text (with selection) replacement");
            TextReplacement::Selection(self.text.unwrap())
        } else if self.text.dirty() {
            info!("found text (without selection) replacement");
            TextReplacement::Full(self.text.unwrap())
        } else {
            TextReplacement::None
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum TextReplacement {
    Full(String),
    Selection(String),
    Insert(Vec<String>),
    None,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct JSException {
    pub exception_str: String,
    pub resource_name: Option<String>,
    pub source_line: Option<String>,
    pub line_number: Option<usize>,
    pub columns: Option<(usize, usize)>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ExecutorError {
    SourceExceedsMaxLength,
    Compile(JSException),
    Execute(JSException),
    NoMain,
}

impl Display for ExecutorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExecutorError::SourceExceedsMaxLength => write!(f, "source exceeds max length"),
            ExecutorError::Compile(exception) => write!(f, "JS compile exception: {:?}", exception),
            ExecutorError::Execute(exception) => {
                write!(f, "JS execution exception: {:?}", exception)
            }
            ExecutorError::NoMain => write!(f, "no main function"),
        }
    }
}

impl Error for ExecutorError {}

impl Executor {
    pub fn new(source: &str) -> Result<Self, ExecutorError> {
        INIT_V8.call_once(|| {
            let start = Instant::now();

            // initialize V8
            let platform = v8::new_default_platform().unwrap();
            v8::V8::initialize_platform(platform);
            v8::V8::initialize();

            info!("V8 initialized in {:?}", start.elapsed());
        });

        // set up execution context
        let mut isolate = {
            let start = Instant::now();

            let isolate = v8::Isolate::new(Default::default());
            info!("isolate initialized in {:?}", start.elapsed());

            isolate
        };
        let (global_context, main_function) = {
            let scope = &mut v8::HandleScope::new(&mut isolate);
            // let context = v8::Context::new(scope);
            let (context, main_function) = Executor::initialize_context(source, scope)?;
            (v8::Global::new(scope, context), main_function)
        };

        // set status slot, stores execution infomation
        let status_slot: Rc<RefCell<ExecutionStatus>> =
            Rc::new(RefCell::new(ExecutionStatus::default()));
        isolate.set_slot(status_slot);

        // set state slot, stores v8 details
        let state_slot: Rc<RefCell<ExecutorState>> = Rc::new(RefCell::new(ExecutorState {
            global_context: Some(global_context),
            main_function: Some(main_function),
        }));
        isolate.set_slot(state_slot);

        Ok(Executor { isolate })
    }

    // load source code from internal files or external filesystem depending on the path
    fn load_raw_source(path: String) -> Result<String, SimpleError> {
        if path.starts_with("@boop/") {
            // script is internal

            let internal_path = path.replace("@boop/", "lib/");
            info!(
                "found internal script, real path: #BINARY#/{}",
                internal_path
            );

            let raw_source = String::from_utf8(
                Scripts::get(&internal_path)
                    .ok_or_else(|| {
                        SimpleError::new(format!("no internal script with path \"{}\"", path))
                    })?
                    .to_vec(),
            )
            .map_err(|e| SimpleError::with("problem with file encoding", e))?;

            return Ok(raw_source);
        }

        let mut external_path = if cfg!(test) {
            env::temp_dir()
        } else {
            let mut path = PROJECT_DIRS.config_dir().to_path_buf();
            path.push("scripts");
            path
        };
        external_path.push(&path);

        info!(
            "found external script, real path: {}",
            external_path.display()
        );

        let mut raw_source = String::new();
        File::open(external_path)
            .map_err(|e| SimpleError::with(&format!("could not open \"{}\"", path), e))?
            .read_to_string(&mut raw_source)
            .map_err(|e| SimpleError::with("problem reading file", e))?;

        Ok(raw_source)
    }

    fn initialize_context<'s>(
        source: &str,
        scope: &mut v8::HandleScope<'s, ()>,
    ) -> Result<(v8::Local<'s, v8::Context>, v8::Global<v8::Function>), ExecutorError> {
        let scope = &mut v8::EscapableHandleScope::new(scope);
        let context = v8::Context::new(scope);
        let global = context.global(scope);
        let scope = &mut v8::ContextScope::new(scope, context);

        let require_key =
            v8::String::new(scope, "require").expect("failed to created 'require' string");
        let require_val = v8::Function::new(scope, Executor::global_require)
            .expect("failed to created require function");
        global.set(scope, require_key.into(), require_val.into());

        // complile and run script
        let code = v8::String::new(scope, source).ok_or(ExecutorError::SourceExceedsMaxLength)?;

        let tc_scope = &mut v8::TryCatch::new(scope);
        let compiled_script = v8::Script::compile(tc_scope, code, None)
            .ok_or_else(|| {
                Executor::extract_exception(tc_scope)
                    .expect("exception occored but no exception was caught")
            })
            .map_err(ExecutorError::Compile)?;

        compiled_script
            .run(tc_scope)
            .ok_or_else(|| {
                Executor::extract_exception(tc_scope)
                    .expect("exception occored but no exception was caught")
            })
            .map_err(ExecutorError::Execute)?;

        // extract main function
        let main_key =
            v8::String::new(tc_scope, "main").expect("failed to create JS string 'main'");
        let main_function =
            v8::Local::<v8::Function>::try_from(global.get(tc_scope, main_key.into()).unwrap())
                .map_err(|_e| ExecutorError::NoMain)?;
        let main_function = v8::Global::new(tc_scope, main_function);

        Ok((tc_scope.escape(context), main_function))
    }

    pub fn execute(
        &mut self,
        full_text: &str,
        selection: Option<&str>,
    ) -> Result<ExecutionStatus, ExecutorError> {
        // setup execution status
        {
            let status_slot = self
                .isolate
                .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
                .expect("failed to get mutable access to status slot");

            let mut status = status_slot.borrow_mut();

            status.reset();
            *status.full_text.write() = full_text.to_string();
            status.full_text.clear();
            *status.text.write() = selection.unwrap_or(full_text).to_string();
            status.text.clear();
            *status.selection.write() = selection.unwrap_or("").to_string();
            status.selection.clear();
        }

        // prepare payload and execute main

        // TODO: use ObjectTemplate, problem: rusty_v8 doesn't have set_accessor_with_setter or even set_accessor for
        // object templates
        {
            let state_slot = self
                .isolate
                .get_slot_mut::<Rc<RefCell<ExecutorState>>>()
                .expect("failed to get mutable access to state slot")
                .clone();
            let state_slot = state_slot.borrow();

            let context = state_slot
                .global_context
                .as_ref()
                .expect("global_context is not initalizied");
            let scope = &mut v8::HandleScope::with_context(&mut self.isolate, context);

            // payload is the object passed into function main
            let payload = v8::Object::new(scope);

            // value: isSelection
            {
                let is_selection_key = v8::String::new(scope, "isSelection")
                    .expect("failed to construct 'isSelection' JS string");

                let is_selection_value = v8::Boolean::new(scope, selection.is_some());

                payload
                    .set(scope, is_selection_key.into(), is_selection_value.into())
                    .expect("failed to set 'isSelection' value");
            }

            // getter/setters: full_text, text, selection
            {
                let full_text_key = v8::String::new(scope, "fullText")
                    .expect("failed to construct 'fullText' JS string");
                let text_key =
                    v8::String::new(scope, "text").expect("failed to construct 'text' JS string");
                let selection_key = v8::String::new(scope, "selection")
                    .expect("failed to construct 'selection' JS string");

                payload
                    .set_accessor_with_setter(
                        scope,
                        full_text_key.into(),
                        Executor::payload_full_text_getter,
                        Executor::payload_full_text_setter,
                    )
                    .expect("failed to set 'full_text' accessor");
                payload
                    .set_accessor_with_setter(
                        scope,
                        text_key.into(),
                        Executor::payload_text_getter,
                        Executor::payload_text_setter,
                    )
                    .expect("failed to set 'text' accessor");
                payload
                    .set_accessor_with_setter(
                        scope,
                        selection_key.into(),
                        Executor::payload_selection_getter,
                        Executor::payload_selection_setter,
                    )
                    .expect("failed to set 'selection' accessor");
            }

            // functions: post_info, post_error, insert

            let post_info_key =
                v8::String::new(scope, "postInfo").expect("failed to create JS string 'postInfo'");
            let post_error_key = v8::String::new(scope, "postError")
                .expect("failed to create JS string 'postError'");
            let insert_key =
                v8::String::new(scope, "insert").expect("failed to create JS string 'insert'");

            let post_info_val = v8::Function::new(scope, Executor::payload_post_info)
                .expect("failed to convert post_info function");
            let post_error_val = v8::Function::new(scope, Executor::payload_post_error)
                .expect("failed to create post_error function");
            let insert_val = v8::Function::new(scope, Executor::payload_insert)
                .expect("failed to create payload_insert function");

            payload
                .set(scope, post_info_key.into(), post_info_val.into())
                .expect("failed to set 'post_info' function");
            payload
                .set(scope, post_error_key.into(), post_error_val.into())
                .expect("failed to set 'post_error' function");
            payload
                .set(scope, insert_key.into(), insert_val.into())
                .expect("failed to set 'insert' function");

            let main_function = state_slot
                .main_function
                .as_ref()
                .expect("main_function not initialized")
                .get(scope);
            let escape_scope = &mut v8::EscapableHandleScope::new(scope);
            let tc_scope = &mut v8::TryCatch::new(escape_scope);

            main_function
                .call(tc_scope, payload.into(), &[payload.into()])
                .ok_or_else(|| {
                    ExecutorError::Execute(
                        Executor::extract_exception(tc_scope)
                            .expect("exception occored but no exception was caught"),
                    )
                })?;
        }

        // extract execution status
        {
            let status_slot = self
                .isolate
                .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
                .expect("failed to get mutable access to status slot");

            let status = (status_slot).borrow();

            Ok(status.clone())
        }
    }

    fn extract_exception(
        tc_scope: &mut v8::TryCatch<v8::EscapableHandleScope>,
    ) -> Option<JSException> {
        let exception_str = tc_scope
            .exception()?
            .to_string(tc_scope)
            .expect("exception is not a string")
            .to_rust_string_lossy(tc_scope);

        let message = match tc_scope.message() {
            Some(message) => message,
            None => {
                return Some(JSException {
                    exception_str,
                    ..Default::default()
                });
            }
        };

        Some(JSException {
            exception_str,
            resource_name: message
                .get_script_resource_name(tc_scope)
                .and_then(|r| r.to_string(tc_scope))
                .map(|r| r.to_rust_string_lossy(tc_scope)),
            source_line: message
                .get_source_line(tc_scope)
                .map(|l| l.to_rust_string_lossy(tc_scope)),
            line_number: message.get_line_number(tc_scope),
            columns: Some((message.get_start_column(), message.get_end_column())),
        })
    }

    fn global_require(
        scope: &mut v8::HandleScope<'_>,
        args: v8::FunctionCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let code = args
            .get(0)
            .to_string(scope)
            .ok_or_else(|| SimpleError::new("argument to require is not a string"))
            .map(|string_arg| string_arg.to_rust_string_lossy(scope))
            .map(|mut path| {
                if !path.ends_with(".js") {
                    path.push_str(".js");
                }
                info!("loading {}", path);
                path
            })
            // grab the source
            .and_then(Executor::load_raw_source)
            // add boop wrapper
            .map(|raw_source| [BOOP_WRAPPER_START, &raw_source, BOOP_WRAPPER_END].concat())
            // create JS string
            .and_then(|source| {
                v8::String::new(scope, &source)
                    .ok_or_else(|| SimpleError::new("failed to create JS string from source"))
            });

        if let Err(err) = code {
            let exception_str = v8::String::new(scope, &err.to_string())
                .expect("failed to create string for exception");
            let exception = v8::Exception::error(scope, exception_str);

            scope.throw_exception(exception);

            return;
        }

        let code = code.unwrap();

        let export = v8::Script::compile(scope, code, None)
            .ok_or_else(|| SimpleError::new("failed to compile JS"))
            .and_then(|script| {
                script
                    .run(scope)
                    .ok_or_else(|| SimpleError::new("failed to execute JS"))
            });

        match export {
            Ok(export) => rv.set(export),
            Err(err) => error!("failed to require script: {}", err),
        }
    }

    fn payload_post_info(
        scope: &mut v8::HandleScope<'_>,
        args: v8::FunctionCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let info = args
            .get(0)
            .to_string(scope)
            .expect("failed to convert argument to post_info to string")
            .to_rust_string_lossy(scope);

        scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get mutable access to status slot")
            .borrow_mut()
            .info
            .replace(info);

        let undefined = v8::undefined(scope).into();
        rv.set(undefined)
    }

    fn payload_post_error(
        scope: &mut v8::HandleScope<'_>,
        args: v8::FunctionCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let error = args
            .get(0)
            .to_string(scope)
            .expect("failed to convert argument to post_error to string")
            .to_rust_string_lossy(scope);

        scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get mutable access to status slot")
            .borrow_mut()
            .error
            .replace(error);

        let undefined = v8::undefined(scope).into();
        rv.set(undefined)
    }

    fn payload_insert(
        scope: &mut v8::HandleScope<'_>,
        args: v8::FunctionCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let insert = args
            .get(0)
            .to_string(scope)
            .expect("failed to convert insert argument to string")
            .to_rust_string_lossy(scope);

        scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get mutable access to status slot")
            .borrow_mut()
            .insert
            .push(insert);

        let undefined = v8::undefined(scope).into();
        rv.set(undefined)
    }

    fn payload_full_text_getter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        _args: v8::PropertyCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let full_text = scope
            .get_slot::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get status slot")
            .borrow()
            .full_text
            .read()
            .clone();

        rv.set(
            v8::String::new(scope, &full_text)
                .expect("failed to construct JS string from full_text")
                .into(),
        );
    }

    fn payload_full_text_setter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        value: v8::Local<'_, v8::Value>,
        _args: v8::PropertyCallbackArguments<'_>,
    ) {
        let new_value = value
            .to_string(scope)
            .expect("failed to convert value to string")
            .to_rust_string_lossy(scope);

        info!("setting full_text ({} bytes)", new_value.len());

        let slot = scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get mutable access to status slot");

        let mut slot = slot.borrow_mut();

        let full_text = slot.full_text.write();

        *full_text = new_value;
    }

    fn payload_text_getter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        _args: v8::PropertyCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let text = scope
            .get_slot::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get status slot")
            .borrow()
            .text
            .read()
            .clone();

        rv.set(
            v8::String::new(scope, &text)
                .expect("faield to create JS string from text")
                .into(),
        );
    }

    fn payload_text_setter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        value: v8::Local<'_, v8::Value>,
        _args: v8::PropertyCallbackArguments<'_>,
    ) {
        let new_value = value
            .to_string(scope)
            .expect("failed to convert value to string")
            .to_rust_string_lossy(scope);

        info!("setting text ({} bytes)", new_value.len());

        let slot = scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("faield to get mutable access status slot");

        let mut slot = slot.borrow_mut();

        let text = slot.text.write();

        *text = new_value;
    }

    fn payload_selection_getter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        _args: v8::PropertyCallbackArguments<'_>,
        mut rv: v8::ReturnValue<'_>,
    ) {
        let selection = scope
            .get_slot::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get status slot")
            .borrow()
            .selection
            .read()
            .clone();

        rv.set(
            v8::String::new(scope, &selection)
                .expect("problem constructing JS string")
                .into(),
        );
    }

    fn payload_selection_setter(
        scope: &mut v8::HandleScope<'_>,
        _key: v8::Local<'_, v8::Name>,
        value: v8::Local<'_, v8::Value>,
        _args: v8::PropertyCallbackArguments<'_>,
    ) {
        let new_value = value
            .to_string(scope)
            .expect("failed to convert value to string")
            .to_rust_string_lossy(scope);

        info!("setting selection ({} bytes)", new_value.len());

        let slot = scope
            .get_slot_mut::<Rc<RefCell<ExecutionStatus>>>()
            .expect("failed to get mutable access to status slot");

        let mut slot = slot.borrow_mut();

        let selection = slot.selection.write();

        *selection = new_value;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    extern crate tempfile;
    use std::io::prelude::*;

    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    #[test]
    fn test_error_new_big_string() {
        init();
        let source = "0".repeat(1 << 29);
        let result = Executor::new(&source);
        assert_eq!(result.unwrap_err(), ExecutorError::SourceExceedsMaxLength);
    }

    #[test]
    fn test_error_new_compile() {
        init();
        let source = "this won't compile!";
        let result = Executor::new(&source);
        assert_eq!(
            result.unwrap_err(),
            ExecutorError::Compile(JSException {
                exception_str: "SyntaxError: Unexpected identifier".to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some("this won\'t compile!".to_string()),
                line_number: Some(1),
                columns: Some((5, 8)),
            })
        );
    }

    #[test]
    fn test_error_new_execute() {
        init();
        let source = r#"throw "Woo! Exception!";"#;
        let result = Executor::new(source);
        assert_eq!(
            result.unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str: "Woo! Exception!".to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some("throw \"Woo! Exception!\";".to_string()),
                line_number: Some(1),
                columns: Some((0, 1))
            })
        );
    }

    #[test]
    fn test_error_execute_no_main() {
        init();
        let source = r#"let i = 100;"#;

        assert_eq!(Executor::new(source).unwrap_err(), ExecutorError::NoMain)
    }

    #[test]
    fn test_error_execute_exception() {
        init();
        let source = r#"function main() {
            throw "(╯°□°)╯︵ ┻━┻";
        }"#;

        assert_eq!(
            Executor::new(source)
                .unwrap()
                .execute("full_text", None)
                .unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str: "(╯°□°)╯︵ ┻━┻".to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some("            throw \"(╯°□°)╯︵ ┻━┻\";".to_string()),
                line_number: Some(2),
                columns: Some((12, 13))
            })
        );
    }

    #[test]
    fn test_error_require_internal_script() {
        init();
        let source = r#"function main() {
            let foo = require("@boop/non-existant");
        }"#;

        assert_eq!(
            Executor::new(source)
                .unwrap()
                .execute("full_text", None)
                .unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str: "Error: no internal script with path \"@boop/non-existant.js\""
                    .to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some(
                    "            let foo = require(\"@boop/non-existant\");".to_string()
                ),
                line_number: Some(2),
                columns: Some((22, 23))
            }),
        );
    }

    #[test]
    fn test_error_require_script_missing() {
        init();
        let source = r#"function main() {
            let foo = require("this-script-does-not-exist.js");
        }"#;

        assert_eq!(
            Executor::new(source)
                .unwrap()
                .execute("full_text", None)
                .unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str:
                    if cfg!(windows) {
                        "Error: could not open \"this-script-does-not-exist.js\", The system cannot find the file specified. (os error 2)"
                    } else {
                        "Error: could not open \"this-script-does-not-exist.js\", No such file or directory (os error 2)"
                    }.to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some("            let foo = require(\"this-script-does-not-exist.js\");".to_string()),
                line_number: Some(2),
                columns: Some((22, 23))
            }),
        );
    }

    #[test]
    fn test_error_require_script_compile_error() {
        init();

        let mut file = tempfile::Builder::new().suffix(".js").tempfile().unwrap();
        write!(file, r#"┻━┻ ︵ ¯\(ツ)/¯ ︵ ┻━┻"#).unwrap();

        let file_name = file.path().file_name().unwrap().to_str().unwrap();

        let source = format!(
            "function main() {{
                let foo = require(\"{}\");
            }}",
            file_name
        );

        assert_eq!(
            Executor::new(&source)
                .unwrap()
                .execute("full_text", None)
                .unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str: "SyntaxError: Invalid or unexpected token".to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some(r#"┻━┻ ︵ ¯\(ツ)/¯ ︵ ┻━┻"#.to_string()),
                line_number: Some(17),
                columns: Some((0, 0))
            }),
        );
    }

    #[test]
    fn test_error_require_script_execute_error() {
        init();

        let mut file = tempfile::Builder::new().suffix(".js").tempfile().unwrap();
        write!(
            file,
            r#"(function() {{ throw "༼ノຈل͜ຈ༽ノ︵┻━┻"; return 123 }})()"#
        )
        .unwrap();

        let file_name = file.path().file_name().unwrap().to_str().unwrap();

        let source = format!(
            "function main() {{
                let foo = require(\"{}\");
            }}",
            file_name
        );

        assert_eq!(
            Executor::new(&source)
                .unwrap()
                .execute("full_text", None)
                .unwrap_err(),
            ExecutorError::Execute(JSException {
                exception_str: "༼ノຈل\u{35c}ຈ༽ノ︵┻━┻".to_string(),
                resource_name: Some("undefined".to_string()),
                source_line: Some(
                    "(function() { throw \"༼ノຈل\u{35c}ຈ༽ノ︵┻━┻\"; return 123 })()".to_string()
                ),
                line_number: Some(17),
                columns: Some((14, 15))
            })
        )
    }
}