MCPcopy Create free account
hub / github.com/Serial-Studio/Serial-Studio / compile

Method compile

app/src/MQTT/PublisherScript.cpp:72–144  ·  view source on GitHub ↗

* @brief Compiles the user script in the chosen language. */

Source from the content-addressed store, hash-verified

70 * @brief Compiles the user script in the chosen language.
71 */
72bool MQTT::PublisherScript::compile(const QString& source, int language, QString& errorOut)
73{
74 m_loaded = false;
75 m_language = language;
76
77 if (source.trimmed().isEmpty()) {
78 errorOut = QStringLiteral("Script is empty.");
79 return false;
80 }
81
82 if (language == Lua) {
83 destroyLua();
84 resetJs();
85
86 m_luaState = luaL_newstate();
87 if (!m_luaState) {
88 errorOut = QStringLiteral("Failed to create Lua state.");
89 return false;
90 }
91
92 openSafeLibs(m_luaState);
93 DataModel::installLuaCompat(m_luaState);
94
95 const QByteArray utf8 = source.toUtf8();
96 if (luaL_dostring(m_luaState, utf8.constData()) != LUA_OK) {
97 errorOut = QString::fromUtf8(lua_tostring(m_luaState, -1));
98 destroyLua();
99 return false;
100 }
101
102 lua_getglobal(m_luaState, "mqtt");
103 const bool hasFn = lua_isfunction(m_luaState, -1);
104 lua_pop(m_luaState, 1);
105 if (!hasFn) {
106 errorOut = QStringLiteral("Script must define a function named 'mqtt(frame)'.");
107 destroyLua();
108 return false;
109 }
110
111 m_loaded = true;
112 return true;
113 }
114
115 destroyLua();
116 if (!m_jsEngine) {
117 m_jsEngine = std::make_unique<QJSEngine>();
118 m_jsEngine->installExtensions(QJSEngine::ConsoleExtension
119 | QJSEngine::GarbageCollectionExtension);
120 m_jsWatchdog = std::make_unique<DataModel::JsWatchdog>(
121 m_jsEngine.get(), kRuntimeWatchdogMs, QStringLiteral("MQTT script"));
122 }
123
124 m_jsFunction = QJSValue();
125
126 const QString wrapped = QStringLiteral("(function(){\n%1\n})();").arg(source);
127 const auto result = m_jsEngine->evaluate(wrapped, QStringLiteral("mqtt-script.js"));
128 if (result.isError()) {
129 errorOut = QStringLiteral("Line %1: %2")

Callers 1

Calls 7

luaL_newstateFunction · 0.85
lua_getglobalFunction · 0.85
isEmptyMethod · 0.80
isErrorMethod · 0.80
openSafeLibsFunction · 0.70
getMethod · 0.45
evaluateMethod · 0.45

Tested by

no test coverage detected