aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/corelib/buildgraph
diff options
context:
space:
mode:
authorChristian Kandeler <christian.kandeler@qt.io>2022-02-21 15:02:31 +0100
committerChristian Kandeler <christian.kandeler@qt.io>2023-02-07 09:20:11 +0000
commit087c22e17721f37490dd2048a567b6a58065d939 (patch)
tree3a04067c29884685fe7189b5c51c1fff82f214d9 /src/lib/corelib/buildgraph
parent4e8f377f1844bbb2f5ed7cb4481d6e30a6335da5 (diff)
Switch JavaScript back-end
Newer clang versions seem to expose serious bugs in QtScript, whose complexity makes it difficult to track them down. We therefore switch to the more light-weight QuickJS, which offers all the features we need (most notably property access interception), as well as good performance. To save some porting effort, we removed the long-deprecated loadFile() and loadExtension() functions. During the porting procedure, we noticed and fixed thread safety issues in artifact access from JS commands. We consider this change important enough to bump the major version, so the next release will be 2.0. Detailed benchmarking data is below. In summary, we see a modest speed- up at the cost of a similarly modest increase in memory consumption (with the exception of project resolving on macOS, which has become a bit slower). Importantly, the increase does not rise with project size, as the comparison of qbs vs Qt Creator shows. Output of qbs_benchmarker on Linux with qbs as test project: ========== Performance data for Resolving ========== Old instruction count: 12870602895 New instruction count: 11923459780 Relative change: -8 % Old peak memory usage: 61775848 Bytes New peak memory usage: 67583424 Bytes Relative change: +9 % ========== Performance data for Rule Execution ========== Old instruction count: 4074062223 New instruction count: 3887473574 Relative change: -5 % Old peak memory usage: 35123704 Bytes New peak memory usage: 38398392 Bytes Relative change: +9 % ========== Performance data for Null Build ========== Old instruction count: 1104417596 New instruction count: 1011033948 Relative change: -9 % Old peak memory usage: 24461824 Bytes New peak memory usage: 25325920 Bytes Relative change: +3 % Output of qbs_benchmarker on Linux with Qt Creator as test project: ========== Performance data for Resolving ========== Old instruction count: 67166450352 New instruction count: 60772791018 Relative change: -10 % Old peak memory usage: 327011616 Bytes New peak memory usage: 343724176 Bytes Relative change: +5 % ========== Performance data for Rule Execution ========== Old instruction count: 71684351183 New instruction count: 67051936965 Relative change: -7 % Old peak memory usage: 374913688 Bytes New peak memory usage: 387790992 Bytes Relative change: +3 % ========== Performance data for Null Build ========== Old instruction count: 8383156078 New instruction count: 7930705668 Relative change: -6 % Old peak memory usage: 180468360 Bytes New peak memory usage: 182490384 Bytes Relative change: +1 % Real-world data building Qt Creator (using qbs --log-time, several runs, removing outliers): macOS: Resolving: 43s -> 47s Rule execution: 17s -> 14s Windows: Resolving: 18s -> 16s Rule execution: 22s -> 17s Fixes: QBS-913 Fixes: QBS-1103 Fixes: QBS-1126 Fixes: QBS-1227 Fixes: QBS-1684 Change-Id: Ie5088155026e85bbd1e303f1c67addb15810a3cb Reviewed-by: Ivan Komissarov <ABBAPOH@gmail.com> Reviewed-by: Orgad Shaneh <orgads@gmail.com>
Diffstat (limited to 'src/lib/corelib/buildgraph')
-rw-r--r--src/lib/corelib/buildgraph/artifact.cpp2
-rw-r--r--src/lib/corelib/buildgraph/artifact.h5
-rw-r--r--src/lib/corelib/buildgraph/artifactsscriptvalue.cpp257
-rw-r--r--src/lib/corelib/buildgraph/artifactsscriptvalue.h13
-rw-r--r--src/lib/corelib/buildgraph/buildgraph.cpp503
-rw-r--r--src/lib/corelib/buildgraph/buildgraph.h13
-rw-r--r--src/lib/corelib/buildgraph/dependencyparametersscriptvalue.cpp26
-rw-r--r--src/lib/corelib/buildgraph/dependencyparametersscriptvalue.h7
-rw-r--r--src/lib/corelib/buildgraph/depscanner.cpp53
-rw-r--r--src/lib/corelib/buildgraph/depscanner.h7
-rw-r--r--src/lib/corelib/buildgraph/environmentscriptrunner.cpp44
-rw-r--r--src/lib/corelib/buildgraph/jscommandexecutor.cpp64
-rw-r--r--src/lib/corelib/buildgraph/processcommandexecutor.cpp47
-rw-r--r--src/lib/corelib/buildgraph/productbuilddata.cpp2
-rw-r--r--src/lib/corelib/buildgraph/productbuilddata.h3
-rw-r--r--src/lib/corelib/buildgraph/projectbuilddata.cpp2
-rw-r--r--src/lib/corelib/buildgraph/projectbuilddata.h6
-rw-r--r--src/lib/corelib/buildgraph/qtmocscanner.cpp57
-rw-r--r--src/lib/corelib/buildgraph/qtmocscanner.h14
-rw-r--r--src/lib/corelib/buildgraph/rulecommands.cpp318
-rw-r--r--src/lib/corelib/buildgraph/rulecommands.h19
-rw-r--r--src/lib/corelib/buildgraph/rulesapplicator.cpp228
-rw-r--r--src/lib/corelib/buildgraph/rulesapplicator.h12
-rw-r--r--src/lib/corelib/buildgraph/rulesevaluationcontext.cpp27
-rw-r--r--src/lib/corelib/buildgraph/rulesevaluationcontext.h13
-rw-r--r--src/lib/corelib/buildgraph/scriptclasspropertyiterator.h110
-rw-r--r--src/lib/corelib/buildgraph/transformer.cpp233
-rw-r--r--src/lib/corelib/buildgraph/transformer.h26
28 files changed, 1064 insertions, 1047 deletions
diff --git a/src/lib/corelib/buildgraph/artifact.cpp b/src/lib/corelib/buildgraph/artifact.cpp
index 8d3a8bd3f..8f94353e6 100644
--- a/src/lib/corelib/buildgraph/artifact.cpp
+++ b/src/lib/corelib/buildgraph/artifact.cpp
@@ -64,6 +64,8 @@ Artifact::~Artifact()
{
for (Artifact *p : parentArtifacts())
p->childrenAddedByScanner.remove(this);
+ if (m_deregister)
+ m_deregister(this);
}
void Artifact::accept(BuildGraphVisitor *visitor)
diff --git a/src/lib/corelib/buildgraph/artifact.h b/src/lib/corelib/buildgraph/artifact.h
index 2572a3b52..fce34b6ef 100644
--- a/src/lib/corelib/buildgraph/artifact.h
+++ b/src/lib/corelib/buildgraph/artifact.h
@@ -50,6 +50,7 @@
#include <QtCore/qstring.h>
+#include <functional>
#include <utility>
#include <vector>
@@ -123,8 +124,12 @@ public:
void load(PersistentPool &pool) override;
void store(PersistentPool &pool) override;
+ using Deregister = std::function<void(const Artifact *)>;
+ void setDeregister(const Deregister &deregister) { m_deregister = deregister; }
+
private:
FileTags m_fileTags;
+ Deregister m_deregister;
};
template<> inline QString Set<Artifact *>::toString(Artifact * const &artifact) const
diff --git a/src/lib/corelib/buildgraph/artifactsscriptvalue.cpp b/src/lib/corelib/buildgraph/artifactsscriptvalue.cpp
index 3f3fce59b..6a470bc17 100644
--- a/src/lib/corelib/buildgraph/artifactsscriptvalue.cpp
+++ b/src/lib/corelib/buildgraph/artifactsscriptvalue.cpp
@@ -46,172 +46,177 @@
#include <language/scriptengine.h>
#include <tools/stlutils.h>
-
-#include <QtScript/qscriptclass.h>
-#include <QtScript/qscriptcontext.h>
+#include <tools/stringconstants.h>
namespace qbs {
namespace Internal {
-enum BuildGraphScriptValueCommonPropertyKeys : quint32 {
- CachedValueKey,
- FileTagKey,
- ProductPtrKey,
-};
-
-class ArtifactsScriptClass : public QScriptClass
+template<class ProductOrModule>
+static bool isRelevantArtifact(const ProductOrModule *productOrModule, const Artifact *artifact)
{
-public:
- ArtifactsScriptClass(QScriptEngine *engine) : QScriptClass(engine) { }
-
-private:
- QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name,
- QueryFlags flags, uint *id) override
- {
- getProduct(object);
- qbsEngine()->setNonExistingArtifactSetRequested(m_product, name.toString());
- return QScriptClass::queryProperty(object, name, flags, id);
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>) {
+ Q_UNUSED(productOrModule)
+ return !artifact->isTargetOfModule();
+ } else {
+ return artifact->targetOfModule == productOrModule->name;
}
-
- QScriptClassPropertyIterator *newIterator(const QScriptValue &object) override
- {
- getProduct(object);
- qbsEngine()->setArtifactsEnumerated(m_product);
- return QScriptClass::newIterator(object);
- }
-
- void getProduct(const QScriptValue &object)
- {
- if (m_lastObjectId != object.objectId()) {
- m_lastObjectId = object.objectId();
- m_product = reinterpret_cast<const ResolvedProduct *>(
- object.data().property(ProductPtrKey).toVariant().value<quintptr>());
- }
- }
-
- ScriptEngine *qbsEngine() const { return static_cast<ScriptEngine *>(engine()); }
-
- qint64 m_lastObjectId = 0;
- const ResolvedProduct *m_product = nullptr;
-};
-
-static bool isRelevantArtifact(const ResolvedProduct *, const Artifact *artifact)
-{
- return !artifact->isTargetOfModule();
-}
-static bool isRelevantArtifact(const ResolvedModule *module, const Artifact *artifact)
-{
- return artifact->targetOfModule == module->name;
}
-static ArtifactSetByFileTag artifactsMap(const ResolvedProduct *product)
+template<class ProductOrModule>
+static ArtifactSetByFileTag artifactsMap(const ProductOrModule *productOrModule)
{
- return product->buildData->artifactsByFileTag();
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ return productOrModule->buildData->artifactsByFileTag();
+ else
+ return artifactsMap(productOrModule->product);
}
-static ArtifactSetByFileTag artifactsMap(const ResolvedModule *module)
+template<class ProductOrModule> static int scriptClassIndex()
{
- return artifactsMap(module->product);
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ return 0;
+ return 1;
}
-static QScriptValue createArtifactsObject(const ResolvedProduct *product, ScriptEngine *engine)
+template<class ProductOrModule>
+std::unique_lock<std::mutex> getArtifactsMapLock(ProductOrModule *productOrModule)
{
- QScriptClass *scriptClass = engine->artifactsScriptClass();
- if (!scriptClass) {
- scriptClass = new ArtifactsScriptClass(engine);
- engine->setArtifactsScriptClass(scriptClass);
- }
- QScriptValue artifactsObj = engine->newObject(scriptClass);
- QScriptValue data = engine->newObject();
- QVariant v;
- v.setValue<quintptr>(reinterpret_cast<quintptr>(product));
- data.setProperty(ProductPtrKey, engine->newVariant(v));
- artifactsObj.setData(data);
- return artifactsObj;
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ return productOrModule->buildData->getArtifactsMapLock();
+ else
+ return getArtifactsMapLock(productOrModule->product);
}
-static QScriptValue createArtifactsObject(const ResolvedModule *, ScriptEngine *engine)
+template<class ProductOrModule>
+static bool checkAndSetArtifactsMapUpToDateFlag(const ProductOrModule *productOrModule)
{
- return engine->newObject();
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ return productOrModule->buildData->checkAndSetJsArtifactsMapUpToDateFlag();
+ else
+ return checkAndSetArtifactsMapUpToDateFlag(productOrModule->product);
}
-static bool checkAndSetArtifactsMapUpToDateFlag(const ResolvedProduct *p)
+// Must be called with artifacts map lock held!
+template<class ProductOrModule>
+void registerArtifactsMapAccess(ScriptEngine *engine, ProductOrModule *productOrModule)
{
- return p->buildData->checkAndSetJsArtifactsMapUpToDateFlag();
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>) {
+ if (!checkAndSetArtifactsMapUpToDateFlag(productOrModule))
+ engine->setArtifactsMapRequested(productOrModule, true);
+ else
+ engine->setArtifactsMapRequested(productOrModule, false);
+ } else {
+ registerArtifactsMapAccess(engine, productOrModule->product);
+ }
}
-static bool checkAndSetArtifactsMapUpToDateFlag(const ResolvedModule *) { return true; }
-static void registerArtifactsMapAccess(const ResolvedProduct *p, ScriptEngine *e, bool forceUpdate)
-{
- e->setArtifactsMapRequested(p, forceUpdate);
-}
-static void registerArtifactsMapAccess(const ResolvedModule *, ScriptEngine *, bool) {}
-static void registerArtifactsSetAccess(const ResolvedProduct *p, const FileTag &t, ScriptEngine *e)
+template<class ProductOrModule>
+static int getArtifactsPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
+ JSValueConst obj)
{
- e->setArtifactSetRequestedForTag(p, t);
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto productOrModule = attachedPointer<ProductOrModule>(
+ obj, engine->artifactsScriptClass(scriptClassIndex<ProductOrModule>()));
+ const std::unique_lock lock = getArtifactsMapLock(productOrModule);
+ registerArtifactsMapAccess(engine, productOrModule);
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ engine->setArtifactsEnumerated(productOrModule);
+ const auto &map = artifactsMap(productOrModule);
+ const auto filter = [productOrModule](const Artifact *a) {
+ return isRelevantArtifact(productOrModule, a);
+ };
+ QStringList tags;
+ for (auto it = map.cbegin(); it != map.cend(); ++it) {
+ if (any_of(it.value(), filter)) {
+ tags << it.key().toString();
+ }
+ }
+ *plen = tags.size();
+ if (!tags.isEmpty()) {
+ *ptab = reinterpret_cast<JSPropertyEnum *>(js_malloc(ctx, *plen * sizeof **ptab));
+ JSPropertyEnum *entry = *ptab;
+ for (const QString &tag : qAsConst(tags)) {
+ entry->atom = JS_NewAtom(ctx, tag.toUtf8().constData());
+ entry->is_enumerable = 1;
+ ++entry;
+ }
+ } else {
+ *ptab = nullptr;
+ }
+ return 0;
}
-static void registerArtifactsSetAccess(const ResolvedModule *, const FileTag &, ScriptEngine *) {}
-template<class ProductOrModule> static QScriptValue js_artifactsForFileTag(
- QScriptContext *ctx, ScriptEngine *engine, const ProductOrModule *productOrModule)
+template<class ProductOrModule>
+static int getArtifactsProperty(JSContext *ctx, JSPropertyDescriptor *desc,
+ JSValueConst obj, JSAtom prop)
{
- const FileTag fileTag = FileTag(ctx->callee().property(FileTagKey).toString().toUtf8());
- registerArtifactsSetAccess(productOrModule, fileTag, engine);
- QScriptValue result = ctx->callee().property(CachedValueKey);
- if (result.isArray())
- return result;
- auto artifacts = artifactsMap(productOrModule).value(fileTag);
- const auto filter = [productOrModule](const Artifact *a) {
+ if (!desc)
+ return 1;
+
+ desc->flags = JS_PROP_ENUMERABLE;
+ desc->value = desc->getter = desc->setter = JS_UNDEFINED;
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto productOrModule = attachedPointer<ProductOrModule>(
+ obj, engine->artifactsScriptClass(scriptClassIndex<ProductOrModule>()));
+ const std::unique_lock lock = getArtifactsMapLock(productOrModule);
+ registerArtifactsMapAccess(engine, productOrModule);
+ const QString tagString = getJsString(ctx, prop);
+ const FileTag fileTag(tagString.toUtf8());
+ const auto &map = artifactsMap(productOrModule);
+ const auto it = map.constFind(fileTag);
+ if (it == map.constEnd()) {
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ engine->setNonExistingArtifactSetRequested(productOrModule, tagString);
+ return 1;
+ }
+ if constexpr (std::is_same_v<ProductOrModule, ResolvedProduct>)
+ engine->setArtifactSetRequestedForTag(productOrModule, fileTag);
+ ArtifactSet artifacts = it.value();
+ removeIf(artifacts, [productOrModule](const Artifact *a) {
return !isRelevantArtifact(productOrModule, a);
- };
- Internal::removeIf(artifacts, filter);
- result = engine->newArray(uint(artifacts.size()));
- ctx->callee().setProperty(CachedValueKey, result);
- int k = 0;
- for (const Artifact * const artifact : artifacts)
- result.setProperty(k++, Transformer::translateFileConfig(engine, artifact, QString()));
- return result;
+ });
+ if (!artifacts.empty()) {
+ desc->value = JS_NewArray(ctx); // TODO: Also cache this list?
+ int k = 0;
+ for (Artifact * const artifact : artifacts) {
+ JS_SetPropertyUint32(ctx, desc->value, k++,
+ Transformer::translateFileConfig(engine, artifact, QString()));
+ }
+ }
+ return 1;
}
-template<class ProductOrModule> static QScriptValue js_artifacts(
- QScriptContext *ctx, ScriptEngine *engine, const ProductOrModule *productOrModule)
+template<class ProductOrModule> static JSValue js_artifacts(JSContext *ctx,
+ JSValue jsProductOrModule)
{
- QScriptValue artifactsObj = ctx->callee().property(CachedValueKey);
- if (artifactsObj.isObject() && checkAndSetArtifactsMapUpToDateFlag(productOrModule)) {
- registerArtifactsMapAccess(productOrModule, engine, false);
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto productOrModule = attachedPointer<ProductOrModule>(jsProductOrModule,
+ engine->dataWithPtrClass());
+ JSValue artifactsObj = engine->artifactsMapScriptValue(productOrModule);
+ if (!JS_IsUndefined(artifactsObj))
return artifactsObj;
+ const int classIndex = scriptClassIndex<ProductOrModule>();
+ JSClassID scriptClass = engine->artifactsScriptClass(classIndex);
+ if (scriptClass == 0) {
+ const QByteArray className = "ArtifactsScriptClass" + QByteArray::number(classIndex);
+ scriptClass = engine->registerClass(className.constData(), nullptr, nullptr, JS_UNDEFINED,
+ &getArtifactsPropertyNames<ProductOrModule>,
+ &getArtifactsProperty<ProductOrModule>);
+ engine->setArtifactsScriptClass(classIndex, scriptClass);
}
- registerArtifactsMapAccess(productOrModule, engine, true);
- artifactsObj = createArtifactsObject(productOrModule, engine);
- ctx->callee().setProperty(CachedValueKey, artifactsObj);
- const auto &map = artifactsMap(productOrModule);
- for (auto it = map.cbegin(); it != map.cend(); ++it) {
- const auto filter = [productOrModule](const Artifact *a) {
- return isRelevantArtifact(productOrModule, a);
- };
- if (std::none_of(it.value().cbegin(), it.value().cend(), filter))
- continue;
- QScriptValue fileTagFunc = engine->newFunction(&js_artifactsForFileTag<ProductOrModule>,
- productOrModule);
- const QString fileTag = it.key().toString();
- fileTagFunc.setProperty(FileTagKey, fileTag);
- artifactsObj.setProperty(fileTag, fileTagFunc,
- QScriptValue::ReadOnly | QScriptValue::Undeletable
- | QScriptValue::PropertyGetter);
- }
+ artifactsObj = JS_NewObjectClass(engine->context(), scriptClass);
+ attachPointerTo(artifactsObj, productOrModule);
return artifactsObj;
}
-QScriptValue artifactsScriptValueForProduct(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedProduct *product)
+JSValue artifactsScriptValueForProduct(JSContext *ctx, JSValue this_val, int, JSValue *)
{
- return js_artifacts(ctx, engine, product);
+ return js_artifacts<ResolvedProduct>(ctx, this_val);
}
-QScriptValue artifactsScriptValueForModule(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedModule *module)
+JSValue artifactsScriptValueForModule(JSContext *ctx, JSValueConst this_val, int, JSValueConst *)
{
- return js_artifacts(ctx, engine, module);
+ return js_artifacts<ResolvedModule>(ctx, this_val);
}
} // namespace Internal
diff --git a/src/lib/corelib/buildgraph/artifactsscriptvalue.h b/src/lib/corelib/buildgraph/artifactsscriptvalue.h
index c0da8a05e..dce457758 100644
--- a/src/lib/corelib/buildgraph/artifactsscriptvalue.h
+++ b/src/lib/corelib/buildgraph/artifactsscriptvalue.h
@@ -41,21 +41,14 @@
#include <language/forward_decls.h>
-#include <QtScript/qscriptvalue.h>
-
-QT_BEGIN_NAMESPACE
-class QScriptContext;
-QT_END_NAMESPACE
+#include <quickjs.h>
namespace qbs {
namespace Internal {
class ScriptEngine;
-QScriptValue artifactsScriptValueForProduct(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedProduct *product);
-
-QScriptValue artifactsScriptValueForModule(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedModule *module);
+JSValue artifactsScriptValueForProduct(JSContext *ctx, JSValueConst this_val, int, JSValueConst *);
+JSValue artifactsScriptValueForModule(JSContext *ctx, JSValueConst this_val, int, JSValueConst *);
} // namespace Internal
} // namespace qbs
diff --git a/src/lib/corelib/buildgraph/buildgraph.cpp b/src/lib/corelib/buildgraph/buildgraph.cpp
index 23d141dd8..df3301d57 100644
--- a/src/lib/corelib/buildgraph/buildgraph.cpp
+++ b/src/lib/corelib/buildgraph/buildgraph.cpp
@@ -45,7 +45,6 @@
#include "projectbuilddata.h"
#include "productbuilddata.h"
#include "rulenode.h"
-#include "scriptclasspropertyiterator.h"
#include "transformer.h"
#include <jsextensions/jsextensions.h>
@@ -70,7 +69,6 @@
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
-#include <QtScript/qscriptclass.h>
#include <algorithm>
#include <iterator>
@@ -83,146 +81,187 @@ static QString childItemsProperty() { return QStringLiteral("childItems"); }
static QString exportsProperty() { return QStringLiteral("exports"); }
// TODO: Introduce productscriptvalue.{h,cpp}.
-static QScriptValue getDataForProductScriptValue(QScriptEngine *engine,
- const ResolvedProduct *product)
+
+static JSValue getDataObject(JSContext *ctx, JSValue obj)
{
- QScriptValue data = engine->newObject();
- QVariant v;
- v.setValue<quintptr>(reinterpret_cast<quintptr>(product));
- data.setProperty(ProductPtrKey, engine->newVariant(v));
- return data;
+ return getJsProperty(ctx, obj, StringConstants::dataPropertyInternal());
}
-class ProductPropertyScriptClass : public QScriptClass
+static JSValue getValueFromData(JSContext *ctx, JSValue data,
+ ModulePropertiesScriptValueCommonPropertyKeys key)
{
-public:
- ProductPropertyScriptClass(QScriptEngine *engine) : QScriptClass(engine) { }
-
-private:
- QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags,
- uint *) override
- {
- if (name == StringConstants::parametersProperty()) {
- m_result = object.data().property(DependencyParametersKey);
- return HandlesReadAccess;
- }
- if (name == StringConstants::moduleNameProperty()) {
- m_result = object.data().property(ModuleNameKey);
- return HandlesReadAccess;
- }
- if (name == StringConstants::dependenciesProperty()
- || name == StringConstants::artifactsProperty()
- || name == exportsProperty()) {
- // The prototype is not backed by a QScriptClass.
- m_result = object.prototype().property(name);
- return HandlesReadAccess;
- }
-
- getProduct(object);
- QBS_ASSERT(m_product, return {});
-
- const auto it = m_product->productProperties.find(name);
+ return JS_GetPropertyUint32(ctx, data, key);
+}
- // It is important that we reject unknown property names. Otherwise QtScript will forward
- // *everything* to us, including built-in stuff like the hasOwnProperty function.
- if (it == m_product->productProperties.cend())
- return {};
+static JSValue getValueFromObject(JSContext *ctx, JSValue obj,
+ ModulePropertiesScriptValueCommonPropertyKeys key)
+{
+ const ScopedJsValue data(ctx, getDataObject(ctx, obj));
+ return getValueFromData(ctx, data, key);
+}
- qbsEngine()->addPropertyRequestedInScript(Property(m_product->uniqueName(), QString(), name,
- it.value(), Property::PropertyInProduct));
- m_result = qbsEngine()->toScriptValue(it.value());
- return HandlesReadAccess;
+void getPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
+ const QVariantMap &properties, const QStringList &extraPropertyNames,
+ JSValue extraObject)
+{
+ JSPropertyEnum *basePTab = nullptr;
+ uint32_t basePlen = 0;
+ JS_GetOwnPropertyNames(ctx, &basePTab, &basePlen, extraObject,
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY);
+ *plen = uint32_t(extraPropertyNames.size() + properties.size() + basePlen);
+ *ptab = reinterpret_cast<JSPropertyEnum *>(js_malloc(ctx, *plen * sizeof **ptab));
+ JSPropertyEnum *entry = *ptab;
+ for (auto it = properties.begin(); it != properties.end(); ++it, ++entry) {
+ entry->atom = JS_NewAtom(ctx, it.key().toUtf8().constData());
+ entry->is_enumerable = 1;
}
-
- QScriptValue property(const QScriptValue &, const QScriptString &, uint) override
- {
- return m_result;
+ for (const QString &prop : extraPropertyNames) {
+ entry->atom = JS_NewAtom(ctx, prop.toUtf8().constData());
+ entry->is_enumerable = 1;
+ ++entry;
+ }
+ for (uint32_t i = 0; i < basePlen; ++i, ++entry) {
+ entry->atom = basePTab[i].atom;
+ entry->is_enumerable = 1;
+ }
+ js_free(ctx, basePTab);
+}
+
+static int getProductPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
+ JSValueConst obj)
+{
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const ScopedJsValue data(ctx, getDataObject(engine->context(), obj));
+ const auto product = attachedPointer<ResolvedProduct>(
+ obj, engine->productPropertyScriptClass());
+ QBS_ASSERT(product, return -1);
+
+ // The "moduleName" convenience property is only available for the "main product" in a rule,
+ // and the "parameters" property exists only for elements of the "dependencies" array for
+ // which dependency parameters are present.
+ const auto hasModuleName = [&] {
+ const ScopedJsValue v(ctx, getValueFromData(ctx, data, ModuleNameKey));
+ return JS_IsString(v);
+ };
+ const auto hasDependencyParams = [&] {
+ const ScopedJsValue v(ctx, getValueFromData(ctx, data, DependencyParametersKey));
+ return JS_IsObject(v);
+ };
+ QStringList additionalProperties;
+ if (hasModuleName())
+ additionalProperties.push_back(StringConstants::moduleNameProperty());
+ else if (hasDependencyParams())
+ additionalProperties.push_back(StringConstants::parametersProperty());
+ getPropertyNames(ctx, ptab, plen, product->productProperties, additionalProperties,
+ engine->baseProductScriptValue(product));
+ return 0;
+}
+
+static int getProductProperty(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj,
+ JSAtom prop)
+{
+ if (desc) {
+ desc->getter = desc->setter = desc->value = JS_UNDEFINED;
+ desc->flags = JS_PROP_ENUMERABLE;
+ }
+ const QString name = getJsString(ctx, prop);
+ if (name == StringConstants::parametersProperty()) {
+ if (desc)
+ desc->value = getValueFromObject(ctx, obj, DependencyParametersKey);
+ return 1;
+ }
+ if (name == StringConstants::moduleNameProperty()) {
+ if (desc)
+ desc->value = getValueFromObject(ctx, obj, ModuleNameKey);
+ return 1;
}
- QScriptClassPropertyIterator *newIterator(const QScriptValue &object) override
- {
- getProduct(object);
- QBS_ASSERT(m_product, return nullptr);
-
- // These two are in the prototype and are thus common to all product script values.
- std::vector<QString> additionalProperties({StringConstants::artifactsProperty(),
- StringConstants::dependenciesProperty(),
- exportsProperty()});
-
- // The "moduleName" convenience property is only available for the "main product" in a rule,
- // and the "parameters" property exists only for elements of the "dependencies" array for
- // which dependency parameters are present.
- if (object.data().property(ModuleNameKey).isValid())
- additionalProperties.push_back(StringConstants::moduleNameProperty());
- else if (object.data().property(DependencyParametersKey).isValid())
- additionalProperties.push_back(StringConstants::parametersProperty());
- return new ScriptClassPropertyIterator(object, m_product->productProperties,
- additionalProperties);
- }
-
- void getProduct(const QScriptValue &object)
- {
- if (m_lastObjectId != object.objectId()) {
- m_lastObjectId = object.objectId();
- m_product = reinterpret_cast<const ResolvedProduct *>(
- object.data().property(ProductPtrKey).toVariant().value<quintptr>());
- }
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto product = attachedPointer<ResolvedProduct>(
+ obj, engine->productPropertyScriptClass());
+ QBS_ASSERT(product, return -1);
+
+ const JSValue baseProductValue = engine->baseProductScriptValue(product);
+ if (name == exportsProperty()) {
+ if (desc)
+ desc->value = getJsProperty(ctx, baseProductValue, name);
+ engine->addRequestedExport(product);
+ return 1;
}
- ScriptEngine *qbsEngine() const { return static_cast<ScriptEngine *>(engine()); }
+ const auto it = product->productProperties.constFind(name);
+ if (it == product->productProperties.cend()) {
+ ScopedJsValue v(ctx, JS_GetProperty(ctx, baseProductValue, prop));
+ const int ret = JS_IsUndefined(v) ? 0 : 1;
+ if (desc)
+ desc->value = v.release();
+ return ret;
+ }
- qint64 m_lastObjectId = 0;
- const ResolvedProduct *m_product = nullptr;
- QScriptValue m_result;
-};
+ engine->addPropertyRequestedInScript(Property(product->uniqueName(), QString(), name,
+ it.value(), Property::PropertyInProduct));
+ if (desc)
+ desc->value = engine->toScriptValue(it.value());
+ return 1;
+}
-static QScriptValue setupProjectScriptValue(ScriptEngine *engine,
- const ResolvedProjectConstPtr &project)
+static JSValue setupProjectScriptValue(ScriptEngine *engine, const ResolvedProjectConstPtr &project)
{
- QScriptValue &obj = engine->projectScriptValue(project.get());
- if (obj.isValid())
- return obj;
+ JSValue &obj = engine->projectScriptValue(project.get());
+ if (JS_IsObject(obj))
+ return JS_DupValue(engine->context(), obj);
obj = engine->newObject();
- obj.setProperty(StringConstants::filePathProperty(), project->location.filePath());
- obj.setProperty(StringConstants::pathProperty(), FileInfo::path(project->location.filePath()));
+ setJsProperty(engine->context(), obj, StringConstants::filePathProperty(),
+ project->location.filePath());
+ setJsProperty(engine->context(), obj, StringConstants::pathProperty(),
+ FileInfo::path(project->location.filePath()));
const QVariantMap &projectProperties = project->projectProperties();
for (QVariantMap::const_iterator it = projectProperties.begin();
it != projectProperties.end(); ++it) {
- engine->setObservedProperty(obj, it.key(), engine->toScriptValue(it.value()));
+ const ScopedJsValue val(engine->context(), engine->toScriptValue(it.value()));
+ engine->setObservedProperty(obj, it.key(), val);
}
- engine->observer()->addProjectObjectId(obj.objectId(), project->name);
- return obj;
+ engine->observer()->addProjectObjectId(jsObjectId(obj), project->name);
+ return JS_DupValue(engine->context(), obj);
}
-static QScriptValue setupProductScriptValue(ScriptEngine *engine, const ResolvedProduct *product);
+static void setupBaseProductScriptValue(ScriptEngine *engine, const ResolvedProduct *product);
class DependenciesFunction
{
public:
- DependenciesFunction(ScriptEngine *engine)
- : m_engine(engine)
- {
- }
+ DependenciesFunction(ScriptEngine *engine) : m_engine(engine) { }
- void init(QScriptValue &productScriptValue, QScriptValue &exportsScriptValue,
- const ResolvedProduct *product)
+ void init(JSValue &productScriptValue, JSValue exportsScriptValue)
{
- QScriptValue depfunc = m_engine->newFunction(&js_internalProductDependencies, product);
- productScriptValue.setProperty(StringConstants::dependenciesProperty(), depfunc,
- QScriptValue::ReadOnly | QScriptValue::Undeletable
- | QScriptValue::PropertyGetter);
- depfunc = m_engine->newFunction(&js_exportedProductDependencies, product);
- exportsScriptValue.setProperty(StringConstants::dependenciesProperty(), depfunc,
- QScriptValue::ReadOnly | QScriptValue::Undeletable
- | QScriptValue::PropertyGetter);
+ const QByteArray name = StringConstants::dependenciesProperty().toUtf8();
+ const ScopedJsValue depfunc(
+ m_engine->context(),
+ JS_NewCFunction(m_engine->context(), &js_internalProductDependencies,
+ name.constData(), 0));
+ const ScopedJsAtom depAtom(m_engine->context(), name);
+ JS_DefineProperty(m_engine->context(), productScriptValue, depAtom, JS_UNDEFINED, depfunc,
+ JS_UNDEFINED, JS_PROP_HAS_GET | JS_PROP_ENUMERABLE);
+ const ScopedJsValue exportedDepfunc(
+ m_engine->context(),
+ JS_NewCFunction(m_engine->context(), &js_exportedProductDependencies,
+ name.constData(), 0));
+ JS_DefineProperty(m_engine->context(), exportsScriptValue, depAtom, JS_UNDEFINED,
+ exportedDepfunc, JS_UNDEFINED, JS_PROP_HAS_GET | JS_PROP_ENUMERABLE);
}
private:
enum class DependencyType { Internal, Exported };
- static QScriptValue js_productDependencies(QScriptContext *, ScriptEngine *engine,
- const ResolvedProduct *product, DependencyType depType)
+ static JSValue js_productDependencies(const ResolvedProduct *product,
+ JSContext *ctx, JSValueConst this_val, int argc,
+ JSValueConst *argv, DependencyType depType)
{
- QScriptValue result = engine->newArray();
+ Q_UNUSED(this_val)
+ Q_UNUSED(argc)
+ Q_UNUSED(argv)
+
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ JSValue result = JS_NewArray(ctx);
quint32 idx = 0;
const bool exportCase = depType == DependencyType::Exported;
std::vector<ResolvedProductPtr> productDeps;
@@ -245,201 +284,233 @@ private:
productDeps = product->dependencies;
}
for (const ResolvedProductPtr &dependency : qAsConst(productDeps)) {
- QScriptValue obj = engine->newObject(engine->productPropertyScriptClass());
- obj.setPrototype(setupProductScriptValue(static_cast<ScriptEngine *>(engine),
- dependency.get()));
+ setupBaseProductScriptValue(engine, dependency.get());
+ JSValue obj = JS_NewObjectClass(engine->context(),
+ engine->productPropertyScriptClass());
+ attachPointerTo(obj, dependency.get());
const QVariantMap &params
= (exportCase ? product->exportedModule.dependencyParameters.value(dependency)
: product->dependencyParameters.value(dependency));
- QScriptValue data = getDataForProductScriptValue(engine, dependency.get());
- data.setProperty(DependencyParametersKey, dependencyParametersValue(
- product->uniqueName(), dependency->name, params, engine));
- obj.setData(data);
- result.setProperty(idx++, obj);
+ JSValue data = JS_NewObjectClass(engine->context(), engine->dataWithPtrClass());
+ JS_SetPropertyUint32(ctx, data, DependencyParametersKey, dependencyParametersValue(
+ product->uniqueName(), dependency->name, params, engine));
+ defineJsProperty(ctx, obj, StringConstants::dataPropertyInternal(), data);
+ JS_SetPropertyUint32(ctx, result, idx++, obj);
}
if (exportCase) {
for (const ExportedModuleDependency &m : product->exportedModule.moduleDependencies) {
- QScriptValue obj = engine->newObject();
- obj.setProperty(StringConstants::nameProperty(), m.name);
- QScriptValue exportsValue = engine->newObject();
- obj.setProperty(exportsProperty(), exportsValue);
- exportsValue.setProperty(StringConstants::dependenciesProperty(),
- engine->newArray());
+ JSValue obj = engine->newObject();
+ setJsProperty(ctx, obj, StringConstants::nameProperty(), m.name);
+ JSValue exportsValue = engine->newObject();
+ setJsProperty(ctx, obj, exportsProperty(), exportsValue);
+ setJsProperty(ctx, exportsValue, StringConstants::dependenciesProperty(),
+ JS_NewArray(ctx));
for (auto modIt = m.moduleProperties.begin(); modIt != m.moduleProperties.end();
++modIt) {
const QVariantMap entries = modIt.value().toMap();
if (entries.empty())
continue;
- QScriptValue moduleObj = engine->newObject();
- ModuleProperties::setModuleScriptValue(exportsValue, moduleObj, modIt.key());
- for (auto valIt = entries.begin(); valIt != entries.end(); ++valIt)
- moduleObj.setProperty(valIt.key(), engine->toScriptValue(valIt.value()));
+ JSValue moduleObj = engine->newObject();
+ ModuleProperties::setModuleScriptValue(engine, exportsValue, moduleObj,
+ modIt.key());
+ for (auto valIt = entries.begin(); valIt != entries.end(); ++valIt) {
+ setJsProperty(ctx, moduleObj, valIt.key(),
+ engine->toScriptValue(valIt.value()));
+ }
}
- result.setProperty(idx++, obj);
+ JS_SetPropertyUint32(ctx, result, idx++, obj);
}
return result;
}
for (const auto &dependency : product->modules) {
if (dependency->isProduct)
continue;
- QScriptValue obj = engine->newObject(engine->modulePropertyScriptClass());
- obj.setPrototype(engine->moduleScriptValuePrototype(dependency.get()));
-
- // The prototype must exist already, because we set it up for all modules
- // of the product in ModuleProperties::init().
- QBS_ASSERT(obj.prototype().isValid(), ;);
-
+ JSValue obj = JS_NewObjectClass(ctx, engine->modulePropertyScriptClass());
+ attachPointerTo(obj, dependency.get());
const QVariantMap &params = product->moduleParameters.value(dependency);
- QScriptValue data = getDataForModuleScriptValue(engine, product, nullptr,
- dependency.get());
- data.setProperty(DependencyParametersKey, dependencyParametersValue(
- product->uniqueName(), dependency->name, params, engine));
- obj.setData(data);
- result.setProperty(idx++, obj);
+ JSValue data = createDataForModuleScriptValue(engine, nullptr);
+ JS_SetPropertyUint32(ctx, data, DependencyParametersKey, dependencyParametersValue(
+ product->uniqueName(), dependency->name, params, engine));
+ defineJsProperty(ctx, obj, StringConstants::dataPropertyInternal(), data);
+ JS_SetPropertyUint32(ctx, result, idx++, obj);
}
return result;
}
- static QScriptValue js_internalProductDependencies(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedProduct * const product)
+ static JSValue js_internalProductDependencies(JSContext *ctx, JSValueConst this_val,
+ int argc, JSValueConst *argv)
{
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto product = attachedPointer<ResolvedProduct>(this_val, engine->dataWithPtrClass());
engine->addDependenciesArrayRequested(product);
- return js_productDependencies(ctx, engine, product, DependencyType::Internal);
+ return js_productDependencies(product, ctx, this_val, argc, argv,
+ DependencyType::Internal);
}
- static QScriptValue js_exportedProductDependencies(QScriptContext *ctx, ScriptEngine *engine,
- const ResolvedProduct * const product)
+ static JSValue js_exportedProductDependencies(JSContext *ctx, JSValueConst this_val,
+ int argc, JSValueConst *argv)
{
- return js_productDependencies(ctx, engine, product, DependencyType::Exported);
+ const auto product = attachedPointer<ResolvedProduct>(
+ this_val, ScriptEngine::engineForContext(ctx)->dataWithPtrClass());
+ return js_productDependencies(product, ctx, this_val, argc, argv, DependencyType::Exported);
}
ScriptEngine *m_engine;
};
-static QScriptValue setupExportedPropertyScriptValue(const ExportedProperty &property,
+static JSValue setupExportedPropertyScriptValue(const ExportedProperty &property,
ScriptEngine *engine)
{
- QScriptValue propertyScriptValue = engine->newObject();
- propertyScriptValue.setProperty(StringConstants::nameProperty(), property.fullName);
- propertyScriptValue.setProperty(StringConstants::typeProperty(),
- PropertyDeclaration::typeString(property.type));
- propertyScriptValue.setProperty(StringConstants::sourceCodeProperty(), property.sourceCode);
- propertyScriptValue.setProperty(QStringLiteral("isBuiltin"), property.isBuiltin);
+ JSValue propertyScriptValue = engine->newObject();
+ setJsProperty(engine->context(), propertyScriptValue, StringConstants::nameProperty(),
+ property.fullName);
+ setJsProperty(engine->context(), propertyScriptValue, StringConstants::typeProperty(),
+ PropertyDeclaration::typeString(property.type));
+ setJsProperty(engine->context(), propertyScriptValue, StringConstants::sourceCodeProperty(),
+ property.sourceCode);
+ JS_SetPropertyStr(engine->context(), propertyScriptValue, "isBuiltin",
+ JS_NewBool(engine->context(), property.isBuiltin));
return propertyScriptValue;
}
-static void setupExportedPropertiesScriptValue(QScriptValue &parentObject,
+static void setupExportedPropertiesScriptValue(JSValue &parentObject,
const std::vector<ExportedProperty> &properties,
ScriptEngine *engine)
{
- QScriptValue propertiesScriptValue = engine->newArray(static_cast<uint>(properties.size()));
- parentObject.setProperty(QStringLiteral("properties"), propertiesScriptValue);
+ JSValue propertiesScriptValue = JS_NewArray(engine->context());
quint32 arrayIndex = 0;
for (const ExportedProperty &p : properties) {
- propertiesScriptValue.setProperty(arrayIndex++,
- setupExportedPropertyScriptValue(p, engine));
+ JS_SetPropertyUint32(engine->context(), propertiesScriptValue, arrayIndex++,
+ setupExportedPropertyScriptValue(p, engine));
}
+ JS_SetPropertyStr(engine->context(), parentObject, "properties", propertiesScriptValue);
}
-static QScriptValue setupExportedItemScriptValue(const ExportedItem *item, ScriptEngine *engine)
+static JSValue setupExportedItemScriptValue(const ExportedItem *item, ScriptEngine *engine)
{
- QScriptValue itemScriptValue = engine->newObject();
- itemScriptValue.setProperty(StringConstants::nameProperty(), item->name);
+ JSValue itemScriptValue = engine->newObject();
+ setJsProperty(engine->context(), itemScriptValue, StringConstants::nameProperty(), item->name);
setupExportedPropertiesScriptValue(itemScriptValue, item->properties, engine);
- QScriptValue childrenScriptValue = engine->newArray(static_cast<uint>(item->children.size()));
- itemScriptValue.setProperty(childItemsProperty(), childrenScriptValue);
+ JSValue childrenScriptValue = JS_NewArray(engine->context());
quint32 arrayIndex = 0;
for (const auto &childItem : item->children) {
- childrenScriptValue.setProperty(arrayIndex++,
- setupExportedItemScriptValue(childItem.get(), engine));
+ JS_SetPropertyUint32(engine->context(), childrenScriptValue, arrayIndex++,
+ setupExportedItemScriptValue(childItem.get(), engine));
}
+ setJsProperty(engine->context(), itemScriptValue, childItemsProperty(), childrenScriptValue);
return itemScriptValue;
}
-static QScriptValue setupExportsScriptValue(const ExportedModule &module, ScriptEngine *engine)
+static JSValue setupExportsScriptValue(const ResolvedProduct *product, ScriptEngine *engine)
{
- QScriptValue exportsScriptValue = engine->newObject();
- for (auto it = module.propertyValues.cbegin(); it != module.propertyValues.cend(); ++it)
- exportsScriptValue.setProperty(it.key(), engine->toScriptValue(it.value()));
+ const ExportedModule &module = product->exportedModule;
+ JSValue exportsScriptValue = JS_NewObjectClass(engine->context(), engine->dataWithPtrClass());
+ attachPointerTo(exportsScriptValue, product);
+ for (auto it = module.propertyValues.cbegin(); it != module.propertyValues.cend(); ++it) {
+ setJsProperty(engine->context(), exportsScriptValue, it.key(),
+ engine->toScriptValue(it.value()));
+ }
setupExportedPropertiesScriptValue(exportsScriptValue, module.m_properties, engine);
- QScriptValue childrenScriptValue = engine->newArray(static_cast<uint>(module.children.size()));
- exportsScriptValue.setProperty(childItemsProperty(), childrenScriptValue);
+ JSValue childrenScriptValue = JS_NewArray(engine->context());
quint32 arrayIndex = 0;
for (const auto &exportedItem : module.children) {
- childrenScriptValue.setProperty(arrayIndex++,
- setupExportedItemScriptValue(exportedItem.get(), engine));
+ JS_SetPropertyUint32(engine->context(), childrenScriptValue, arrayIndex++,
+ setupExportedItemScriptValue(exportedItem.get(), engine));
}
- QScriptValue importsScriptValue = engine->newArray(module.importStatements.size());
- exportsScriptValue.setProperty(StringConstants::importsProperty(), importsScriptValue);
+ setJsProperty(engine->context(), exportsScriptValue, childItemsProperty(), childrenScriptValue);
+ JSValue importsScriptValue = JS_NewArray(engine->context());
arrayIndex = 0;
- for (const QString &importStatement : module.importStatements)
- importsScriptValue.setProperty(arrayIndex++, importStatement);
+ for (const QString &importStatement : module.importStatements) {
+ JS_SetPropertyUint32(engine->context(), importsScriptValue, arrayIndex++,
+ makeJsString(engine->context(), importStatement));
+ }
+ setJsProperty(engine->context(), exportsScriptValue, StringConstants::importsProperty(),
+ importsScriptValue);
for (auto it = module.modulePropertyValues.cbegin(); it != module.modulePropertyValues.cend();
++it) {
const QVariantMap entries = it.value().toMap();
if (entries.empty())
continue;
- QScriptValue moduleObject = engine->newObject();
- ModuleProperties::setModuleScriptValue(exportsScriptValue, moduleObject, it.key());
- for (auto valIt = entries.begin(); valIt != entries.end(); ++valIt)
- moduleObject.setProperty(valIt.key(), engine->toScriptValue(valIt.value()));
+ JSValue moduleObject = engine->newObject();
+ ModuleProperties::setModuleScriptValue(engine, exportsScriptValue, moduleObject, it.key());
+ for (auto valIt = entries.begin(); valIt != entries.end(); ++valIt) {
+ setJsProperty(engine->context(), moduleObject, valIt.key(),
+ engine->toScriptValue(valIt.value()));
+ }
}
return exportsScriptValue;
}
-static QScriptValue setupProductScriptValue(ScriptEngine *engine, const ResolvedProduct *product)
+static void setupBaseProductScriptValue(ScriptEngine *engine, const ResolvedProduct *product)
{
- QScriptValue &productScriptValue = engine->productScriptValuePrototype(product);
- if (productScriptValue.isValid())
- return productScriptValue;
- productScriptValue = engine->newObject();
- ModuleProperties::init(productScriptValue, product);
-
- QScriptValue artifactsFunc = engine->newFunction(&artifactsScriptValueForProduct, product);
- productScriptValue.setProperty(StringConstants::artifactsProperty(), artifactsFunc,
- QScriptValue::ReadOnly | QScriptValue::Undeletable
- | QScriptValue::PropertyGetter);
-
- QScriptValue exportsScriptValue = setupExportsScriptValue(product->exportedModule, engine);
- DependenciesFunction(engine).init(productScriptValue, exportsScriptValue, product);
+ JSValue &productScriptValue = engine->baseProductScriptValue(product);
+ if (JS_IsObject(productScriptValue))
+ return;
+ const ScopedJsValue proto(engine->context(), JS_NewObject(engine->context()));
+ productScriptValue = JS_NewObjectProtoClass(engine->context(), proto,
+ engine->dataWithPtrClass());
+ attachPointerTo(productScriptValue, product);
+ ModuleProperties::init(engine, productScriptValue, product);
+
+ const QByteArray funcName = StringConstants::artifactsProperty().toUtf8();
+ const ScopedJsValue artifactsFunc(
+ engine->context(),
+ JS_NewCFunction(engine->context(), &artifactsScriptValueForProduct,
+ funcName.constData(), 0));
+ const ScopedJsAtom artifactsAtom(engine->context(), funcName);
+ JS_DefineProperty(engine->context(), productScriptValue, artifactsAtom,
+ JS_UNDEFINED, artifactsFunc, JS_UNDEFINED,
+ JS_PROP_HAS_GET | JS_PROP_ENUMERABLE);
+
+ // FIXME: Proper un-observe rather than ref count decrease here.
+ ScopedJsValue exportsScriptValue(engine->context(), setupExportsScriptValue(product, engine));
+ DependenciesFunction(engine).init(productScriptValue, exportsScriptValue);
+
+ // TODO: Why are these necessary? We catch accesses to product.exports in getProductProperty().
+ // But the exportsQbs() and exportsPkgConfig() tests fail without them.
engine->setObservedProperty(productScriptValue, exportsProperty(), exportsScriptValue);
- engine->observer()->addExportsObjectId(exportsScriptValue.objectId(), product);
- return productScriptValue;
+ engine->observer()->addExportsObjectId(jsObjectId(exportsScriptValue), product);
}
void setupScriptEngineForFile(ScriptEngine *engine, const FileContextBaseConstPtr &fileContext,
- QScriptValue targetObject, const ObserveMode &observeMode)
+ JSValue targetObject, const ObserveMode &observeMode)
{
engine->import(fileContext, targetObject, observeMode);
- JsExtensions::setupExtensions(fileContext->jsExtensions(), targetObject);
+ JsExtensions::setupExtensions(engine, fileContext->jsExtensions(), targetObject);
}
void setupScriptEngineForProduct(ScriptEngine *engine, ResolvedProduct *product,
- const ResolvedModule *module, QScriptValue targetObject,
+ const ResolvedModule *module, JSValue targetObject,
bool setBuildEnvironment)
{
- QScriptValue projectScriptValue = setupProjectScriptValue(engine, product->project.lock());
- targetObject.setProperty(StringConstants::projectVar(), projectScriptValue);
-
+ JSValue projectScriptValue = setupProjectScriptValue(engine, product->project.lock());
+ setJsProperty(engine->context(), targetObject, StringConstants::projectVar(),
+ projectScriptValue);
if (setBuildEnvironment) {
QVariant v;
v.setValue<void*>(&product->buildEnvironment);
engine->setProperty(StringConstants::qbsProcEnvVarInternal(), v);
}
- QScriptClass *scriptClass = engine->productPropertyScriptClass();
- if (!scriptClass) {
- scriptClass = new ProductPropertyScriptClass(engine);
- engine->setProductPropertyScriptClass(scriptClass);
+ JSClassID scriptClass = engine->productPropertyScriptClass();
+ if (scriptClass == 0) {
+ engine->setProductPropertyScriptClass(engine->registerClass("ProductProperties", nullptr,
+ nullptr, JS_UNDEFINED, &getProductPropertyNames, &getProductProperty));
+ scriptClass = engine->productPropertyScriptClass();
}
- QScriptValue productScriptValue = engine->newObject(scriptClass);
- productScriptValue.setPrototype(setupProductScriptValue(engine, product));
- targetObject.setProperty(StringConstants::productVar(), productScriptValue);
+ setupBaseProductScriptValue(engine, product);
+ JSValue productScriptValue = JS_NewObjectClass(engine->context(), scriptClass);
+ attachPointerTo(productScriptValue, product);
+ setJsProperty(engine->context(), targetObject, StringConstants::productVar(),
+ productScriptValue);
- QScriptValue data = getDataForProductScriptValue(engine, product);
+ JSValue data = JS_NewObjectClass(engine->context(), engine->dataWithPtrClass());
// If the Rule is in a Module, set up the 'moduleName' property
- if (!module->name.isEmpty())
- data.setProperty(ModuleNameKey, module->name);
- productScriptValue.setData(data);
+ if (!module->name.isEmpty()) {
+ JS_SetPropertyUint32(engine->context(), data, ModuleNameKey,
+ makeJsString(engine->context(), module->name));
+ }
+ defineJsProperty(engine->context(), productScriptValue,
+ StringConstants::dataPropertyInternal(), data);
}
bool findPath(BuildGraphNode *u, BuildGraphNode *v, QList<BuildGraphNode *> &path)
diff --git a/src/lib/corelib/buildgraph/buildgraph.h b/src/lib/corelib/buildgraph/buildgraph.h
index 2909b06bb..1eadb2e20 100644
--- a/src/lib/corelib/buildgraph/buildgraph.h
+++ b/src/lib/corelib/buildgraph/buildgraph.h
@@ -43,9 +43,10 @@
#include <language/forward_decls.h>
#include <tools/qbs_export.h>
-#include <QtCore/qstringlist.h>
+#include <quickjs.h>
-#include <QtScript/qscriptvalue.h>
+#include <QtCore/qstringlist.h>
+#include <QtCore/QVariantMap>
namespace qbs {
namespace Internal {
@@ -88,14 +89,18 @@ void removeGeneratedArtifactFromDisk(const QString &filePath, const Logger &logg
void disconnect(BuildGraphNode *u, BuildGraphNode *v);
void setupScriptEngineForFile(ScriptEngine *engine, const FileContextBaseConstPtr &fileContext,
- QScriptValue targetObject, const ObserveMode &observeMode);
+ JSValue targetObject, const ObserveMode &observeMode);
void setupScriptEngineForProduct(ScriptEngine *engine, ResolvedProduct *product,
- const ResolvedModule *module, QScriptValue targetObject,
+ const ResolvedModule *module, JSValue targetObject,
bool setBuildEnvironment);
QString relativeArtifactFileName(const Artifact *artifact); // Debugging helpers
void doSanityChecks(const ResolvedProjectPtr &project, const Logger &logger);
+void getPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
+ const QVariantMap &properties, const QStringList &extraPropertyNames,
+ JSValueConst extraObject);
+
} // namespace Internal
} // namespace qbs
diff --git a/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.cpp b/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.cpp
index ac6b1dc42..7b333d32f 100644
--- a/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.cpp
+++ b/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.cpp
@@ -46,37 +46,39 @@
namespace qbs {
namespace Internal {
-static QScriptValue toScriptValue(ScriptEngine *engine, const QString &productName,
- const QVariantMap &v, const QString &depName,
- const QualifiedId &moduleName)
+static JSValue toScriptValue(ScriptEngine *engine, const QString &productName,
+ const QVariantMap &v, const QString &depName,
+ const QualifiedId &moduleName)
{
- QScriptValue obj = engine->newObject();
+ JSValue obj = engine->newObject();
bool objIdAddedToObserver = false;
for (auto it = v.begin(); it != v.end(); ++it) {
if (it.value().userType() == QMetaType::QVariantMap) {
- obj.setProperty(it.key(), toScriptValue(engine, productName, it.value().toMap(),
- depName, QualifiedId(moduleName) << it.key()));
+ setJsProperty(engine->context(), obj, it.key(),
+ toScriptValue(engine, productName, it.value().toMap(),
+ depName, QualifiedId(moduleName) << it.key()));
} else {
if (!objIdAddedToObserver) {
objIdAddedToObserver = true;
- engine->observer()->addParameterObjectId(obj.objectId(), productName, depName,
+ engine->observer()->addParameterObjectId(jsObjectId(obj), productName, depName,
moduleName);
}
- engine->setObservedProperty(obj, it.key(), engine->toScriptValue(it.value()));
+ const ScopedJsValue val(engine->context(), engine->toScriptValue(it.value()));
+ engine->setObservedProperty(obj, it.key(), val);
}
}
return obj;
}
-static QScriptValue toScriptValue(ScriptEngine *scriptEngine, const QString &productName,
- const QVariantMap &v, const QString &depName)
+static JSValue toScriptValue(ScriptEngine *scriptEngine, const QString &productName,
+ const QVariantMap &v, const QString &depName)
{
return toScriptValue(scriptEngine, productName, v, depName, {});
}
-QScriptValue dependencyParametersValue(const QString &productName, const QString &dependencyName,
- const QVariantMap &parametersMap, ScriptEngine *engine)
+JSValue dependencyParametersValue(const QString &productName, const QString &dependencyName,
+ const QVariantMap &parametersMap, ScriptEngine *engine)
{
return toScriptValue(engine, productName, parametersMap, dependencyName);
}
diff --git a/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.h b/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.h
index 7e4287be6..2fb4634e8 100644
--- a/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.h
+++ b/src/lib/corelib/buildgraph/dependencyparametersscriptvalue.h
@@ -39,15 +39,16 @@
#ifndef QBS_DEPENDENCYPARAMETERSSCRIPTVALUE_H
#define QBS_DEPENDENCYPARAMETERSSCRIPTVALUE_H
+#include <quickjs.h>
+
#include <QtCore/qvariant.h>
-#include <QtScript/qscriptvalue.h>
namespace qbs {
namespace Internal {
class ScriptEngine;
-QScriptValue dependencyParametersValue(const QString &productName, const QString &dependencyName,
- const QVariantMap &parametersMap, ScriptEngine *engine);
+JSValue dependencyParametersValue(const QString &productName, const QString &dependencyName,
+ const QVariantMap &parametersMap, ScriptEngine *engine);
} // namespace Internal
} // namespace qbs
diff --git a/src/lib/corelib/buildgraph/depscanner.cpp b/src/lib/corelib/buildgraph/depscanner.cpp
index b24ec2d91..e4e10f477 100644
--- a/src/lib/corelib/buildgraph/depscanner.cpp
+++ b/src/lib/corelib/buildgraph/depscanner.cpp
@@ -56,7 +56,7 @@
#include <QtCore/qvariant.h>
-#include <QtScript/qscriptcontext.h>
+#include <vector>
namespace qbs {
namespace Internal {
@@ -158,10 +158,9 @@ UserDependencyScanner::UserDependencyScanner(ResolvedScannerConstPtr scanner,
ScriptEngine *engine)
: m_scanner(std::move(scanner)),
m_engine(engine),
+ m_global(engine->context(), JS_NewObjectProto(engine->context(), m_engine->globalObject())),
m_product(nullptr)
{
- m_global = m_engine->newObject();
- m_global.setPrototype(m_engine->globalObject());
setupScriptEngineForFile(m_engine, m_scanner->scanScript.fileContext(), m_global,
ObserveMode::Disabled); // TODO: QBS-1092
}
@@ -218,7 +217,7 @@ public:
}
};
-QStringList UserDependencyScanner::evaluate(const Artifact *artifact,
+QStringList UserDependencyScanner::evaluate(Artifact *artifact,
const FileResourceBase *fileToScan, const PrivateScriptFunction &script)
{
ScriptEngineActiveFlagGuard guard(m_engine);
@@ -229,38 +228,42 @@ QStringList UserDependencyScanner::evaluate(const Artifact *artifact,
m_scanner->module.get(), m_global, true);
}
- QScriptValueList args;
+ JSValueList args;
args.reserve(fileToScan ? 4 : 3);
- args.push_back(m_global.property(StringConstants::projectVar()));
- args.push_back(m_global.property(StringConstants::productVar()));
+ args.push_back(getJsProperty(m_engine->context(), m_global, StringConstants::projectVar()));
+ args.push_back(getJsProperty(m_engine->context(), m_global, StringConstants::productVar()));
args.push_back(Transformer::translateFileConfig(m_engine, artifact, m_scanner->module->name));
if (fileToScan)
- args.push_back(fileToScan->filePath());
+ args.push_back(makeJsString(m_engine->context(), fileToScan->filePath()));
+ const ScopedJsValueList argsMgr(m_engine->context(), args);
- m_engine->setGlobalObject(m_global);
- QScriptValue &function = script.scriptFunction;
- if (!function.isValid() || function.engine() != m_engine) {
- function = m_engine->evaluate(script.sourceCode());
- if (Q_UNLIKELY(!function.isFunction()))
+ const TemporaryGlobalObjectSetter gos(m_engine, m_global);
+ JSValue &function = script.scriptFunction;
+ if (!JS_IsFunction(m_engine->context(), function)) {
+ function = m_engine->evaluate(JsValueOwner::ScriptEngine, script.sourceCode());
+ if (Q_UNLIKELY(!JS_IsFunction(m_engine->context(), function)))
throw ErrorInfo(Tr::tr("Invalid scan script."), script.location());
}
- QScriptValue result = function.call(QScriptValue(), args);
- m_engine->setGlobalObject(m_global.prototype());
+ const ScopedJsValue result(
+ m_engine->context(),
+ JS_Call(m_engine->context(), function, m_engine->globalObject(),
+ int(args.size()), args.data()));
m_engine->clearRequestedProperties();
- if (Q_UNLIKELY(m_engine->hasErrorOrException(result))) {
- QString msg = Tr::tr("evaluating scan script: ") + m_engine->lastErrorString(result);
- const CodeLocation loc = m_engine->lastErrorLocation(result, script.location());
- m_engine->clearExceptions();
- throw ErrorInfo(msg, loc);
+ if (JsException ex = m_engine->checkAndClearException(script.location())) {
+ ErrorInfo err = ex.toErrorInfo();
+ err.prepend(Tr::tr("Error evaluating scan script"));
+ throw err;
}
QStringList list;
- if (result.isArray()) {
- const int count = result.property(StringConstants::lengthProperty()).toInt32();
+ if (JS_IsArray(m_engine->context(), result)) {
+ const int count = getJsIntProperty(m_engine->context(), result,
+ StringConstants::lengthProperty());
list.reserve(count);
for (qint32 i = 0; i < count; ++i) {
- QScriptValue item = result.property(i);
- if (item.isValid() && !item.isUndefined())
- list.push_back(item.toString());
+ JSValue item = JS_GetPropertyUint32(m_engine->context(), result, i);
+ if (!JS_IsUninitialized(item) && !JS_IsUndefined(item))
+ list.push_back(getJsString(m_engine->context(), item));
+ JS_FreeValue(m_engine->context(), item);
}
}
return list;
diff --git a/src/lib/corelib/buildgraph/depscanner.h b/src/lib/corelib/buildgraph/depscanner.h
index 6b18004f9..51816dbd7 100644
--- a/src/lib/corelib/buildgraph/depscanner.h
+++ b/src/lib/corelib/buildgraph/depscanner.h
@@ -43,11 +43,10 @@
#include <language/forward_decls.h>
#include <language/filetags.h>
#include <language/preparescriptobserver.h>
+#include <tools/scripttools.h>
#include <QtCore/qstringlist.h>
-#include <QtScript/qscriptvalue.h>
-
class ScannerPlugin;
namespace qbs {
@@ -115,11 +114,11 @@ private:
const PropertyMapConstPtr &m2) const override;
bool cacheIsPerFile() const override { return true; }
- QStringList evaluate(const Artifact *artifact, const FileResourceBase *fileToScan, const PrivateScriptFunction &script);
+ QStringList evaluate(Artifact *artifact, const FileResourceBase *fileToScan, const PrivateScriptFunction &script);
ResolvedScannerConstPtr m_scanner;
ScriptEngine *m_engine;
- QScriptValue m_global;
+ ScopedJsValue m_global;
ResolvedProduct *m_product;
};
diff --git a/src/lib/corelib/buildgraph/environmentscriptrunner.cpp b/src/lib/corelib/buildgraph/environmentscriptrunner.cpp
index 841f39a8d..c4810f621 100644
--- a/src/lib/corelib/buildgraph/environmentscriptrunner.cpp
+++ b/src/lib/corelib/buildgraph/environmentscriptrunner.cpp
@@ -51,6 +51,8 @@
#include <tools/stlutils.h>
#include <tools/stringconstants.h>
+#include <quickjs.h>
+
#include <QtCore/qhash.h>
#include <QtCore/qvariant.h>
@@ -165,38 +167,40 @@ void EnvironmentScriptRunner::setupEnvironment()
continue;
RulesEvaluationContext::Scope s(m_evalContext);
- QScriptValue envScriptContext = engine()->newObject();
- envScriptContext.setPrototype(engine()->globalObject());
+ JSContext * const ctx = engine()->context();
+ ScopedJsValue envScriptContext(ctx, JS_NewObjectProto(ctx, engine()->globalObject()));
setupScriptEngineForProduct(engine(), m_product, module, envScriptContext, false);
const QString &productKey = StringConstants::productVar();
const QString &projectKey = StringConstants::projectVar();
- m_evalContext->scope().setProperty(productKey, envScriptContext.property(productKey));
- m_evalContext->scope().setProperty(projectKey, envScriptContext.property(projectKey));
+ setJsProperty(ctx, m_evalContext->scope(), productKey,
+ getJsProperty(ctx, envScriptContext, productKey));
+ setJsProperty(ctx, m_evalContext->scope(), projectKey,
+ getJsProperty(ctx, envScriptContext, projectKey));
if (m_envType == RunEnv) {
- QScriptValue configArray = engine()->newArray(m_runEnvConfig.size());
+ JSValue configArray = JS_NewArray(ctx);
for (int i = 0; i < m_runEnvConfig.size(); ++i)
- configArray.setProperty(i, QScriptValue(m_runEnvConfig.at(i)));
- m_evalContext->scope().setProperty(QStringLiteral("config"), configArray);
+ JS_SetPropertyUint32(ctx, configArray, i, makeJsString(ctx, m_runEnvConfig.at(i)));
+ JS_SetPropertyStr(ctx, m_evalContext->scope(), "config", configArray);
}
setupScriptEngineForFile(engine(), setupScript.fileContext(), m_evalContext->scope(),
ObserveMode::Disabled);
// TODO: Cache evaluate result
- QScriptValue fun = engine()->evaluate(setupScript.sourceCode(),
- setupScript.location().filePath(),
- setupScript.location().line());
- QBS_CHECK(fun.isFunction());
- const QScriptValueList svArgs = ScriptEngine::argumentList(scriptFunctionArgs,
- m_evalContext->scope());
- const QScriptValue res = fun.call(QScriptValue(), svArgs);
- engine()->releaseResourcesOfScriptObjects();
- if (Q_UNLIKELY(engine()->hasErrorOrException(res))) {
+ ScopedJsValue fun(ctx, engine()->evaluate(JsValueOwner::Caller, setupScript.sourceCode(),
+ setupScript.location().filePath(),
+ setupScript.location().line()));
+ QBS_CHECK(JS_IsFunction(ctx, fun));
+ const ScopedJsValueList svArgs = engine()->argumentList(scriptFunctionArgs,
+ m_evalContext->scope());
+ JSValueList argsForFun = svArgs;
+ JS_Call(ctx, fun, engine()->globalObject(), int(argsForFun.size()), argsForFun.data());
+ if (const JsException ex = engine()->checkAndClearException(setupScript.location())) {
const QString scriptName = m_envType == BuildEnv
? StringConstants::setupBuildEnvironmentProperty()
: StringConstants::setupRunEnvironmentProperty();
- throw ErrorInfo(Tr::tr("Error running %1 script for product '%2': %3")
- .arg(scriptName, m_product->fullDisplayName(),
- engine()->lastErrorString(res)),
- engine()->lastErrorLocation(res, setupScript.location()));
+ ErrorInfo err = ex.toErrorInfo();
+ err.prepend(Tr::tr("Error running %1 script for product '%2'")
+ .arg(scriptName, m_product->fullDisplayName()));
+ throw err;
}
}
diff --git a/src/lib/corelib/buildgraph/jscommandexecutor.cpp b/src/lib/corelib/buildgraph/jscommandexecutor.cpp
index abebc82b8..4d92bf7c3 100644
--- a/src/lib/corelib/buildgraph/jscommandexecutor.cpp
+++ b/src/lib/corelib/buildgraph/jscommandexecutor.cpp
@@ -40,7 +40,6 @@
#include "jscommandexecutor.h"
-#include "artifact.h"
#include "buildgraph.h"
#include "rulecommands.h"
#include "transformer.h"
@@ -55,7 +54,10 @@
#include <tools/qbsassert.h>
#include <tools/qttools.h>
+#include <quickjs.h>
+
#include <QtCore/qeventloop.h>
+#include <QtCore/qmutex.h>
#include <QtCore/qpointer.h>
#include <QtCore/qthread.h>
#include <QtCore/qtimer.h>
@@ -87,10 +89,11 @@ public:
void cancel(const qbs::ErrorInfo &reason)
{
+ QMutexLocker locker(&m_resultMutex);
m_result.success = !reason.hasError();
m_result.errorMessage = reason.toString();
if (m_scriptEngine)
- m_scriptEngine->abortEvaluation();
+ m_scriptEngine->cancel();
m_cancelled = true;
}
@@ -122,36 +125,30 @@ private:
m_result.success = true;
m_result.errorMessage.clear();
ScriptEngine * const scriptEngine = provideScriptEngine();
- QScriptValue scope = scriptEngine->newObject();
- scope.setPrototype(scriptEngine->globalObject());
- m_scriptEngine->clearRequestedProperties();
+ JSContext * const ctx = scriptEngine->context();
+ const ScopedJsValue scope(ctx, JS_NewObject(scriptEngine->context()));
setupScriptEngineForFile(scriptEngine,
transformer->rule->prepareScript.fileContext(), scope,
ObserveMode::Enabled);
-
- QScriptValue importScopeForSourceCode;
+ ScopedJsValue importScopeForSourceCode(ctx, JS_UNDEFINED);
if (!cmd->scopeName().isEmpty())
- importScopeForSourceCode = scope.property(cmd->scopeName());
+ importScopeForSourceCode.setValue(getJsProperty(ctx, scope, cmd->scopeName()));
setupScriptEngineForProduct(scriptEngine, transformer->product().get(),
transformer->rule->module.get(), scope, true);
- transformer->setupInputs(scope);
- transformer->setupOutputs(scope);
- transformer->setupExplicitlyDependsOn(scope);
-
- for (QVariantMap::const_iterator it = cmd->properties().constBegin();
- it != cmd->properties().constEnd(); ++it) {
- scope.setProperty(it.key(), scriptEngine->toScriptValue(it.value()));
- }
-
- scriptEngine->setGlobalObject(scope);
- if (importScopeForSourceCode.isObject())
- scriptEngine->currentContext()->pushScope(importScopeForSourceCode);
- scriptEngine->evaluate(cmd->sourceCode());
- scriptEngine->releaseResourcesOfScriptObjects();
- if (importScopeForSourceCode.isObject())
- scriptEngine->currentContext()->popScope();
- scriptEngine->setGlobalObject(scope.prototype());
+ transformer->setupInputs(scriptEngine, scope);
+ transformer->setupOutputs(scriptEngine, scope);
+ transformer->setupExplicitlyDependsOn(scriptEngine, scope);
+
+ for (auto it = cmd->properties().constBegin(); it != cmd->properties().constEnd(); ++it)
+ setJsProperty(ctx, scope, it.key(), scriptEngine->toScriptValue(it.value()));
+
+ const TemporaryGlobalObjectSetter gos(scriptEngine, scope);
+ JSValueList scopeChain;
+ if (JS_IsObject(importScopeForSourceCode))
+ scopeChain << importScopeForSourceCode;
+ const ScopedJsValue res(ctx, scriptEngine->evaluate(JsValueOwner::Caller, cmd->sourceCode(),
+ {}, 1, scopeChain));
transformer->propertiesRequestedInCommands
+= scriptEngine->propertiesRequestedInScript();
unite(transformer->propertiesRequestedFromArtifactInCommands,
@@ -168,14 +165,17 @@ private:
std::make_pair(p->uniqueName(), p->exportedModule));
}
scriptEngine->clearRequestedProperties();
- if (scriptEngine->hasUncaughtException()) {
+ if (const JsException exception = scriptEngine->checkAndClearException(cmd->codeLocation())) {
// ### We don't know the line number of the command's sourceCode property assignment.
- setError(scriptEngine->uncaughtException().toString(), cmd->codeLocation());
+ setError(exception.message(), cmd->codeLocation());
}
}
void setError(const QString &errorMessage, const CodeLocation &codeLocation)
{
+ QMutexLocker locker(&m_resultMutex);
+ if (m_cancelled)
+ return;
m_result.success = false;
m_result.errorMessage = errorMessage;
m_result.errorLocation = codeLocation;
@@ -185,12 +185,15 @@ private:
{
if (!m_scriptEngine)
m_scriptEngine = ScriptEngine::create(m_logger, EvalContext::JsCommand);
+ else
+ m_scriptEngine->reset();
return m_scriptEngine.get();
}
Logger m_logger;
std::unique_ptr<ScriptEngine> m_scriptEngine;
JavaScriptCommandResult m_result;
+ QMutex m_resultMutex;
bool m_running = false;
bool m_cancelled = false;
};
@@ -258,11 +261,8 @@ bool JsCommandExecutor::doStart()
void JsCommandExecutor::cancel(const qbs::ErrorInfo &reason)
{
- if (m_running && (!dryRun() || command()->ignoreDryRun()))
- QTimer::singleShot(0, m_objectInThread, [objectInThread = QPointer<JsCommandExecutorThreadObject>{m_objectInThread}, reason] {
- if (objectInThread)
- objectInThread->cancel(reason);
- });
+ if (m_running && (!dryRun() || command()->ignoreDryRun()) && m_objectInThread)
+ m_objectInThread->cancel(reason);
}
void JsCommandExecutor::onJavaScriptCommandFinished()
diff --git a/src/lib/corelib/buildgraph/processcommandexecutor.cpp b/src/lib/corelib/buildgraph/processcommandexecutor.cpp
index e687342e1..0058b940e 100644
--- a/src/lib/corelib/buildgraph/processcommandexecutor.cpp
+++ b/src/lib/corelib/buildgraph/processcommandexecutor.cpp
@@ -61,12 +61,12 @@
#include <tools/shellutils.h>
#include <tools/stringconstants.h>
+#include <quickjs.h>
+
#include <QtCore/qdir.h>
#include <QtCore/qtemporaryfile.h>
#include <QtCore/qtimer.h>
-#include <QtScript/qscriptvalue.h>
-
namespace qbs {
namespace Internal {
@@ -215,34 +215,39 @@ QString ProcessCommandExecutor::filterProcessOutput(const QByteArray &_output,
if (filterFunctionSource.isEmpty())
return output;
- QScriptValue scope = scriptEngine()->newObject();
- scope.setPrototype(scriptEngine()->globalObject());
- for (QVariantMap::const_iterator it = command()->properties().constBegin();
- it != command()->properties().constEnd(); ++it) {
- scope.setProperty(it.key(), scriptEngine()->toScriptValue(it.value()));
+ JSContext * const ctx = scriptEngine()->context();
+ const ScopedJsValue scope(ctx, JS_NewObjectProto(ctx, scriptEngine()->globalObject()));
+ for (auto it = command()->properties().constBegin();
+ it != command()->properties().constEnd(); ++it) {
+ setJsProperty(ctx, scope, it.key(), scriptEngine()->toScriptValue(it.value()));
}
- TemporaryGlobalObjectSetter tgos(scope);
- QScriptValue filterFunction = scriptEngine()->evaluate(QLatin1String("var f = ")
- + filterFunctionSource
- + QLatin1String("; f"));
- if (!filterFunction.isFunction()) {
+ TemporaryGlobalObjectSetter tgos(scriptEngine(), scope);
+ const ScopedJsValue filterFunction(
+ ctx,
+ scriptEngine()->evaluate(JsValueOwner::Caller,
+ QLatin1String("var f = ")
+ + filterFunctionSource
+ + QLatin1String("; f")));
+ if (!JS_IsFunction(scriptEngine()->context(), filterFunction)) {
logger().printWarning(ErrorInfo(Tr::tr("Error in filter function: %1.\n%2")
- .arg(filterFunctionSource, filterFunction.toString())));
+ .arg(filterFunctionSource,
+ getJsString(scriptEngine()->context(), filterFunction))));
return output;
}
- QScriptValue outputArg = scriptEngine()->newArray(1);
- outputArg.setProperty(0, scriptEngine()->toScriptValue(output));
- QScriptValue filteredOutput = filterFunction.call(scriptEngine()->undefinedValue(), outputArg);
- if (scriptEngine()->hasErrorOrException(filteredOutput)) {
- logger().printWarning(ErrorInfo(Tr::tr("Error when calling output filter function: %1")
- .arg(scriptEngine()->lastErrorString(filteredOutput)),
- scriptEngine()->lastErrorLocation(filteredOutput)));
+ const ScopedJsValue outputArg(ctx, scriptEngine()->toScriptValue(output));
+ JSValue outputArgForCall = outputArg;
+ const ScopedJsValue filteredOutput(
+ ctx, JS_Call(ctx, filterFunction, JS_UNDEFINED, 1, &outputArgForCall));
+ if (const JsException ex = scriptEngine()->checkAndClearException({})) {
+ ErrorInfo err = ex.toErrorInfo();
+ err.prepend(Tr::tr("Error when calling output filter function"));
+ logger().printWarning(err);
return output;
}
- return filteredOutput.toString();
+ return getJsString(ctx, filteredOutput);
}
static QProcess::ProcessError saveToFile(const QString &filePath, const QByteArray &content)
diff --git a/src/lib/corelib/buildgraph/productbuilddata.cpp b/src/lib/corelib/buildgraph/productbuilddata.cpp
index db51b2b9f..6ec01a1ce 100644
--- a/src/lib/corelib/buildgraph/productbuilddata.cpp
+++ b/src/lib/corelib/buildgraph/productbuilddata.cpp
@@ -102,7 +102,6 @@ void ProductBuildData::addFileTagToArtifact(Artifact *artifact, const FileTag &t
ArtifactSetByFileTag ProductBuildData::artifactsByFileTag() const
{
- std::lock_guard<std::mutex> l(m_artifactsMapMutex);
return m_artifactsByFileTag;
}
@@ -124,7 +123,6 @@ void ProductBuildData::addRescuableArtifactData(const QString &filePath,
bool ProductBuildData::checkAndSetJsArtifactsMapUpToDateFlag()
{
- std::lock_guard<std::mutex> l(m_artifactsMapMutex);
if (!m_jsArtifactsMapUpToDate) {
m_jsArtifactsMapUpToDate = true;
return false;
diff --git a/src/lib/corelib/buildgraph/productbuilddata.h b/src/lib/corelib/buildgraph/productbuilddata.h
index a7660af27..f6c531713 100644
--- a/src/lib/corelib/buildgraph/productbuilddata.h
+++ b/src/lib/corelib/buildgraph/productbuilddata.h
@@ -86,6 +86,9 @@ public:
void setBuildPriority(unsigned int prio) { m_buildPriority = prio; }
bool checkAndSetJsArtifactsMapUpToDateFlag();
+ std::unique_lock<std::mutex> getArtifactsMapLock() {
+ return std::unique_lock(m_artifactsMapMutex);
+ }
template<PersistentPool::OpType opType> void completeSerializationOp(PersistentPool &pool)
{
diff --git a/src/lib/corelib/buildgraph/projectbuilddata.cpp b/src/lib/corelib/buildgraph/projectbuilddata.cpp
index e0e70e650..c229a6171 100644
--- a/src/lib/corelib/buildgraph/projectbuilddata.cpp
+++ b/src/lib/corelib/buildgraph/projectbuilddata.cpp
@@ -473,7 +473,7 @@ ScriptEngine *BuildDataResolver::engine() const
return evalContext()->engine();
}
-QScriptValue BuildDataResolver::scope() const
+JSValue BuildDataResolver::scope() const
{
return evalContext()->scope();
}
diff --git a/src/lib/corelib/buildgraph/projectbuilddata.h b/src/lib/corelib/buildgraph/projectbuilddata.h
index 930344435..416651912 100644
--- a/src/lib/corelib/buildgraph/projectbuilddata.h
+++ b/src/lib/corelib/buildgraph/projectbuilddata.h
@@ -47,11 +47,11 @@
#include <tools/set.h>
#include <tools/qttools.h>
+#include <quickjs.h>
+
#include <QtCore/qlist.h>
#include <QtCore/qstring.h>
-#include <QtScript/qscriptvalue.h>
-
#include <unordered_map>
namespace qbs {
@@ -126,7 +126,7 @@ private:
RulesEvaluationContextPtr evalContext() const;
ScriptEngine *engine() const;
- QScriptValue scope() const;
+ JSValue scope() const;
TopLevelProjectPtr m_project;
Logger m_logger;
diff --git a/src/lib/corelib/buildgraph/qtmocscanner.cpp b/src/lib/corelib/buildgraph/qtmocscanner.cpp
index a911f4a50..7df84e52c 100644
--- a/src/lib/corelib/buildgraph/qtmocscanner.cpp
+++ b/src/lib/corelib/buildgraph/qtmocscanner.cpp
@@ -54,9 +54,6 @@
#include <QtCore/qdebug.h>
-#include <QtScript/qscriptcontext.h>
-#include <QtScript/qscriptengine.h>
-
namespace qbs {
namespace Internal {
@@ -102,21 +99,23 @@ private:
static QString qtMocScannerJsName() { return QStringLiteral("QtMocScanner"); }
-QtMocScanner::QtMocScanner(const ResolvedProductPtr &product, QScriptValue targetScriptValue)
- : m_tags(*commonFileTags())
+QtMocScanner::QtMocScanner(const ResolvedProductPtr &product, ScriptEngine *engine, JSValue targetScriptValue)
+ : m_engine(engine)
+ , m_tags(*commonFileTags())
, m_product(product)
- , m_targetScriptValue(targetScriptValue)
+ , m_targetScriptValue(JS_DupValue(engine->context(), targetScriptValue))
{
- const auto engine = static_cast<ScriptEngine *>(targetScriptValue.engine());
- QScriptValue scannerObj = engine->newObject();
- targetScriptValue.setProperty(qtMocScannerJsName(), scannerObj);
- QScriptValue applyFunction = engine->newFunction(&js_apply, this);
- scannerObj.setProperty(QStringLiteral("apply"), applyFunction);
+ JSValue scannerObj = JS_NewObjectClass(engine->context(), engine->dataWithPtrClass());
+ attachPointerTo(scannerObj, this);
+ setJsProperty(engine->context(), targetScriptValue, qtMocScannerJsName(), scannerObj);
+ JSValue applyFunction = JS_NewCFunction(engine->context(), &js_apply, "QtMocScanner", 1);
+ setJsProperty(engine->context(), scannerObj, QStringLiteral("apply"), applyFunction);
}
QtMocScanner::~QtMocScanner()
{
- m_targetScriptValue.setProperty(qtMocScannerJsName(), QScriptValue());
+ setJsProperty(m_engine->context(), m_targetScriptValue, qtMocScannerJsName(), JS_UNDEFINED);
+ JS_FreeValue(m_engine->context(), m_targetScriptValue);
}
static RawScanResult runScanner(ScannerPlugin *scanner, const Artifact *artifact)
@@ -199,22 +198,24 @@ void QtMocScanner::findIncludedMocCppFiles()
}
}
-QScriptValue QtMocScanner::js_apply(QScriptContext *ctx, QScriptEngine *engine,
- QtMocScanner *that)
+JSValue QtMocScanner::js_apply(JSContext *ctx, JSValue this_val, int argc, JSValue *argv)
{
- QScriptValue input = ctx->argument(0);
- return that->apply(engine, attachedPointer<Artifact>(input));
+ if (argc < 1)
+ return throwError(ctx, Tr::tr("QtMocScanner.apply() requires an argument."));
+ ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const auto scanner = attachedPointer<QtMocScanner>(this_val, engine->dataWithPtrClass());
+ return scanner->apply(engine, attachedPointer<Artifact>(argv[0], engine->dataWithPtrClass()));
}
-static QScriptValue scannerCountError(QScriptEngine *engine, size_t scannerCount,
- const QString &fileTag)
+static JSValue scannerCountError(ScriptEngine *engine, size_t scannerCount,
+ const QString &fileTag)
{
- return engine->currentContext()->throwError(
- Tr::tr("There are %1 scanners for the file tag %2. "
- "Expected is exactly one.").arg(scannerCount).arg(fileTag));
+ return throwError(engine->context(),
+ Tr::tr("There are %1 scanners for the file tag %2. "
+ "Expected is exactly one.").arg(scannerCount).arg(fileTag));
}
-QScriptValue QtMocScanner::apply(QScriptEngine *engine, const Artifact *artifact)
+JSValue QtMocScanner::apply(ScriptEngine *engine, const Artifact *artifact)
{
if (!m_cppScanner) {
auto scanners = ScannerPluginManager::scannersForFileTag(m_tags.cpp);
@@ -266,11 +267,13 @@ QScriptValue QtMocScanner::apply(QScriptEngine *engine, const Artifact *artifact
<< "mustCompile:" << mustCompile
<< "hasPluginMetaDataMacro:" << hasPluginMetaDataMacro;
- QScriptValue obj = engine->newObject();
- obj.setProperty(QStringLiteral("hasQObjectMacro"), hasQObjectMacro);
- obj.setProperty(QStringLiteral("mustCompile"), mustCompile);
- obj.setProperty(QStringLiteral("hasPluginMetaDataMacro"), hasPluginMetaDataMacro);
- static_cast<ScriptEngine *>(engine)->setUsesIo();
+ JSValue obj = engine->newObject();
+ JSContext * const ctx = m_engine->context();
+ setJsProperty(ctx, obj, QStringLiteral("hasQObjectMacro"), JS_NewBool(ctx, hasQObjectMacro));
+ setJsProperty(ctx, obj, QStringLiteral("mustCompile"), JS_NewBool(ctx, mustCompile));
+ setJsProperty(ctx, obj, QStringLiteral("hasPluginMetaDataMacro"),
+ JS_NewBool(ctx, hasPluginMetaDataMacro));
+ engine->setUsesIo();
return obj;
}
diff --git a/src/lib/corelib/buildgraph/qtmocscanner.h b/src/lib/corelib/buildgraph/qtmocscanner.h
index 6455383f3..2e2a00007 100644
--- a/src/lib/corelib/buildgraph/qtmocscanner.h
+++ b/src/lib/corelib/buildgraph/qtmocscanner.h
@@ -41,12 +41,11 @@
#define QBS_QTMOCSCANNER_H
#include <language/language.h>
+#include <quickjs.h>
#include <QtCore/qhash.h>
#include <QtCore/qstring.h>
-#include <QtScript/qscriptvalue.h>
-
QT_BEGIN_NAMESPACE
class QScriptContext;
QT_END_NAMESPACE
@@ -55,6 +54,7 @@ class ScannerPlugin;
namespace qbs {
namespace Internal {
+class ScriptEngine;
class Artifact;
struct CommonFileTags;
@@ -62,17 +62,19 @@ struct CommonFileTags;
class QtMocScanner
{
public:
- explicit QtMocScanner(const ResolvedProductPtr &product, QScriptValue targetScriptValue);
+ explicit QtMocScanner(const ResolvedProductPtr &product, ScriptEngine *engine,
+ JSValue targetScriptValue);
~QtMocScanner();
private:
void findIncludedMocCppFiles();
- static QScriptValue js_apply(QScriptContext *ctx, QScriptEngine *engine, QtMocScanner *that);
- QScriptValue apply(QScriptEngine *engine, const Artifact *artifact);
+ static JSValue js_apply(JSContext *ctx, JSValue this_val, int argc, JSValue *argv);
+ JSValue apply(ScriptEngine *engine, const Artifact *artifact);
+ ScriptEngine * const m_engine;
const CommonFileTags &m_tags;
const ResolvedProductPtr &m_product;
- QScriptValue m_targetScriptValue;
+ JSValue m_targetScriptValue;
QHash<QString, QString> m_includedMocCppFiles;
ScannerPlugin *m_cppScanner = nullptr;
};
diff --git a/src/lib/corelib/buildgraph/rulecommands.cpp b/src/lib/corelib/buildgraph/rulecommands.cpp
index 9eed7c715..6acd1d68c 100644
--- a/src/lib/corelib/buildgraph/rulecommands.cpp
+++ b/src/lib/corelib/buildgraph/rulecommands.cpp
@@ -39,6 +39,8 @@
****************************************************************************/
#include "rulecommands.h"
+
+#include <language/scriptengine.h>
#include <logging/translator.h>
#include <tools/error.h>
#include <tools/fileinfo.h>
@@ -48,9 +50,6 @@
#include <QtCore/qfile.h>
-#include <QtScript/qscriptengine.h>
-#include <QtScript/qscriptvalueiterator.h>
-
namespace qbs {
namespace Internal {
@@ -79,10 +78,11 @@ static QString stdoutFilterFunctionProperty() { return QStringLiteral("stdoutFil
static QString timeoutProperty() { return QStringLiteral("timeout"); }
static QString workingDirProperty() { return QStringLiteral("workingDirectory"); }
-static QString invokedSourceCode(const QScriptValue &codeOrFunction)
+static QString invokedSourceCode(JSContext *ctx, const JSValue &codeOrFunction)
{
- const QString &code = codeOrFunction.toString();
- return codeOrFunction.isFunction() ? QStringLiteral("(") + code + QStringLiteral(")()") : code;
+ const QString &code = getJsString(ctx, codeOrFunction);
+ return JS_IsFunction(ctx, codeOrFunction)
+ ? QStringLiteral("(") + code + QStringLiteral(")()") : code;
}
AbstractCommand::AbstractCommand()
@@ -110,17 +110,18 @@ bool AbstractCommand::equals(const AbstractCommand *other) const
&& m_properties == other->m_properties;
}
-void AbstractCommand::fillFromScriptValue(const QScriptValue *scriptValue, const CodeLocation &codeLocation)
+void AbstractCommand::fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue,
+ const CodeLocation &codeLocation)
{
- m_description = scriptValue->property(StringConstants::descriptionProperty()).toString();
- m_extendedDescription = scriptValue->property(extendedDescriptionProperty()).toString();
- m_highlight = scriptValue->property(highlightProperty()).toString();
- m_ignoreDryRun = scriptValue->property(ignoreDryRunProperty()).toBool();
- m_silent = scriptValue->property(silentProperty()).toBool();
- m_jobPool = scriptValue->property(StringConstants::jobPoolProperty()).toString();
- const auto timeoutScriptValue = scriptValue->property(timeoutProperty());
- if (!timeoutScriptValue.isUndefined() && !timeoutScriptValue.isNull())
- m_timeout = timeoutScriptValue.toInt32();
+ m_description = getJsStringProperty(ctx, *scriptValue, StringConstants::descriptionProperty());
+ m_extendedDescription = getJsStringProperty(ctx, *scriptValue, extendedDescriptionProperty());
+ m_highlight = getJsStringProperty(ctx, *scriptValue, highlightProperty());
+ m_ignoreDryRun = getJsBoolProperty(ctx, *scriptValue, ignoreDryRunProperty());
+ m_silent = getJsBoolProperty(ctx, *scriptValue, silentProperty());
+ m_jobPool = getJsStringProperty(ctx, *scriptValue, StringConstants::jobPoolProperty());
+ const auto timeoutScriptValue = getJsProperty(ctx, *scriptValue, timeoutProperty());
+ if (!JS_IsUndefined(timeoutScriptValue) && !JS_IsNull(timeoutScriptValue))
+ m_timeout = JS_VALUE_GET_INT(timeoutScriptValue);
m_codeLocation = codeLocation;
m_predefinedProperties
@@ -148,94 +149,95 @@ void AbstractCommand::store(PersistentPool &pool)
serializationOp<PersistentPool::Store>(pool);
}
-void AbstractCommand::applyCommandProperties(const QScriptValue *scriptValue)
+void AbstractCommand::applyCommandProperties(JSContext *ctx, const JSValue *scriptValue)
{
- QScriptValueIterator it(*scriptValue);
- while (it.hasNext()) {
- it.next();
- if (m_predefinedProperties.contains(it.name()))
- continue;
- const QVariant value = it.value().toVariant();
- if (QMetaType::Type(value.userType()) == QMetaType::QObjectStar
- || it.value().scriptClass()
- || it.value().data().isValid()) {
+ handleJsProperties(ctx, *scriptValue, [this, ctx](const JSAtom &prop, const JSPropertyDescriptor &desc) {
+ const QString name = getJsString(ctx, prop);
+ if (m_predefinedProperties.contains(name))
+ return;
+ // TODO: Use script class for command objects, don't allow setting random properties
+ if (!isSimpleValue(desc.value)) {
throw ErrorInfo(Tr::tr("Property '%1' has a type unsuitable for storing in a command "
- "object.").arg(it.name()), m_codeLocation);
+ "object.").arg(name), m_codeLocation);
}
- m_properties.insert(it.name(), value);
- }
-}
-
-static QScriptValue js_CommandBase(QScriptContext *context, QScriptEngine *engine)
-{
- QScriptValue cmd = context->thisObject();
- QBS_ASSERT(context->isCalledAsConstructor(), cmd = engine->newObject());
- cmd.setProperty(StringConstants::descriptionProperty(),
- engine->toScriptValue(AbstractCommand::defaultDescription()));
- cmd.setProperty(extendedDescriptionProperty(),
- engine->toScriptValue(AbstractCommand::defaultExtendedDescription()));
- cmd.setProperty(highlightProperty(),
- engine->toScriptValue(AbstractCommand::defaultHighLight()));
- cmd.setProperty(ignoreDryRunProperty(),
- engine->toScriptValue(AbstractCommand::defaultIgnoreDryRun()));
- cmd.setProperty(silentProperty(),
- engine->toScriptValue(AbstractCommand::defaultIsSilent()));
- cmd.setProperty(timeoutProperty(),
- engine->toScriptValue(AbstractCommand::defaultTimeout()));
+ m_properties.insert(name, getJsVariant(ctx, desc.value));
+ });
+}
+
+static JSValue js_CommandBase(JSContext *ctx)
+{
+ const JSValue cmd = JS_NewObject(ctx);
+ setJsProperty(ctx, cmd, StringConstants::descriptionProperty(),
+ makeJsString(ctx, AbstractCommand::defaultDescription()));
+ setJsProperty(ctx, cmd, extendedDescriptionProperty(),
+ makeJsString(ctx, AbstractCommand::defaultExtendedDescription()));
+ setJsProperty(ctx, cmd, highlightProperty(),
+ makeJsString(ctx, AbstractCommand::defaultHighLight()));
+ setJsProperty(ctx, cmd, ignoreDryRunProperty(),
+ JS_NewBool(ctx, AbstractCommand::defaultIgnoreDryRun()));
+ setJsProperty(ctx, cmd, silentProperty(),
+ JS_NewBool(ctx, AbstractCommand::defaultIsSilent()));
+ setJsProperty(ctx, cmd, timeoutProperty(),
+ JS_NewInt32(ctx, AbstractCommand::defaultTimeout()));
return cmd;
}
-static QScriptValue js_Command(QScriptContext *context, QScriptEngine *engine)
+static JSValue js_Command(JSContext *ctx, JSValueConst, JSValueConst,
+ int argc, JSValueConst *argv, int)
{
- if (Q_UNLIKELY(!context->isCalledAsConstructor()))
- return context->throwError(Tr::tr("Command constructor called without new."));
-
static ProcessCommandPtr commandPrototype = ProcessCommand::create();
-
- QScriptValue program = context->argument(0);
- if (program.isUndefined())
- program = engine->toScriptValue(commandPrototype->program());
- QScriptValue arguments = context->argument(1);
- if (arguments.isUndefined())
- arguments = engine->toScriptValue(commandPrototype->arguments());
- QScriptValue cmd = js_CommandBase(context, engine);
- cmd.setProperty(StringConstants::classNameProperty(),
- engine->toScriptValue(StringConstants::commandType()));
- cmd.setProperty(programProperty(), program);
- cmd.setProperty(argumentsProperty(), arguments);
- cmd.setProperty(workingDirProperty(),
- engine->toScriptValue(commandPrototype->workingDir()));
- cmd.setProperty(maxExitCodeProperty(),
- engine->toScriptValue(commandPrototype->maxExitCode()));
- cmd.setProperty(stdoutFilterFunctionProperty(),
- engine->toScriptValue(commandPrototype->stdoutFilterFunction()));
- cmd.setProperty(stderrFilterFunctionProperty(),
- engine->toScriptValue(commandPrototype->stderrFilterFunction()));
- cmd.setProperty(responseFileThresholdProperty(),
- engine->toScriptValue(commandPrototype->responseFileThreshold()));
- cmd.setProperty(responseFileArgumentIndexProperty(),
- engine->toScriptValue(commandPrototype->responseFileArgumentIndex()));
- cmd.setProperty(responseFileUsagePrefixProperty(),
- engine->toScriptValue(commandPrototype->responseFileUsagePrefix()));
- cmd.setProperty(responseFileSeparatorProperty(),
- engine->toScriptValue(commandPrototype->responseFileSeparator()));
- cmd.setProperty(stdoutFilePathProperty(),
- engine->toScriptValue(commandPrototype->stdoutFilePath()));
- cmd.setProperty(stderrFilePathProperty(),
- engine->toScriptValue(commandPrototype->stderrFilePath()));
- cmd.setProperty(environmentProperty(),
- engine->toScriptValue(commandPrototype->environment().toStringList()));
- cmd.setProperty(ignoreDryRunProperty(),
- engine->toScriptValue(commandPrototype->ignoreDryRun()));
+ JSValue program = JS_UNDEFINED;
+ if (argc > 0)
+ program = JS_DupValue(ctx, argv[0]);
+ if (JS_IsUndefined(program))
+ program = makeJsString(ctx, commandPrototype->program());
+ JSValue arguments = JS_UNDEFINED;
+ if (argc > 1)
+ arguments = JS_DupValue(ctx, argv[1]);
+ if (JS_IsUndefined(arguments))
+ arguments = makeJsStringList(ctx, commandPrototype->arguments());
+ if (JS_IsString(arguments)) {
+ JSValue args = JS_NewArray(ctx);
+ JS_SetPropertyUint32(ctx, args, 0, arguments);
+ arguments = args;
+ }
+ JSValue cmd = js_CommandBase(ctx);
+ setJsProperty(ctx, cmd, StringConstants::classNameProperty(),
+ makeJsString(ctx, StringConstants::commandType()));
+ setJsProperty(ctx, cmd, programProperty(), program);
+ setJsProperty(ctx, cmd, argumentsProperty(), arguments);
+ setJsProperty(ctx, cmd, workingDirProperty(),
+ makeJsString(ctx, commandPrototype->workingDir()));
+ setJsProperty(ctx, cmd, maxExitCodeProperty(),
+ JS_NewInt32(ctx, commandPrototype->maxExitCode()));
+ setJsProperty(ctx, cmd, stdoutFilterFunctionProperty(),
+ makeJsString(ctx, commandPrototype->stdoutFilterFunction()));
+ setJsProperty(ctx, cmd, stderrFilterFunctionProperty(),
+ makeJsString(ctx, commandPrototype->stderrFilterFunction()));
+ setJsProperty(ctx, cmd, responseFileThresholdProperty(),
+ JS_NewInt32(ctx, commandPrototype->responseFileThreshold()));
+ setJsProperty(ctx, cmd, responseFileArgumentIndexProperty(),
+ JS_NewInt32(ctx, commandPrototype->responseFileArgumentIndex()));
+ setJsProperty(ctx, cmd, responseFileUsagePrefixProperty(),
+ makeJsString(ctx, commandPrototype->responseFileUsagePrefix()));
+ setJsProperty(ctx, cmd, responseFileSeparatorProperty(),
+ makeJsString(ctx, commandPrototype->responseFileSeparator()));
+ setJsProperty(ctx, cmd, stdoutFilePathProperty(),
+ makeJsString(ctx, commandPrototype->stdoutFilePath()));
+ setJsProperty(ctx, cmd, stderrFilePathProperty(),
+ makeJsString(ctx, commandPrototype->stderrFilePath()));
+ setJsProperty(ctx, cmd, environmentProperty(),
+ makeJsStringList(ctx, commandPrototype->environment().toStringList()));
+ setJsProperty(ctx, cmd, ignoreDryRunProperty(),
+ JS_NewBool(ctx, commandPrototype->ignoreDryRun()));
return cmd;
}
-void ProcessCommand::setupForJavaScript(QScriptValue targetObject)
+void ProcessCommand::setupForJavaScript(ScriptEngine *engine, JSValue targetObject)
{
- QBS_CHECK(targetObject.isObject());
- QScriptValue ctor = targetObject.engine()->newFunction(js_Command, 2);
- targetObject.setProperty(StringConstants::commandType(), ctor);
+ engine->registerClass(StringConstants::commandType().toUtf8().constData(), js_Command, nullptr,
+ targetObject);
}
ProcessCommand::ProcessCommand()
@@ -289,40 +291,37 @@ bool ProcessCommand::equals(const AbstractCommand *otherAbstractCommand) const
&& m_environment == other->m_environment;
}
-void ProcessCommand::fillFromScriptValue(const QScriptValue *scriptValue, const CodeLocation &codeLocation)
-{
- AbstractCommand::fillFromScriptValue(scriptValue, codeLocation);
- m_program = scriptValue->property(programProperty()).toString();
- m_arguments = scriptValue->property(argumentsProperty()).toVariant().toStringList();
- m_workingDir = scriptValue->property(workingDirProperty()).toString();
- m_maxExitCode = scriptValue->property(maxExitCodeProperty()).toInt32();
-
- // toString() is required, presumably due to QtScript bug that manifests itself on Windows
- const QScriptValue stdoutFilterFunction
- = scriptValue->property(stdoutFilterFunctionProperty()).toString();
-
- m_stdoutFilterFunction = invokedSourceCode(stdoutFilterFunction);
-
- // toString() is required, presumably due to QtScript bug that manifests itself on Windows
- const QScriptValue stderrFilterFunction
- = scriptValue->property(stderrFilterFunctionProperty()).toString();
-
- m_stderrFilterFunction = invokedSourceCode(stderrFilterFunction);
- m_relevantEnvVars = scriptValue->property(QStringLiteral("relevantEnvironmentVariables"))
- .toVariant().toStringList();
- m_responseFileThreshold = scriptValue->property(responseFileThresholdProperty())
- .toInt32();
- m_responseFileArgumentIndex = scriptValue->property(responseFileArgumentIndexProperty())
- .toInt32();
- m_responseFileUsagePrefix = scriptValue->property(responseFileUsagePrefixProperty())
- .toString();
- m_responseFileSeparator = scriptValue->property(responseFileSeparatorProperty())
- .toString();
- QStringList envList = scriptValue->property(environmentProperty()).toVariant()
- .toStringList();
+void ProcessCommand::fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue, const CodeLocation &codeLocation)
+{
+ AbstractCommand::fillFromScriptValue(ctx, scriptValue, codeLocation);
+ m_program = getJsStringProperty(ctx, *scriptValue, programProperty());
+ m_arguments = getJsStringListProperty(ctx, *scriptValue, argumentsProperty());
+ m_workingDir = getJsStringProperty(ctx, *scriptValue, workingDirProperty());
+ m_maxExitCode = getJsIntProperty(ctx, *scriptValue, maxExitCodeProperty());
+
+ const ScopedJsValue stdoutFilterFunction(ctx, getJsProperty(ctx, *scriptValue,
+ stdoutFilterFunctionProperty()));
+ if (JS_IsFunction(ctx, stdoutFilterFunction))
+ m_stdoutFilterFunction = QLatin1Char('(') + getJsString(ctx, stdoutFilterFunction) + QLatin1Char(')');
+
+ const ScopedJsValue stderrFilterFunction(ctx, getJsProperty(ctx, *scriptValue,
+ stderrFilterFunctionProperty()));
+ if (JS_IsFunction(ctx, stderrFilterFunction))
+ m_stderrFilterFunction = QLatin1Char('(') + getJsString(ctx, stderrFilterFunction) + QLatin1Char(')');
+
+ m_relevantEnvVars = getJsStringListProperty(ctx, *scriptValue,
+ QStringLiteral("relevantEnvironmentVariables"));
+ m_responseFileThreshold = getJsIntProperty(ctx, *scriptValue, responseFileThresholdProperty());
+ m_responseFileArgumentIndex = getJsIntProperty(ctx, *scriptValue,
+ responseFileArgumentIndexProperty());
+ m_responseFileUsagePrefix = getJsStringProperty(ctx, *scriptValue,
+ responseFileUsagePrefixProperty());
+ m_responseFileSeparator = getJsStringProperty(ctx, *scriptValue,
+ responseFileSeparatorProperty());
+ QStringList envList = getJsStringListProperty(ctx, *scriptValue, environmentProperty());
getEnvironmentFromList(envList);
- m_stdoutFilePath = scriptValue->property(stdoutFilePathProperty()).toString();
- m_stderrFilePath = scriptValue->property(stderrFilePathProperty()).toString();
+ m_stdoutFilePath = getJsStringProperty(ctx, *scriptValue, stdoutFilePathProperty());
+ m_stderrFilePath = getJsStringProperty(ctx, *scriptValue, stderrFilePathProperty());
m_predefinedProperties
<< programProperty()
@@ -337,7 +336,7 @@ void ProcessCommand::fillFromScriptValue(const QScriptValue *scriptValue, const
<< environmentProperty()
<< stdoutFilePathProperty()
<< stderrFilePathProperty();
- applyCommandProperties(scriptValue);
+ applyCommandProperties(ctx, scriptValue);
}
QStringList ProcessCommand::relevantEnvVars() const
@@ -365,43 +364,42 @@ void ProcessCommand::store(PersistentPool &pool)
serializationOp<PersistentPool::Store>(pool);
}
-static QString currentImportScopeName(QScriptContext *context)
+static QString currentImportScopeName(JSContext *ctx)
{
- for (; context; context = context->parentContext()) {
- QScriptValue v = context->thisObject()
- .property(StringConstants::importScopeNamePropertyInternal());
- if (v.isString())
- return v.toString();
+ const ScriptEngine * const engine = ScriptEngine::engineForContext(ctx);
+ const JSValueList &contextStack = engine->contextStack();
+ for (auto it = contextStack.rbegin(); it != contextStack.rend(); ++it) {
+ if (!JS_IsObject(*it))
+ continue;
+ const ScopedJsValue v(ctx, getJsProperty(ctx, *it,
+ StringConstants::importScopeNamePropertyInternal()));
+ if (JS_IsString(v))
+ return getJsString(ctx, v);
}
return {};
}
-static QScriptValue js_JavaScriptCommand(QScriptContext *context, QScriptEngine *engine)
+static JSValue js_JavaScriptCommand(JSContext *ctx, JSValueConst, JSValueConst,
+ int argc, JSValueConst *, int)
{
- if (Q_UNLIKELY(!context->isCalledAsConstructor()))
- return context->throwError(Tr::tr("JavaScriptCommand constructor called without new."));
- if (Q_UNLIKELY(context->argumentCount() != 0)) {
- return context->throwError(QScriptContext::SyntaxError,
- Tr::tr("JavaScriptCommand c'tor doesn't take arguments."));
- }
+ if (argc > 0)
+ return throwError(ctx, Tr::tr("JavaScriptCommand c'tor doesn't take arguments."));
static JavaScriptCommandPtr commandPrototype = JavaScriptCommand::create();
- QScriptValue cmd = js_CommandBase(context, engine);
- cmd.setProperty(StringConstants::classNameProperty(),
- engine->toScriptValue(StringConstants::javaScriptCommandType()));
- cmd.setProperty(StringConstants::sourceCodeProperty(),
- engine->toScriptValue(commandPrototype->sourceCode()));
- cmd.setProperty(StringConstants::importScopeNamePropertyInternal(),
- engine->toScriptValue(currentImportScopeName(context)));
-
+ JSValue cmd = js_CommandBase(ctx);
+ setJsProperty(ctx, cmd, StringConstants::classNameProperty(),
+ makeJsString(ctx, StringConstants::javaScriptCommandType()));
+ setJsProperty(ctx, cmd, StringConstants::sourceCodeProperty(),
+ makeJsString(ctx, commandPrototype->sourceCode()));
+ setJsProperty(ctx, cmd, StringConstants::importScopeNamePropertyInternal(),
+ makeJsString(ctx, currentImportScopeName(ctx)));
return cmd;
}
-void JavaScriptCommand::setupForJavaScript(QScriptValue targetObject)
+void JavaScriptCommand::setupForJavaScript(ScriptEngine *engine, JSValue targetObject)
{
- QBS_CHECK(targetObject.isObject());
- QScriptValue ctor = targetObject.engine()->newFunction(js_JavaScriptCommand, 0);
- targetObject.setProperty(StringConstants::javaScriptCommandType(), ctor);
+ engine->registerClass(StringConstants::javaScriptCommandType().toUtf8().constData(),
+ js_JavaScriptCommand, nullptr, targetObject);
}
JavaScriptCommand::JavaScriptCommand() = default;
@@ -414,22 +412,24 @@ bool JavaScriptCommand::equals(const AbstractCommand *otherAbstractCommand) cons
return m_sourceCode == other->m_sourceCode;
}
-void JavaScriptCommand::fillFromScriptValue(const QScriptValue *scriptValue, const CodeLocation &codeLocation)
+void JavaScriptCommand::fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue,
+ const CodeLocation &codeLocation)
{
- AbstractCommand::fillFromScriptValue(scriptValue, codeLocation);
+ AbstractCommand::fillFromScriptValue(ctx, scriptValue, codeLocation);
- const QScriptValue importScope = scriptValue->property(
- StringConstants::importScopeNamePropertyInternal());
- if (importScope.isString())
- m_scopeName = importScope.toString();
+ const ScopedJsValue importScope(ctx, getJsProperty(ctx, *scriptValue,
+ StringConstants::importScopeNamePropertyInternal()));
+ if (JS_IsString(importScope))
+ m_scopeName = getJsString(ctx, importScope);
- const QScriptValue sourceCode = scriptValue->property(StringConstants::sourceCodeProperty());
- m_sourceCode = invokedSourceCode(sourceCode);
+ const ScopedJsValue sourceCode(ctx, getJsProperty(ctx, *scriptValue,
+ StringConstants::sourceCodeProperty()));
+ m_sourceCode = invokedSourceCode(ctx, sourceCode);
m_predefinedProperties << StringConstants::classNameProperty()
<< StringConstants::sourceCodeProperty()
<< StringConstants::importScopeNamePropertyInternal();
- applyCommandProperties(scriptValue);
+ applyCommandProperties(ctx, scriptValue);
}
void JavaScriptCommand::load(PersistentPool &pool)
diff --git a/src/lib/corelib/buildgraph/rulecommands.h b/src/lib/corelib/buildgraph/rulecommands.h
index 725cd6d89..7b08d1015 100644
--- a/src/lib/corelib/buildgraph/rulecommands.h
+++ b/src/lib/corelib/buildgraph/rulecommands.h
@@ -47,14 +47,15 @@
#include <tools/persistence.h>
#include <tools/set.h>
+#include <quickjs.h>
+
#include <QtCore/qprocess.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qvariant.h>
-#include <QtScript/qscriptvalue.h>
-
namespace qbs {
namespace Internal {
+class ScriptEngine;
class AbstractCommand
{
@@ -75,7 +76,8 @@ public:
virtual CommandType type() const = 0;
virtual bool equals(const AbstractCommand *other) const;
- virtual void fillFromScriptValue(const QScriptValue *scriptValue, const CodeLocation &codeLocation);
+ virtual void fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue,
+ const CodeLocation &codeLocation);
QString fullDescription(const QString &productName) const;
const QString description() const { return m_description; }
@@ -94,7 +96,7 @@ public:
protected:
AbstractCommand();
- void applyCommandProperties(const QScriptValue *scriptValue);
+ void applyCommandProperties(JSContext *ctx, const JSValue *scriptValue);
Set<QString> m_predefinedProperties;
@@ -121,11 +123,11 @@ class ProcessCommand : public AbstractCommand
{
public:
static ProcessCommandPtr create() { return ProcessCommandPtr(new ProcessCommand); }
- static void setupForJavaScript(QScriptValue targetObject);
+ static void setupForJavaScript(ScriptEngine *engine, JSValue targetObject);
CommandType type() const override { return ProcessCommandType; }
bool equals(const AbstractCommand *otherAbstractCommand) const override;
- void fillFromScriptValue(const QScriptValue *scriptValue,
+ void fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue,
const CodeLocation &codeLocation) override;
const QString program() const { return m_program; }
const QStringList arguments() const { return m_arguments; }
@@ -186,16 +188,15 @@ class JavaScriptCommand : public AbstractCommand
{
public:
static JavaScriptCommandPtr create() { return JavaScriptCommandPtr(new JavaScriptCommand); }
- static void setupForJavaScript(QScriptValue targetObject);
+ static void setupForJavaScript(ScriptEngine *engine, JSValue targetObject);
CommandType type() const override { return JavaScriptCommandType; }
bool equals(const AbstractCommand *otherAbstractCommand) const override;
- void fillFromScriptValue(const QScriptValue *scriptValue,
+ void fillFromScriptValue(JSContext *ctx, const JSValue *scriptValue,
const CodeLocation &codeLocation) override;
const QString &scopeName() const { return m_scopeName; }
const QString &sourceCode() const { return m_sourceCode; }
- void setSourceCode(const QString &str) { m_sourceCode = str; }
void load(PersistentPool &pool) override;
void store(PersistentPool &pool) override;
diff --git a/src/lib/corelib/buildgraph/rulesapplicator.cpp b/src/lib/corelib/buildgraph/rulesapplicator.cpp
index f464734b8..84956d123 100644
--- a/src/lib/corelib/buildgraph/rulesapplicator.cpp
+++ b/src/lib/corelib/buildgraph/rulesapplicator.cpp
@@ -1,5 +1,3 @@
-#include <utility>
-
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
@@ -41,7 +39,6 @@
#include "rulesapplicator.h"
#include "buildgraph.h"
-#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "qtmocscanner.h"
#include "rulecommands.h"
@@ -57,7 +54,6 @@
#include <language/preparescriptobserver.h>
#include <language/propertymapinternal.h>
#include <language/resolvedfilecontext.h>
-#include <language/scriptengine.h>
#include <logging/categories.h>
#include <logging/translator.h>
#include <tools/error.h>
@@ -69,7 +65,6 @@
#include <QtCore/qcryptographichash.h>
#include <QtCore/qdir.h>
-#include <QtScript/qscriptvalueiterator.h>
#include <memory>
#include <vector>
@@ -113,10 +108,10 @@ void RulesApplicator::applyRule(RuleNode *ruleNode, const ArtifactSet &inputArti
m_completeInputSet = inputArtifacts;
if (m_rule->name.startsWith(QLatin1String("QtCoreMocRule"))) {
delete m_mocScanner;
- m_mocScanner = new QtMocScanner(m_product, scope());
+ m_mocScanner = new QtMocScanner(m_product, engine(), scope());
}
- QScriptValue prepareScriptContext = engine()->newObject();
- prepareScriptContext.setPrototype(engine()->globalObject());
+ ScopedJsValue prepareScriptContext(jsContext(), engine()->newObject());
+ JS_SetPrototype(jsContext(), prepareScriptContext, engine()->globalObject());
setupScriptEngineForFile(engine(), m_rule->prepareScript.fileContext(), scope(),
ObserveMode::Enabled);
setupScriptEngineForProduct(engine(), m_product.get(), m_rule->module.get(),
@@ -134,6 +129,7 @@ void RulesApplicator::applyRule(RuleNode *ruleNode, const ArtifactSet &inputArti
}
if (engine()->usesIo())
m_ruleUsesIo = true;
+ engine()->releaseInputArtifactScriptValues(ruleNode);
}
void RulesApplicator::handleRemovedRuleOutputs(const ArtifactSet &inputArtifacts,
@@ -164,9 +160,9 @@ ArtifactSet RulesApplicator::collectAuxiliaryInputs(const Rule *rule,
CurrentProduct | Dependencies);
}
-static void copyProperty(const QString &name, const QScriptValue &src, QScriptValue dst)
+static void copyProperty(JSContext *ctx, const QString &name, const JSValue &src, JSValue dst)
{
- dst.setProperty(name, src.property(name));
+ setJsProperty(ctx, dst, name, getJsProperty(ctx, src, name));
}
static QStringList toStringList(const ArtifactSet &artifacts)
@@ -180,7 +176,7 @@ static QStringList toStringList(const ArtifactSet &artifacts)
return lst;
}
-void RulesApplicator::doApply(const ArtifactSet &inputArtifacts, QScriptValue &prepareScriptContext)
+void RulesApplicator::doApply(const ArtifactSet &inputArtifacts, JSValue prepareScriptContext)
{
evalContext()->checkForCancelation();
for (const Artifact *inputArtifact : inputArtifacts)
@@ -202,20 +198,22 @@ void RulesApplicator::doApply(const ArtifactSet &inputArtifacts, QScriptValue &p
engine()->clearRequestedProperties();
// create the output artifacts from the set of input artifacts
- m_transformer->setupInputs(prepareScriptContext);
- m_transformer->setupExplicitlyDependsOn(prepareScriptContext);
- copyProperty(StringConstants::inputsVar(), prepareScriptContext, scope());
- copyProperty(StringConstants::inputVar(), prepareScriptContext, scope());
- copyProperty(StringConstants::explicitlyDependsOnVar(), prepareScriptContext, scope());
- copyProperty(StringConstants::productVar(), prepareScriptContext, scope());
- copyProperty(StringConstants::projectVar(), prepareScriptContext, scope());
+ m_transformer->setupInputs(engine(), prepareScriptContext);
+ m_transformer->setupExplicitlyDependsOn(engine(), prepareScriptContext);
+ copyProperty(jsContext(), StringConstants::inputsVar(), prepareScriptContext, scope());
+ copyProperty(jsContext(), StringConstants::inputVar(), prepareScriptContext, scope());
+ copyProperty(jsContext(), StringConstants::explicitlyDependsOnVar(),
+ prepareScriptContext, scope());
+ copyProperty(jsContext(), StringConstants::productVar(), prepareScriptContext, scope());
+ copyProperty(jsContext(), StringConstants::projectVar(), prepareScriptContext, scope());
if (m_rule->isDynamic()) {
- outputArtifacts = runOutputArtifactsScript(inputArtifacts,
- ScriptEngine::argumentList(Rule::argumentNamesForOutputArtifacts(), scope()));
+ const ScopedJsValueList argList
+ = engine()->argumentList(Rule::argumentNamesForOutputArtifacts(), scope());
+ outputArtifacts = runOutputArtifactsScript(inputArtifacts, argList);
} else {
Set<QString> outputFilePaths;
for (const auto &ruleArtifact : m_rule->artifacts) {
- const OutputArtifactInfo outputInfo = createOutputArtifactFromRuleArtifact(
+ const OutputArtifactInfo &outputInfo = createOutputArtifactFromRuleArtifact(
ruleArtifact, inputArtifacts, &outputFilePaths);
if (!outputInfo.artifact)
continue;
@@ -255,53 +253,57 @@ void RulesApplicator::doApply(const ArtifactSet &inputArtifacts, QScriptValue &p
}
if (inputArtifacts != m_transformer->inputs)
- m_transformer->setupInputs(prepareScriptContext);
+ m_transformer->setupInputs(engine(), prepareScriptContext);
// change the transformer outputs according to the bindings in Artifact
- QScriptValue scriptValue;
- if (!ruleArtifactArtifactMap.empty())
- engine()->setGlobalObject(prepareScriptContext);
- for (auto it = ruleArtifactArtifactMap.crbegin(), end = ruleArtifactArtifactMap.crend();
- it != end; ++it) {
- const RuleArtifact *ra = it->first;
- if (ra->bindings.empty())
- continue;
-
- // expose attributes of this artifact
- const OutputArtifactInfo outputInfo = it->second;
- Artifact *outputArtifact = outputInfo.artifact;
- outputArtifact->properties = outputArtifact->properties->clone();
+ if (!ruleArtifactArtifactMap.empty()) {
+ const TemporaryGlobalObjectSetter gos(engine(), prepareScriptContext);
+ for (auto it = ruleArtifactArtifactMap.crbegin(), end = ruleArtifactArtifactMap.crend();
+ it != end; ++it) {
+ const RuleArtifact *ra = it->first;
+ if (ra->bindings.empty())
+ continue;
- scope().setProperty(StringConstants::fileNameProperty(),
- engine()->toScriptValue(outputArtifact->filePath()));
- scope().setProperty(StringConstants::fileTagsProperty(),
- toScriptValue(engine(), outputArtifact->fileTags().toStringList()));
-
- QVariantMap artifactModulesCfg = outputArtifact->properties->value();
- for (const auto &binding : ra->bindings) {
- scriptValue = engine()->evaluate(binding.code);
- if (Q_UNLIKELY(engine()->hasErrorOrException(scriptValue))) {
- QString msg = QStringLiteral("evaluating rule binding '%1': %2");
- throw ErrorInfo(msg.arg(binding.name.join(QLatin1Char('.')),
- engine()->lastErrorString(scriptValue)),
- engine()->lastErrorLocation(scriptValue, binding.location));
+ // expose attributes of this artifact
+ const OutputArtifactInfo &outputInfo = it->second;
+ Artifact *outputArtifact = outputInfo.artifact;
+ outputArtifact->properties = outputArtifact->properties->clone();
+
+ setJsProperty(jsContext(), scope(), StringConstants::fileNameProperty(),
+ engine()->toScriptValue(outputArtifact->filePath()));
+ setJsProperty(jsContext(), scope(), StringConstants::fileTagsProperty(),
+ makeJsStringList(engine()->context(),
+ outputArtifact->fileTags().toStringList()));
+
+ QVariantMap artifactModulesCfg = outputArtifact->properties->value();
+ for (const auto &binding : ra->bindings) {
+ const ScopedJsValue scriptValue(jsContext(), engine()->evaluate(
+ JsValueOwner::Caller, binding.code,
+ binding.location.filePath(),
+ binding.location.line()));
+ if (JsException ex = engine()->checkAndClearException(binding.location)) {
+ ErrorInfo err = ex.toErrorInfo();
+ err.prepend(QStringLiteral("evaluating rule binding '%1'")
+ .arg(binding.name.join(QLatin1Char('.'))));
+ throw err;
+ }
+ const QVariant value = getJsVariant(jsContext(), scriptValue);
+ setConfigProperty(artifactModulesCfg, binding.name, value);
+ outputArtifact->pureProperties.emplace_back(binding.name, value);
+ }
+ outputArtifact->properties->setValue(artifactModulesCfg);
+ if (!outputInfo.newlyCreated
+ && (outputArtifact->fileTags() != outputInfo.oldFileTags
+ || outputArtifact->properties->value() != outputInfo.oldProperties)) {
+ invalidateArtifactAsRuleInputIfNecessary(outputArtifact);
}
- const QVariant value = scriptValue.toVariant();
- setConfigProperty(artifactModulesCfg, binding.name, value);
- outputArtifact->pureProperties.emplace_back(binding.name, value);
- }
- outputArtifact->properties->setValue(artifactModulesCfg);
- if (!outputInfo.newlyCreated && (outputArtifact->fileTags() != outputInfo.oldFileTags
- || outputArtifact->properties->value() != outputInfo.oldProperties)) {
- invalidateArtifactAsRuleInputIfNecessary(outputArtifact);
}
}
- if (!ruleArtifactArtifactMap.empty())
- engine()->setGlobalObject(prepareScriptContext.prototype());
- m_transformer->setupOutputs(prepareScriptContext);
- m_transformer->createCommands(engine(), m_rule->prepareScript,
- ScriptEngine::argumentList(Rule::argumentNamesForPrepare(), prepareScriptContext));
+ m_transformer->setupOutputs(engine(), prepareScriptContext);
+ const ScopedJsValueList argList = engine()->argumentList(Rule::argumentNamesForPrepare(),
+ prepareScriptContext);
+ m_transformer->createCommands(engine(), m_rule->prepareScript, argList);
if (Q_UNLIKELY(m_transformer->commands.empty()))
throw ErrorInfo(Tr::tr("There is a rule without commands: %1.")
.arg(m_rule->toString()), m_rule->prepareScript.location());
@@ -386,12 +388,14 @@ RulesApplicator::OutputArtifactInfo RulesApplicator::createOutputArtifactFromRul
FileTags fileTags;
bool alwaysUpdated;
if (ruleArtifact) {
- QScriptValue scriptValue = engine()->evaluate(ruleArtifact->filePath,
- ruleArtifact->filePathLocation.filePath(),
- ruleArtifact->filePathLocation.line());
- if (Q_UNLIKELY(engine()->hasErrorOrException(scriptValue)))
- throw engine()->lastError(scriptValue, ruleArtifact->filePathLocation);
- outputPath = scriptValue.toString();
+ const ScopedJsValue scriptValue(
+ jsContext(),
+ engine()->evaluate(JsValueOwner::Caller, ruleArtifact->filePath,
+ ruleArtifact->filePathLocation.filePath(),
+ ruleArtifact->filePathLocation.line()));
+ if (JsException ex = engine()->checkAndClearException(ruleArtifact->filePathLocation))
+ throw ex.toErrorInfo();
+ outputPath = getJsString(jsContext(), scriptValue);
fileTags = ruleArtifact->fileTags;
alwaysUpdated = ruleArtifact->alwaysUpdated;
} else {
@@ -514,26 +518,31 @@ public:
};
QList<Artifact *> RulesApplicator::runOutputArtifactsScript(const ArtifactSet &inputArtifacts,
- const QScriptValueList &args)
+ const JSValueList &args)
{
QList<Artifact *> lst;
- QScriptValue fun = engine()->evaluate(m_rule->outputArtifactsScript.sourceCode(),
- m_rule->outputArtifactsScript.location().filePath(),
- m_rule->outputArtifactsScript.location().line());
- if (!fun.isFunction())
+ const ScopedJsValue fun(jsContext(),
+ engine()->evaluate(JsValueOwner::Caller,
+ m_rule->outputArtifactsScript.sourceCode(),
+ m_rule->outputArtifactsScript.location().filePath(),
+ m_rule->outputArtifactsScript.location().line()));
+ if (!JS_IsFunction(jsContext(), fun))
throw ErrorInfo(QStringLiteral("Function expected."),
m_rule->outputArtifactsScript.location());
- QScriptValue res = fun.call(QScriptValue(), args);
- engine()->releaseResourcesOfScriptObjects();
- if (engine()->hasErrorOrException(res))
- throw engine()->lastError(res, m_rule->outputArtifactsScript.location());
- if (!res.isArray())
+ JSValueList argv(args.begin(), args.end());
+ const ScopedJsValue res(
+ jsContext(),
+ JS_Call(jsContext(), fun, engine()->globalObject(), int(args.size()), argv.data()));
+ if (JsException ex = engine()->checkAndClearException(m_rule->outputArtifactsScript.location()))
+ throw ex.toErrorInfo();
+ if (!JS_IsArray(jsContext(), res))
throw ErrorInfo(Tr::tr("Rule.outputArtifacts must return an array of objects."),
m_rule->outputArtifactsScript.location());
- const quint32 c = res.property(StringConstants::lengthProperty()).toUInt32();
+ const quint32 c = getJsIntProperty(jsContext(), res, StringConstants::lengthProperty());
for (quint32 i = 0; i < c; ++i) {
try {
- lst.push_back(createOutputArtifactFromScriptValue(res.property(i), inputArtifacts));
+ ScopedJsValue val(engine()->context(), JS_GetPropertyUint32(jsContext(), res, i));
+ lst.push_back(createOutputArtifactFromScriptValue(val, inputArtifacts));
} catch (const RuleOutputArtifactsException &roae) {
ErrorInfo ei = roae;
ei.prepend(Tr::tr("Error in Rule.outputArtifacts[%1]").arg(i),
@@ -556,6 +565,8 @@ class ArtifactBindingsExtractor
QString name;
QVariant value;
};
+ ScriptEngine *m_engine = nullptr;
+ JSContext *m_ctx = nullptr;
std::vector<Entry> m_propertyValues;
static Set<QString> getArtifactItemPropertyNames()
@@ -570,35 +581,36 @@ class ArtifactBindingsExtractor
return s;
}
- void extractPropertyValues(const QScriptValue &obj, const QString &moduleName = QString())
+ void extractPropertyValues(const JSValue &obj, const QString &moduleName = QString())
{
- QScriptValueIterator svit(obj);
- while (svit.hasNext()) {
- svit.next();
- const QString name = svit.name();
+ handleJsProperties(m_ctx, obj, [&](const JSAtom &prop, const JSPropertyDescriptor &desc) {
+ const QString name = getJsString(m_ctx, prop);
if (moduleName.isEmpty()) {
// Ignore property names that are part of the Artifact item.
static const Set<QString> artifactItemPropertyNames
= getArtifactItemPropertyNames();
if (artifactItemPropertyNames.contains(name))
- continue;
+ return;
}
- const QScriptValue value = svit.value();
- if (value.isObject() && !value.isArray() && !value.isError() && !value.isRegExp()) {
+ const JSValue value = desc.value;
+ if (JS_IsObject(value) && !JS_IsArray(m_ctx, value) && !JS_IsError(m_ctx, value)
+ && !JS_IsRegExp(m_ctx, value)) {
QString newModuleName;
if (!moduleName.isEmpty())
newModuleName.append(moduleName + QLatin1Char('.'));
newModuleName.append(name);
extractPropertyValues(value, newModuleName);
} else {
- m_propertyValues.emplace_back(moduleName, name, value.toVariant());
+ m_propertyValues.emplace_back(moduleName, name, getJsVariant(m_ctx, value));
}
- }
+ });
}
public:
- void apply(Artifact *outputArtifact, const QScriptValue &obj)
+ void apply(ScriptEngine *engine, Artifact *outputArtifact, const JSValue &obj)
{
+ m_engine = engine;
+ m_ctx = m_engine->context();
extractPropertyValues(obj);
if (m_propertyValues.empty())
return;
@@ -614,24 +626,27 @@ public:
}
};
-Artifact *RulesApplicator::createOutputArtifactFromScriptValue(const QScriptValue &obj,
+Artifact *RulesApplicator::createOutputArtifactFromScriptValue(const JSValue &obj,
const ArtifactSet &inputArtifacts)
{
- if (!obj.isObject()) {
+ if (!JS_IsObject(obj)) {
throw ErrorInfo(Tr::tr("Elements of the Rule.outputArtifacts array must be "
"of Object type."), m_rule->outputArtifactsScript.location());
}
- const QString unresolvedFilePath
- = obj.property(StringConstants::filePathProperty()).toVariant().toString();
+ QString unresolvedFilePath;
+ const ScopedJsValue jsFilePath(jsContext(), getJsProperty(jsContext(), obj,
+ StringConstants::filePathProperty()));
+ if (JS_IsString(jsFilePath))
+ unresolvedFilePath = getJsString(jsContext(), jsFilePath);
if (unresolvedFilePath.isEmpty()) {
throw RuleOutputArtifactsException(
Tr::tr("Property filePath must be a non-empty string."));
}
const QString filePath = FileInfo::resolvePath(m_product->buildDirectory(), unresolvedFilePath);
const FileTags fileTags = FileTags::fromStringList(
- obj.property(StringConstants::fileTagsProperty()).toVariant().toStringList());
- const QVariant alwaysUpdatedVar
- = obj.property(StringConstants::alwaysUpdatedProperty()).toVariant();
+ getJsStringListProperty(jsContext(), obj, StringConstants::fileTagsProperty()));
+ const QVariant alwaysUpdatedVar = getJsVariantProperty(jsContext(), obj,
+ StringConstants::alwaysUpdatedProperty());
const bool alwaysUpdated = alwaysUpdatedVar.isValid() ? alwaysUpdatedVar.toBool() : true;
OutputArtifactInfo outputInfo = createOutputArtifact(filePath, fileTags, alwaysUpdated,
inputArtifacts);
@@ -642,14 +657,13 @@ Artifact *RulesApplicator::createOutputArtifactFromScriptValue(const QScriptValu
"Alternatively, a FileTagger can be provided.")
.arg(unresolvedFilePath));
}
- const FileTags explicitlyDependsOn = FileTags::fromStringList(
- obj.property(StringConstants::explicitlyDependsOnProperty())
- .toVariant().toStringList());
+ const FileTags explicitlyDependsOn = FileTags::fromStringList(getJsStringListProperty(
+ jsContext(), obj, StringConstants::explicitlyDependsOnProperty()));
for (const FileTag &tag : explicitlyDependsOn) {
for (Artifact * const dependency : m_product->lookupArtifactsByFileTag(tag))
connect(outputInfo.artifact, dependency);
}
- ArtifactBindingsExtractor().apply(outputInfo.artifact, obj);
+ ArtifactBindingsExtractor().apply(engine(), outputInfo.artifact, obj);
if (!outputInfo.newlyCreated && (outputInfo.artifact->fileTags() != outputInfo.oldFileTags
|| outputInfo.artifact->properties->value() != outputInfo.oldProperties)) {
invalidateArtifactAsRuleInputIfNecessary(outputInfo.artifact);
@@ -670,15 +684,9 @@ const RulesEvaluationContextPtr &RulesApplicator::evalContext() const
return m_product->topLevelProject()->buildData->evaluationContext;
}
-ScriptEngine *RulesApplicator::engine() const
-{
- return evalContext()->engine();
-}
-
-QScriptValue RulesApplicator::scope() const
-{
- return evalContext()->scope();
-}
+ScriptEngine *RulesApplicator::engine() const { return evalContext()->engine(); }
+JSContext *RulesApplicator::jsContext() const { return engine()->context(); }
+JSValue RulesApplicator::scope() const { return evalContext()->scope(); }
} // namespace Internal
} // namespace qbs
diff --git a/src/lib/corelib/buildgraph/rulesapplicator.h b/src/lib/corelib/buildgraph/rulesapplicator.h
index da7815014..72f9aadcc 100644
--- a/src/lib/corelib/buildgraph/rulesapplicator.h
+++ b/src/lib/corelib/buildgraph/rulesapplicator.h
@@ -44,12 +44,13 @@
#include "nodeset.h"
#include <language/filetags.h>
#include <language/forward_decls.h>
+#include <language/scriptengine.h>
#include <logging/logger.h>
+#include <quickjs.h>
#include <QtCore/qflags.h>
#include <QtCore/qhash.h>
#include <QtCore/qstring.h>
-#include <QtScript/qscriptvalue.h>
#include <unordered_map>
@@ -85,7 +86,7 @@ public:
Q_DECLARE_FLAGS(InputsSources, InputsSourceFlag)
private:
- void doApply(const ArtifactSet &inputArtifacts, QScriptValue &prepareScriptContext);
+ void doApply(const ArtifactSet &inputArtifacts, JSValue prepareScriptContext);
ArtifactSet collectOldOutputArtifacts(const ArtifactSet &inputArtifacts) const;
struct OutputArtifactInfo {
@@ -100,13 +101,14 @@ private:
OutputArtifactInfo createOutputArtifact(const QString &filePath, const FileTags &fileTags,
bool alwaysUpdated, const ArtifactSet &inputArtifacts);
QList<Artifact *> runOutputArtifactsScript(const ArtifactSet &inputArtifacts,
- const QScriptValueList &args);
- Artifact *createOutputArtifactFromScriptValue(const QScriptValue &obj,
+ const JSValueList &args);
+ Artifact *createOutputArtifactFromScriptValue(const JSValue &obj,
const ArtifactSet &inputArtifacts);
QString resolveOutPath(const QString &path) const;
const RulesEvaluationContextPtr &evalContext() const;
ScriptEngine *engine() const;
- QScriptValue scope() const;
+ JSContext *jsContext() const;
+ JSValue scope() const;
static ArtifactSet collectAdditionalInputs(const FileTags &tags,
const Rule *rule, const ResolvedProduct *product,
diff --git a/src/lib/corelib/buildgraph/rulesevaluationcontext.cpp b/src/lib/corelib/buildgraph/rulesevaluationcontext.cpp
index 0422b9288..2d0f5d44d 100644
--- a/src/lib/corelib/buildgraph/rulesevaluationcontext.cpp
+++ b/src/lib/corelib/buildgraph/rulesevaluationcontext.cpp
@@ -38,9 +38,7 @@
****************************************************************************/
#include "rulesevaluationcontext.h"
-#include "artifact.h"
#include "rulecommands.h"
-#include "transformer.h"
#include <language/language.h>
#include <language/scriptengine.h>
#include <logging/translator.h>
@@ -57,15 +55,19 @@ RulesEvaluationContext::RulesEvaluationContext(Logger logger)
: m_logger(std::move(logger)),
m_engine(ScriptEngine::create(m_logger, EvalContext::RuleExecution)),
m_observer(nullptr),
- m_initScopeCalls(0)
+ m_initScopeCalls(0),
+ m_prepareScriptScope(m_engine->newObject())
{
- m_prepareScriptScope = m_engine->newObject();
- m_prepareScriptScope.setPrototype(m_engine->globalObject());
- ProcessCommand::setupForJavaScript(m_prepareScriptScope);
- JavaScriptCommand::setupForJavaScript(m_prepareScriptScope);
+
+ JS_SetPrototype(m_engine->context(), m_prepareScriptScope, m_engine->globalObject());
+ ProcessCommand::setupForJavaScript(m_engine.get(), m_prepareScriptScope);
+ JavaScriptCommand::setupForJavaScript(m_engine.get(), m_prepareScriptScope);
}
-RulesEvaluationContext::~RulesEvaluationContext() = default;
+RulesEvaluationContext::~RulesEvaluationContext()
+{
+ JS_FreeValue(m_engine->context(), m_prepareScriptScope);
+}
void RulesEvaluationContext::initializeObserver(const QString &description, int maximumProgress)
{
@@ -92,7 +94,7 @@ void RulesEvaluationContext::initScope()
m_engine->setActive(true);
m_scope = m_engine->newObject();
- m_scope.setPrototype(m_prepareScriptScope);
+ JS_SetPrototype(m_engine->context(), m_scope, m_prepareScriptScope);
m_engine->setGlobalObject(m_scope);
}
@@ -102,8 +104,11 @@ void RulesEvaluationContext::cleanupScope()
if (--m_initScopeCalls > 0)
return;
- m_scope = QScriptValue();
- m_engine->setGlobalObject(m_prepareScriptScope.prototype());
+ JS_FreeValue(m_engine->context(), m_scope);
+ m_scope = JS_UNDEFINED;
+ const ScopedJsValue proto(engine()->context(),
+ JS_GetPrototype(m_engine->context(), m_prepareScriptScope));
+ m_engine->setGlobalObject(proto);
m_engine->setActive(false);
}
diff --git a/src/lib/corelib/buildgraph/rulesevaluationcontext.h b/src/lib/corelib/buildgraph/rulesevaluationcontext.h
index bb7955496..7ff75b51f 100644
--- a/src/lib/corelib/buildgraph/rulesevaluationcontext.h
+++ b/src/lib/corelib/buildgraph/rulesevaluationcontext.h
@@ -42,12 +42,11 @@
#include <language/forward_decls.h>
#include <logging/logger.h>
+#include <quickjs.h>
+
#include <QtCore/qhash.h>
#include <QtCore/qstring.h>
-#include <QtScript/qscriptprogram.h>
-#include <QtScript/qscriptvalue.h>
-
namespace qbs {
namespace Internal {
class ProgressObserver;
@@ -70,7 +69,7 @@ public:
};
ScriptEngine *engine() const { return m_engine.get(); }
- QScriptValue scope() const { return m_scope; }
+ JSValue scope() const { return m_scope; }
void setObserver(ProgressObserver *observer) { m_observer = observer; }
ProgressObserver *observer() const { return m_observer; }
@@ -79,8 +78,6 @@ public:
void checkForCancelation();
private:
- friend class Scope;
-
void initScope();
void cleanupScope();
@@ -88,8 +85,8 @@ private:
const std::unique_ptr<ScriptEngine> m_engine;
ProgressObserver *m_observer;
unsigned int m_initScopeCalls;
- QScriptValue m_scope;
- QScriptValue m_prepareScriptScope;
+ JSValue m_scope = JS_UNDEFINED;
+ const JSValue m_prepareScriptScope;
};
} // namespace Internal
diff --git a/src/lib/corelib/buildgraph/scriptclasspropertyiterator.h b/src/lib/corelib/buildgraph/scriptclasspropertyiterator.h
deleted file mode 100644
index b57072236..000000000
--- a/src/lib/corelib/buildgraph/scriptclasspropertyiterator.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qbs.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QBS_SCRIPTCLASSPROPERTYITERATOR_H
-#define QBS_SCRIPTCLASSPROPERTYITERATOR_H
-
-#include <tools/qbsassert.h>
-
-#include <QtCore/qmap.h>
-#include <QtCore/qstring.h>
-#include <QtScript/qscriptclasspropertyiterator.h>
-#include <QtScript/qscriptengine.h>
-#include <QtScript/qscriptstring.h>
-
-#include <vector>
-
-namespace qbs {
-namespace Internal {
-
-class ScriptClassPropertyIterator : public QScriptClassPropertyIterator
-{
-public:
- ScriptClassPropertyIterator(const QScriptValue &object, const QVariantMap &properties,
- std::vector<QString> additionalProperties)
- : QScriptClassPropertyIterator(object),
- m_it(properties),
- m_additionalProperties(std::move(additionalProperties))
- {
- }
-
-private:
- bool hasNext() const override
- {
- return m_it.hasNext() || m_index < int(m_additionalProperties.size()) - 1;
- }
- bool hasPrevious() const override { return m_index > -1 || m_it.hasPrevious(); }
- void toFront() override { m_it.toFront(); m_index = -1; }
- void toBack() override { m_it.toBack(); m_index = int(m_additionalProperties.size()) - 1; }
-
- void next() override
- {
- QBS_ASSERT(hasNext(), return);
- if (m_it.hasNext())
- m_it.next();
- else
- ++m_index;
- }
-
- void previous() override
- {
- QBS_ASSERT(hasPrevious(), return);
- if (m_index >= 0)
- --m_index;
- if (m_index == -1)
- m_it.previous();
- }
-
- QScriptString name() const override
- {
- const QString theName = m_index >= 0 && m_index < int(m_additionalProperties.size())
- ? m_additionalProperties.at(m_index)
- : m_it.key();
- return object().engine()->toStringHandle(theName);
- }
-
- QMapIterator<QString, QVariant> m_it;
- const std::vector<QString> m_additionalProperties;
- int m_index = -1;
-};
-
-} // namespace Internal
-} // namespace qbs
-
-#endif // QBS_SCRIPTCLASSPROPERTYITERATOR_H
diff --git a/src/lib/corelib/buildgraph/transformer.cpp b/src/lib/corelib/buildgraph/transformer.cpp
index 29f2bcdf0..ae044cd2c 100644
--- a/src/lib/corelib/buildgraph/transformer.cpp
+++ b/src/lib/corelib/buildgraph/transformer.cpp
@@ -39,6 +39,7 @@
#include "transformer.h"
#include "artifact.h"
+#include "productbuilddata.h"
#include <jsextensions/moduleproperties.h>
#include <language/language.h>
#include <language/preparescriptobserver.h>
@@ -54,6 +55,7 @@
#include <QtCore/qdir.h>
#include <algorithm>
+#include <vector>
namespace qbs {
namespace Internal {
@@ -64,78 +66,82 @@ Transformer::Transformer() : alwaysRun(false)
Transformer::~Transformer() = default;
-static QScriptValue js_baseName(QScriptContext *ctx, QScriptEngine *engine,
- const Artifact *artifact)
+static JSValue js_baseName(JSContext *ctx, JSValueConst this_val, int, JSValueConst *)
{
- Q_UNUSED(ctx);
- Q_UNUSED(engine);
- return {FileInfo::baseName(artifact->filePath())};
+ return ScriptEngine::engineForContext(ctx)->getArtifactProperty(this_val,
+ [ctx](const Artifact *a) {
+ return makeJsString(ctx, FileInfo::baseName(a->filePath()));
+ });
}
-static QScriptValue js_completeBaseName(QScriptContext *ctx, QScriptEngine *engine,
- const Artifact *artifact)
+static JSValue js_completeBaseName(JSContext *ctx, JSValueConst this_val, int, JSValueConst *)
{
- Q_UNUSED(ctx);
- Q_UNUSED(engine);
- return {FileInfo::completeBaseName(artifact->filePath())};
+ return ScriptEngine::engineForContext(ctx)->getArtifactProperty(this_val,
+ [ctx](const Artifact *a) {
+ return makeJsString(ctx, FileInfo::completeBaseName(a->filePath()));
+ });
}
-static QScriptValue js_baseDir(QScriptContext *ctx, QScriptEngine *engine,
- const Artifact *artifact)
+static JSValue js_baseDir(JSContext *ctx, JSValueConst this_val, int, JSValueConst *)
{
- Q_UNUSED(ctx);
- Q_UNUSED(engine);
- QString basedir;
- if (artifact->artifactType == Artifact::SourceFile) {
- QDir sourceDir(artifact->product->sourceDirectory);
- basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));
- } else {
- QDir buildDir(artifact->product->buildDirectory());
- basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));
- }
- return basedir;
+ return ScriptEngine::engineForContext(ctx)->getArtifactProperty(this_val,
+ [ctx](const Artifact *artifact) {
+ QString basedir;
+ if (artifact->artifactType == Artifact::SourceFile) {
+ QDir sourceDir(artifact->product->sourceDirectory);
+ basedir = FileInfo::path(sourceDir.relativeFilePath(artifact->filePath()));
+ } else {
+ QDir buildDir(artifact->product->buildDirectory());
+ basedir = FileInfo::path(buildDir.relativeFilePath(artifact->filePath()));
+ }
+ return makeJsString(ctx, basedir);
+ });
}
-static QScriptValue js_children(QScriptContext *ctx, QScriptEngine *engine, const Artifact *artifact)
+static JSValue js_children(JSContext *ctx, JSValueConst this_val, int, JSValueConst *)
{
- Q_UNUSED(ctx);
- QScriptValue sv = engine->newArray();
- uint idx = 0;
- for (const Artifact *child : artifact->childArtifacts()) {
- sv.setProperty(idx++, Transformer::translateFileConfig(static_cast<ScriptEngine *>(engine),
- child, QString()));
- }
- return sv;
+ return ScriptEngine::engineForContext(ctx)->getArtifactProperty(this_val,
+ [ctx](const Artifact *artifact) {
+ JSValue sv = JS_NewArray(ctx);
+ uint idx = 0;
+
+ // FIXME: childArtifacts() is not guarded by any mutex ...
+ for (Artifact *child : artifact->childArtifacts()) {
+ JS_SetPropertyUint32(ctx, sv, idx++, Transformer::translateFileConfig(
+ ScriptEngine::engineForContext(ctx), child, QString()));
+ }
+ return sv;
+ });
}
-static void setArtifactProperty(QScriptValue &obj, const QString &name,
- QScriptValue (*func)(QScriptContext *, QScriptEngine *, const Artifact *),
- const Artifact *artifact)
+static void setArtifactProperty(JSContext *ctx, JSValue &obj, const QString &name,
+ JSCFunction *func)
{
- obj.setProperty(name, static_cast<ScriptEngine *>(obj.engine())->newFunction(func, artifact),
- QScriptValue::PropertyGetter);
+ const QByteArray nameBa = name.toUtf8();
+ const JSValue jsFunc = JS_NewCFunction(ctx, func, nameBa.constData(), 0);
+ const ScopedJsAtom nameAtom(ctx, nameBa);
+ JS_DefinePropertyGetSet(ctx, obj, nameAtom, jsFunc, JS_UNDEFINED, JS_PROP_HAS_GET);
}
-QScriptValue Transformer::translateFileConfig(ScriptEngine *scriptEngine, const Artifact *artifact,
- const QString &defaultModuleName)
+JSValue Transformer::translateFileConfig(ScriptEngine *engine, Artifact *artifact,
+ const QString &defaultModuleName)
{
- QScriptValue obj = scriptEngine->newObject();
- attachPointerTo(obj, artifact);
- ModuleProperties::init(obj, artifact);
- obj.setProperty(StringConstants::fileNameProperty(), artifact->fileName());
- obj.setProperty(StringConstants::filePathProperty(), artifact->filePath());
- setArtifactProperty(obj, StringConstants::baseNameProperty(), js_baseName, artifact);
- setArtifactProperty(obj, StringConstants::completeBaseNameProperty(), js_completeBaseName,
- artifact);
- setArtifactProperty(obj, QStringLiteral("baseDir"), js_baseDir, artifact);
- setArtifactProperty(obj, QStringLiteral("children"), js_children, artifact);
- const QStringList fileTags = sorted(artifact->fileTags().toStringList());
- scriptEngine->setObservedProperty(obj, StringConstants::fileTagsProperty(),
- scriptEngine->toScriptValue(fileTags));
- scriptEngine->observer()->addArtifactId(obj.objectId());
- if (!defaultModuleName.isEmpty())
- obj.setProperty(StringConstants::moduleNameProperty(), defaultModuleName);
- return obj;
+ return engine->getArtifactScriptValue(artifact, defaultModuleName, [&](JSValue obj) {
+ ModuleProperties::init(engine, obj, artifact);
+ JSContext * const ctx = engine->context();
+ setJsProperty(ctx, obj, StringConstants::fileNameProperty(), artifact->fileName());
+ setJsProperty(ctx, obj, StringConstants::filePathProperty(), artifact->filePath());
+ setArtifactProperty(ctx, obj, StringConstants::baseNameProperty(), js_baseName);
+ setArtifactProperty(ctx, obj, StringConstants::completeBaseNameProperty(), js_completeBaseName);
+ setArtifactProperty(ctx, obj, QStringLiteral("baseDir"), js_baseDir);
+ setArtifactProperty(ctx, obj, QStringLiteral("children"), js_children);
+ const QStringList fileTags = sorted(artifact->fileTags().toStringList());
+ const ScopedJsValue jsFileTags(ctx, engine->toScriptValue(fileTags));
+ engine->setObservedProperty(obj, StringConstants::fileTagsProperty(), jsFileTags);
+ engine->observer()->addArtifactId(jsObjectId(obj));
+ if (!defaultModuleName.isEmpty())
+ setJsProperty(ctx, obj, StringConstants::moduleNameProperty(), defaultModuleName);
+ });
}
static bool compareByFilePath(const Artifact *a1, const Artifact *a2)
@@ -143,9 +149,8 @@ static bool compareByFilePath(const Artifact *a1, const Artifact *a2)
return a1->filePath() < a2->filePath();
}
-QScriptValue Transformer::translateInOutputs(ScriptEngine *scriptEngine,
- const ArtifactSet &artifacts,
- const QString &defaultModuleName)
+JSValue Transformer::translateInOutputs(ScriptEngine *engine, const ArtifactSet &artifacts,
+ const QString &defaultModuleName)
{
using TagArtifactsMap = QMap<QString, QList<Artifact*>>;
TagArtifactsMap tagArtifactsMap;
@@ -155,16 +160,16 @@ QScriptValue Transformer::translateInOutputs(ScriptEngine *scriptEngine,
for (TagArtifactsMap::Iterator it = tagArtifactsMap.begin(); it != tagArtifactsMap.end(); ++it)
std::sort(it.value().begin(), it.value().end(), compareByFilePath);
- QScriptValue jsTagFiles = scriptEngine->newObject();
- for (TagArtifactsMap::const_iterator tag = tagArtifactsMap.constBegin(); tag != tagArtifactsMap.constEnd(); ++tag) {
+ JSValue jsTagFiles = engine->newObject();
+ for (auto tag = tagArtifactsMap.constBegin(); tag != tagArtifactsMap.constEnd(); ++tag) {
const QList<Artifact*> &artifacts = tag.value();
- QScriptValue jsFileConfig = scriptEngine->newArray(artifacts.size());
+ JSValue jsFileConfig = JS_NewArray(engine->context());
int i = 0;
for (Artifact * const artifact : artifacts) {
- jsFileConfig.setProperty(i++, translateFileConfig(scriptEngine, artifact,
- defaultModuleName));
+ JS_SetPropertyUint32(engine->context(), jsFileConfig, i++,
+ translateFileConfig(engine, artifact, defaultModuleName));
}
- jsTagFiles.setProperty(tag.key(), jsFileConfig);
+ setJsProperty(engine->context(), jsTagFiles, tag.key(), jsFileConfig);
}
return jsTagFiles;
@@ -177,66 +182,70 @@ ResolvedProductPtr Transformer::product() const
return (*outputs.cbegin())->product.lock();
}
-void Transformer::setupInputs(QScriptValue targetScriptValue, const ArtifactSet &inputs,
- const QString &defaultModuleName)
+void Transformer::setupInputs(ScriptEngine *engine, JSValue targetScriptValue,
+ const ArtifactSet &inputs, const QString &defaultModuleName)
{
- const auto scriptEngine = static_cast<ScriptEngine *>(targetScriptValue.engine());
- QScriptValue scriptValue = translateInOutputs(scriptEngine, inputs, defaultModuleName);
- targetScriptValue.setProperty(StringConstants::inputsVar(), scriptValue);
- QScriptValue inputScriptValue;
+ JSValue scriptValue = translateInOutputs(engine, inputs, defaultModuleName);
+ setJsProperty(engine->context(), targetScriptValue, StringConstants::inputsVar(), scriptValue);
+ JSValue inputScriptValue = JS_UNDEFINED;
if (inputs.size() == 1) {
Artifact *input = *inputs.cbegin();
const FileTags &fileTags = input->fileTags();
QBS_ASSERT(!fileTags.empty(), return);
- QScriptValue inputsForFileTag = scriptValue.property(fileTags.cbegin()->toString());
- inputScriptValue = inputsForFileTag.property(0);
+ const ScopedJsValue inputsForFileTag(
+ engine->context(),
+ getJsProperty(engine->context(), scriptValue, fileTags.cbegin()->toString()));
+ inputScriptValue = JS_GetPropertyUint32(engine->context(), inputsForFileTag, 0);
}
- targetScriptValue.setProperty(StringConstants::inputVar(), inputScriptValue);
+ setJsProperty(engine->context(), targetScriptValue, StringConstants::inputVar(),
+ inputScriptValue);
}
-void Transformer::setupInputs(const QScriptValue &targetScriptValue)
+void Transformer::setupInputs(ScriptEngine *engine, const JSValue &targetScriptValue)
{
- setupInputs(targetScriptValue, inputs, rule->module->name);
+ setupInputs(engine, targetScriptValue, inputs, rule->module->name);
}
-void Transformer::setupOutputs(QScriptValue targetScriptValue)
+void Transformer::setupOutputs(ScriptEngine *engine, JSValue targetScriptValue)
{
- const auto scriptEngine = static_cast<ScriptEngine *>(targetScriptValue.engine());
const QString &defaultModuleName = rule->module->name;
- QScriptValue scriptValue = translateInOutputs(scriptEngine, outputs, defaultModuleName);
- targetScriptValue.setProperty(StringConstants::outputsVar(), scriptValue);
- QScriptValue outputScriptValue;
+ JSValue scriptValue = translateInOutputs(engine, outputs, defaultModuleName);
+ setJsProperty(engine->context(), targetScriptValue, StringConstants::outputsVar(), scriptValue);
+ JSValue outputScriptValue = JS_UNDEFINED;
if (outputs.size() == 1) {
Artifact *output = *outputs.cbegin();
const FileTags &fileTags = output->fileTags();
QBS_ASSERT(!fileTags.empty(), return);
- QScriptValue outputsForFileTag = scriptValue.property(fileTags.cbegin()->toString());
- outputScriptValue = outputsForFileTag.property(0);
+ const ScopedJsValue outputsForFileTag(
+ engine->context(),
+ getJsProperty(engine->context(), scriptValue, fileTags.cbegin()->toString()));
+ outputScriptValue = JS_GetPropertyUint32(engine->context(), outputsForFileTag, 0);
}
- targetScriptValue.setProperty(StringConstants::outputVar(), outputScriptValue);
+ setJsProperty(engine->context(), targetScriptValue, StringConstants::outputVar(),
+ outputScriptValue);
}
-void Transformer::setupExplicitlyDependsOn(QScriptValue targetScriptValue)
+void Transformer::setupExplicitlyDependsOn(ScriptEngine *engine, JSValue targetScriptValue)
{
- const auto scriptEngine = static_cast<ScriptEngine *>(targetScriptValue.engine());
- QScriptValue scriptValue = translateInOutputs(scriptEngine, explicitlyDependsOn,
- rule->module->name);
- targetScriptValue.setProperty(StringConstants::explicitlyDependsOnVar(), scriptValue);
+ JSValue scriptValue = translateInOutputs(engine, explicitlyDependsOn, rule->module->name);
+ setJsProperty(engine->context(), targetScriptValue, StringConstants::explicitlyDependsOnVar(),
+ scriptValue);
}
-AbstractCommandPtr Transformer::createCommandFromScriptValue(const QScriptValue &scriptValue,
- const CodeLocation &codeLocation)
+AbstractCommandPtr Transformer::createCommandFromScriptValue(
+ ScriptEngine *engine, const JSValue &scriptValue, const CodeLocation &codeLocation)
{
AbstractCommandPtr cmdBase;
- if (scriptValue.isUndefined() || !scriptValue.isValid())
+ if (JS_IsUndefined(scriptValue) || JS_IsUninitialized(scriptValue))
return cmdBase;
- QString className = scriptValue.property(StringConstants::classNameProperty()).toString();
+ QString className = getJsStringProperty(engine->context(), scriptValue,
+ StringConstants::classNameProperty());
if (className == StringConstants::commandType())
cmdBase = ProcessCommand::create();
else if (className == StringConstants::javaScriptCommandType())
cmdBase = JavaScriptCommand::create();
if (cmdBase)
- cmdBase->fillFromScriptValue(&scriptValue, codeLocation);
+ cmdBase->fillFromScriptValue(engine->context(), &scriptValue, codeLocation);
if (className == StringConstants::commandType()) {
auto procCmd = static_cast<ProcessCommand *>(cmdBase.get());
procCmd->clearRelevantEnvValues();
@@ -248,18 +257,20 @@ AbstractCommandPtr Transformer::createCommandFromScriptValue(const QScriptValue
}
void Transformer::createCommands(ScriptEngine *engine, const PrivateScriptFunction &script,
- const QScriptValueList &args)
+ const JSValueList &args)
{
- if (!script.scriptFunction.isValid() || script.scriptFunction.engine() != engine) {
- script.scriptFunction = engine->evaluate(script.sourceCode(),
+ if (JS_IsUndefined(script.scriptFunction)) {
+ script.scriptFunction = engine->evaluate(JsValueOwner::ScriptEngine, script.sourceCode(),
script.location().filePath(),
script.location().line());
- if (Q_UNLIKELY(!script.scriptFunction.isFunction()))
+ if (Q_UNLIKELY(!JS_IsFunction(engine->context(), script.scriptFunction)))
throw ErrorInfo(Tr::tr("Invalid prepare script."), script.location());
}
-
- QScriptValue scriptValue = script.scriptFunction.call(QScriptValue(), args);
- engine->releaseResourcesOfScriptObjects();
+ JSValueList argv(args.cbegin(), args.cend());
+ const ScopedJsValue scriptValue(
+ engine->context(),
+ JS_Call(engine->context(), script.scriptFunction, engine->globalObject(),
+ int(argv.size()), argv.data()));
propertiesRequestedInPrepareScript = engine->propertiesRequestedInScript();
propertiesRequestedFromArtifactInPrepareScript = engine->propertiesRequestedFromArtifact();
importedFilesUsedInPrepareScript = engine->importedFilesUsedInScript();
@@ -271,22 +282,24 @@ void Transformer::createCommands(ScriptEngine *engine, const PrivateScriptFuncti
p->exportedModule));
}
engine->clearRequestedProperties();
- if (Q_UNLIKELY(engine->hasErrorOrException(scriptValue)))
- throw engine->lastError(scriptValue, script.location());
+ if (JsException ex = engine->checkAndClearException(script.location()))
+ throw ex.toErrorInfo();
commands.clear();
- if (scriptValue.isArray()) {
- const int count = scriptValue.property(StringConstants::lengthProperty()).toInt32();
+ if (JS_IsArray(engine->context(), scriptValue)) {
+ const int count = JS_VALUE_GET_INT(getJsProperty(engine->context(), scriptValue,
+ StringConstants::lengthProperty()));
for (qint32 i = 0; i < count; ++i) {
- QScriptValue item = scriptValue.property(i);
- if (item.isValid() && !item.isUndefined()) {
- const AbstractCommandPtr cmd
- = createCommandFromScriptValue(item, script.location());
+ ScopedJsValue item(engine->context(),
+ JS_GetPropertyUint32(engine->context(), scriptValue, i));
+ if (!JS_IsUninitialized(item) && !JS_IsUndefined(item)) {
+ const AbstractCommandPtr cmd = createCommandFromScriptValue(engine, item,
+ script.location());
if (cmd)
commands.addCommand(cmd);
}
}
} else {
- const AbstractCommandPtr cmd = createCommandFromScriptValue(scriptValue,
+ const AbstractCommandPtr cmd = createCommandFromScriptValue(engine, scriptValue,
script.location());
if (cmd)
commands.addCommand(cmd);
diff --git a/src/lib/corelib/buildgraph/transformer.h b/src/lib/corelib/buildgraph/transformer.h
index 8772ed868..927572310 100644
--- a/src/lib/corelib/buildgraph/transformer.h
+++ b/src/lib/corelib/buildgraph/transformer.h
@@ -52,6 +52,8 @@
#include <tools/filetime.h>
#include <tools/persistence.h>
+#include <quickjs.h>
+
#include <QtCore/qhash.h>
namespace qbs {
@@ -91,15 +93,14 @@ public:
bool commandsNeedChangeTracking = false;
bool markedForRerun = false;
- static QScriptValue translateFileConfig(ScriptEngine *scriptEngine,
- const Artifact *artifact,
- const QString &defaultModuleName);
+ static JSValue translateFileConfig(ScriptEngine *engine, Artifact *artifact,
+ const QString &defaultModuleName);
ResolvedProductPtr product() const;
- void setupInputs(const QScriptValue &targetScriptValue);
- void setupOutputs(QScriptValue targetScriptValue);
- void setupExplicitlyDependsOn(QScriptValue targetScriptValue);
+ void setupInputs(ScriptEngine *engine, const JSValue &targetScriptValue);
+ void setupOutputs(ScriptEngine *engine, JSValue targetScriptValue);
+ void setupExplicitlyDependsOn(ScriptEngine *engine, JSValue targetScriptValue);
void createCommands(ScriptEngine *engine, const PrivateScriptFunction &script,
- const QScriptValueList &args);
+ const JSValueList &args);
void rescueChangeTrackingData(const TransformerConstPtr &other);
Set<QString> jobPools() const;
@@ -124,14 +125,13 @@ public:
private:
Transformer();
- AbstractCommandPtr createCommandFromScriptValue(const QScriptValue &scriptValue,
+ AbstractCommandPtr createCommandFromScriptValue(ScriptEngine *engine, const JSValue &scriptValue,
const CodeLocation &codeLocation);
- static void setupInputs(QScriptValue targetScriptValue, const ArtifactSet &inputs,
- const QString &defaultModuleName);
- static QScriptValue translateInOutputs(ScriptEngine *scriptEngine,
- const ArtifactSet &artifacts,
- const QString &defaultModuleName);
+ static void setupInputs(ScriptEngine *engine, JSValue targetScriptValue,
+ const ArtifactSet &inputs, const QString &defaultModuleName);
+ static JSValue translateInOutputs(ScriptEngine *engine, const ArtifactSet &artifacts,
+ const QString &defaultModuleName);
};
} // namespace Internal