-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello.cpp
70 lines (58 loc) · 1.68 KB
/
hello.cpp
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
#include "jsapi.h"
#include "js/Initialization.h"
static JSClassOps global_ops = {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
JS_GlobalObjectTraceHook
};
/* The class of the global object. */
static JSClass global_class = {
"global",
JSCLASS_GLOBAL_FLAGS,
&global_ops
};
int main(int argc, const char *argv[])
{
JS_Init();
JSContext *cx = JS_NewContext(8L * 1024 * 1024);
if (!cx)
return 1;
if (!JS::InitSelfHostedCode(cx))
return 1;
{ // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go
// out of scope before we JS_DestroyContext.
JSAutoRequest ar(cx); // In practice, you would want to exit this any
// time you're spinning the event loop
JS::CompartmentOptions options;
JS::RootedObject global(cx, JS_NewGlobalObject(cx, &global_class, nullptr, JS::FireOnNewGlobalHook, options));
if (!global)
return 1;
JS::RootedValue rval(cx);
{ // Scope for JSAutoCompartment
JSAutoCompartment ac(cx, global);
JS_InitStandardClasses(cx, global);
const char *script = "'hello'+'world, it is '+new Date()";
const char *filename = "noname";
int lineno = 1;
JS::CompileOptions opts(cx);
opts.setFileAndLine(filename, lineno);
bool ok = JS::Evaluate(cx, opts, script, strlen(script), &rval);
if (!ok)
return 1;
}
JSString *str = rval.toString();
printf("%s\n", JS_EncodeString(cx, str));
}
JS_DestroyContext(cx);
JS_ShutDown();
return 0;
}