-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathboilerplate.cpp
More file actions
69 lines (54 loc) · 2.01 KB
/
Copy pathboilerplate.cpp
File metadata and controls
69 lines (54 loc) · 2.01 KB
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
#include <jsapi.h>
#include <js/Initialization.h>
#include <js/Exception.h>
#include "boilerplate.h"
// This file contains boilerplate code used by a number of examples. Ideally
// this should eventually become part of SpiderMonkey itself.
// Create a simple Global object. A global object is the top-level 'this' value
// in a script and is required in order to compile or execute JavaScript.
JSObject* boilerplate::CreateGlobal(JSContext* cx) {
JS::RealmOptions options;
static JSClass BoilerplateGlobalClass = {
"BoilerplateGlobal", JSCLASS_GLOBAL_FLAGS, &JS::DefaultGlobalClassOps};
return JS_NewGlobalObject(cx, &BoilerplateGlobalClass, nullptr,
JS::FireOnNewGlobalHook, options);
}
// Helper to read current exception and dump to stderr.
//
// NOTE: This must be called with a JSAutoRealm (or equivalent) on the stack.
void boilerplate::ReportAndClearException(JSContext* cx) {
JS::ExceptionStack stack(cx);
if (!JS::StealPendingExceptionStack(cx, &stack)) {
fprintf(stderr, "Uncatchable exception thrown, out of memory or something");
exit(1);
}
JS::ErrorReportBuilder report(cx);
if (!report.init(cx, stack, JS::ErrorReportBuilder::WithSideEffects)) {
fprintf(stderr, "Couldn't build error report");
exit(1);
}
JS::PrintError(stderr, report, false);
}
// Initialize the JS environment, create a JSContext and run the example
// function in that context. By default the self-hosting environment is
// initialized as it is needed to run any JavaScript). If the 'initSelfHosting'
// argument is false, we will not initialize self-hosting and instead leave
// that to the caller.
bool boilerplate::RunExample(bool (*task)(JSContext*), bool initSelfHosting) {
if (!JS_Init()) {
return false;
}
JSContext* cx = JS_NewContext(JS::DefaultHeapMaxBytes);
if (!cx) {
return false;
}
if (initSelfHosting && !JS::InitSelfHostedCode(cx)) {
return false;
}
if (!task(cx)) {
return false;
}
JS_DestroyContext(cx);
JS_ShutDown();
return true;
}