8

我正在使用 QtScript 来自动化我的应用程序的某些部分,以用于开发和测试目的。我已经到了要测试断言的地步,并且基于“独立断言库”?以及我在 Debian 存储库中可以找到的内容,我选择了 Should.js。

我无法将它加载到我的 Qt 应用程序中,因为它取决于 Node 的require()功能。我尝试实现一个版本,从“支持 CommonJS 的 require()”开始,到下面的代码结束。

可以使它起作用,还是我注定要采用这种方法?将 should.js 的部分复制到单个文件中可能会更好吗?我不想让自己负责保持叉子的最新状态。(许可不是问题,因为我不打算重新分发此代码)。

这是我的 MCVE;对不起,我不能让它更短!

应该.cpp

#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QScriptEngine>
#include <QScriptContext>
#include <QScriptContextInfo>
#include <QTextStream>


// Primitive implementation of Node.js require().
// N.B. Supports only .js sources.
QScriptValue require(QScriptContext* context, QScriptEngine* engine)
{
    const QString moduleName = context->argument(0).toString();

    // First, look in our modules cache
    QScriptValue modules = engine->globalObject().property("$MODULES");
    QScriptValue module = modules.property(moduleName);
    if (module.isValid()) {
        auto cached_file = module.property("filename");
        auto time_stamp = module.property("timestamp");
        auto code = module.property("code");
        if (code.isObject() && cached_file.isString() && time_stamp.isDate()) {
            if (QFileInfo(cached_file.toString()).lastModified() == time_stamp.toDateTime()) {
                qDebug() << "found up-to-date module for require of" << moduleName;
                return code;
            } else {
                qDebug() << "cache stale for" << moduleName;
            }
        }
    } else {
        // Prepare a cache entry, as some modules recursively include each
        // other.  This way, they at least get the partial definition of the
        // other, rather than a stack overflow.
        module = engine->newObject();
        modules.setProperty(moduleName, module);
    }

    qDebug() << "require" << moduleName;

    // resolve filename relative to the calling script
    QString filename = moduleName + ".js";
    for (auto *p = context;  p;  p = p->parentContext()) {
        QScriptContextInfo info(p);
        auto parent_file = info.fileName();
        if (parent_file.isEmpty())
            continue;
        // else, we reached a context with a filename
        QDir base_dir = QFileInfo(parent_file).dir();
        filename = base_dir.filePath(filename);
        if (QFile::exists(filename)) {
            break;
        }
    }

    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        return context->throwValue(QString("Failed to open %0").arg(moduleName));
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");
    auto script = in.readAll();
    file.close();

#if 0
    // I had to disable this, because it barfs on "get not()" definition - is
    // that a Node extension?  Will it cause me problems even if I get require()
    // working?
    auto syntax_check = QScriptEngine::checkSyntax(script);
    if (syntax_check.state() != QScriptSyntaxCheckResult::Valid) {
        return context->throwValue(QString("%2:%0:%1: Syntax error: %3")
                                   .arg(syntax_check.errorLineNumber())
                                   .arg(syntax_check.errorColumnNumber())
                                   .arg(filename, syntax_check.errorMessage()));
    }
#endif

    // create a new context, and capture the module's exports
    QScriptContext* newContext = engine->pushContext();
    QScriptValue exports = engine->newObject();
    newContext->activationObject().setProperty("exports", exports);
    module.setProperty("code", exports);
    module.setProperty("filename", filename);
    module.setProperty("timestamp", engine->newDate(QFileInfo(filename).lastModified()));
    // run the script
    engine->evaluate(script, filename);
    // get the exports
    module.setProperty("code", newContext->activationObject().property("exports"));
    engine->popContext();
    if (engine->hasUncaughtException())
        return engine->uncaughtException();
    qDebug() << "loaded" << moduleName;
    return exports;
}


int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QScriptEngine engine;

    // register global require() function
    auto global = engine.globalObject();
    global.setProperty("require", engine.newFunction(require));
    global.setProperty("$MODULES", engine.newObject());

    engine.evaluate("var should = require('/usr/lib/nodejs/should/lib/should');");

    if (engine.hasUncaughtException()) {
        qCritical() << engine.uncaughtException().toString().toStdString().c_str();
        qWarning() << engine.uncaughtExceptionBacktrace().join("\n").toStdString().c_str();
        return 1;
    }
    return 0;
}

生成文件

check: should
    ./should

CXXFLAGS += -std=c++11 -Wall -Wextra -Werror
CXXFLAGS += -fPIC
CXXFLAGS += $(shell pkg-config --cflags Qt5Script)
LDLIBS += $(shell pkg-config --libs Qt5Script)

输出是

require "/usr/lib/nodejs/should/lib/should" 
require "./util" 
require "./inspect" 
found up-to-date module for require of "./util" 
loaded "./inspect" 
require "assert" 
Failed to open assert 
<eval>() at /usr/lib/nodejs/should/lib/./util.js:126
<native>() at -1
<native>('./util') at -1
<eval>() at /usr/lib/nodejs/should/lib/should.js:8
<native>() at -1
<native>('/usr/lib/nodejs/should/lib/should') at -1
<global>() at 1

(顺便说一句 - 我如何require在堆栈跟踪中获取实际的函数名称而不是<native>?插槽管理这个,所以我应该能够,对吧?)

4

1 回答 1

1

我已经对其进行了更详细的研究,并且重写 C++ Qt 要求系统对我来说比最初认为的要花费更多时间。具有 -ing 核心模块的库也存在问题require(这反过来require会导致未定义的行为的本机模块 - 阅读:可能不起作用)。

方法 #1 -C++ require()实施:

在 C++ Qt 中实现自定义node require(),就像在您的问题和链接中已经开始一样。的工作细节node.js require()可以在这里找到。您需要node在搜索路径中包含核心模块require()(您可以从node.js源存储库中获取它们)。

方法 #2 - 使用browserify

由于我们在 #1 中试图解决的问题基本上是加载和缓存 javascript 文件,为什么不使用已经存在的东西来实现相同的目的。通过这种方式,我们可以避免手动工作并且捆绑javascript我们有强烈的迹象表明它将在浏览器上工作(然后是更有限的环境node.js)。

$ npm install -g browserify
$ npm install expect

index.js

var expect = require('expect');
expect(1).toEqual(1);

并运行browserify

$ browserify index.js -o bundle.js

在你的Qt C++

QString script = loadFile("/path/to/bundle.js");
engine.evaluate(script);

我们已经找到了一种解决方法,require()但是我不确定互操作性。与Qt. Syntax Error另外,我从 QtScript 中遇到了一些js模块,所以这不是灵丹妙药,即使最初看起来如此。

注意:这也是一个有趣的项目:https ://github.com/svalaskevicius/qtjs-generator 。

于 2015-12-09T22:40:07.297 回答