-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathjavascript.hpp
85 lines (67 loc) · 2.78 KB
/
javascript.hpp
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
/* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*/
// This encapsulates QuickJS, the same Javascript engine used in VCV Prototype.
// This is very experimental, and done in the simplest way that would accomplish my goals,
// since the documentation of quickjs is mostly "Just read the uncommented headers lol".
//
// I plan to keep it this simple until I run into an obvious pain point.
//
// In general, the big idea is to load snippets from javascript-libraries,
// craft a string to call a function and assign it to a variable,
// read that variable, and use JSON for interchange because eh that's as
// far as I'm willing to figure out this thing.
//
// Spinning up a new runtime on demand is basically instant, but this stuff is
// just to do one-off data processing. Don't go around writing an oscillator with it.
//
// Jerry Sievert's fork of Quickjs (and advice!) were used: https://github.com/JerrySievert/QuickJS
// See makefile for how to add it to a project.
#pragma once
#include <rack.hpp>
// QuickJS always throws a warning here, but it works.
#include "QuickJS/quickjs.h"
namespace Javascript {
struct Runtime {
JSRuntime *runtime = NULL;
JSContext *context = NULL;
JSValue argv;
JSValue globalObject;
Runtime () {
runtime = JS_NewRuntime();
context = JS_NewContext(runtime);
argv = JS_NewObject(context);
globalObject = JS_GetGlobalObject(context);
}
~Runtime () {
JS_FreeValue(context, argv);
JS_FreeValue(context, globalObject);
if (context) JS_FreeContext(context);
if (runtime) JS_FreeRuntime(runtime);
}
void evaluateString(std::string script) {
JSValue evaluatedScript = JS_Eval(context, script.c_str(), script.size(), "Evaluated script", 0);
JS_FreeValue(context, evaluatedScript);
}
const char* readVariableAsChar(const char* variable){
JSValue value = JS_GetPropertyStr(context, globalObject, variable);
const char *readValue = JS_ToCString(context, value);
JS_FreeValue(context, value);
return readValue;
}
int32_t readVariableAsInt32(const char* variable){
int32_t readValue = 0;
JSValue value = JS_GetPropertyStr(context, globalObject, variable);
JS_ToInt32(context, &readValue, value);
JS_FreeValue(context, value);
return readValue;
}
};
} // Javascript