diff --git a/src/qmljsc/ir/typesystem.cpp b/src/qmljsc/ir/typesystem.cpp index 73d0230..f545dc1 100644 --- a/src/qmljsc/ir/typesystem.cpp +++ b/src/qmljsc/ir/typesystem.cpp @@ -1,153 +1,175 @@ /* * Qml.js Compiler - a QML to JS compiler bringing QML's power to the web. * * Copyright (C) 2015 Anton Kreuzkamp * Copyright (C) 2015 Jan Marker * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include "typesystem.h" using namespace QmlJSc::IR; Type::Type() : m_super(0) { } +Type::Type(Flags flags) + : m_flags(flags) + , m_super(0) +{ +} + const QString &Type::name() { return m_name; } const QString &Type::javaScriptName() { return m_javaScriptName; } +Type::Flags Type::flags() +{ + return m_flags; +} + +void Type::setFlags(Flags flags) +{ + m_flags = flags; +} + Property *Type::addProperty(const QString &name) { return &m_properties.insert(name, Property(name)).value(); } Method *Type::addMethod(const QString &name) { return &m_methods.insert(name, Method(name)).value(); } Signal *Type::addSignal(const QString &name) { return &m_signals.insert(name, Signal(name)).value(); } void Type::setName(const QString &name) { m_name = name; } void Type::setJavaScriptName(const QString &jsName) { m_javaScriptName = jsName; } Property *Type::property(const QString &name) { if (m_properties.contains(name)) { return &m_properties[name]; } if (m_super) { return m_super->property(name); } return 0; } Method *Type::method(const QString &name) { if (m_methods.contains(name)) { return &m_methods[name]; } if (m_super) { return m_super->method(name); } return 0; } Signal *Type::signal(const QString &name) { if (m_signals.contains(name)) { return &m_signals[name]; } if (m_super) { return m_super->signal(name); } return 0; } Type *Type::super() { return m_super; } void Type::setSuper(Type *superType) { m_super = superType; } -LibraryClass::LibraryClass() - : Type() +Type * Type::attachedType() +{ + return m_attachedType; +} + +void Type::setAttachedType(Type *attachedType) { + m_attachedType = attachedType; } + Method::Method() : returnType(0) { } Method::Method(const QString &name) : returnType(0) , name(name) { } Method::Method(Type *returnType, QString name) : returnType(returnType) , name(name) { } Signal::Signal() { } Signal::Signal(QString name) : name(name) { } Property::Property() : type(0) { } Property::Property(const QString &name) : type(0) , name(name) { } Property::Property(Type *type, QString name) : type(type) , name(name) { } \ No newline at end of file diff --git a/src/qmljsc/ir/typesystem.h b/src/qmljsc/ir/typesystem.h index 0c87b0c..6243287 100644 --- a/src/qmljsc/ir/typesystem.h +++ b/src/qmljsc/ir/typesystem.h @@ -1,138 +1,145 @@ /* * Qml.js Compiler - a QML to JS compiler bringing QML's power to the web. * * Copyright (C) 2015 Anton Kreuzkamp * Copyright (C) 2015 Jan Marker * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #ifndef TYPESYSTEM_H #define TYPESYSTEM_H #include #include #include namespace QQmlJS { namespace AST { class ExpressionNode; } } namespace QmlJSc { namespace IR { class Property; class Method; class Signal; /** * This class provides API representing Qml.js objects and types and allows to * learn about the type's properties, functions, etc. * * Type hereby refers to (built in) basic types, types provided by modules and * components as well as any objects defined in QML. */ class Type { public: + enum Flag { + None = 0, + IsInstantiable = 1, + IsComponent = 2 + }; + Q_DECLARE_FLAGS(Flags, Flag); + Type(); + Type(Flags flags); const QString &name(); const QString &javaScriptName(); Property *property(const QString &name); Method *method(const QString &name); Signal *signal(const QString &name); Property *addProperty(const QString &name); Method *addMethod(const QString &name); Signal *addSignal(const QString &name); void setName(const QString &name); void setJavaScriptName(const QString &jsName); Type *super(); void setSuper(Type *superType); + void setFlags(Flags flags); + Flags flags(); + + Type *attachedType(); + void setAttachedType(Type *); + protected: QString m_name; QString m_javaScriptName; + Flags m_flags; QHash m_properties; QHash m_methods; QHash m_signals; + Type *m_attachedType; /** * pointer to the super class or in case of objects the class of the object */ Type *m_super; friend class TestIR; }; -class LibraryClass : public Type -{ -public: - LibraryClass(); - -private: - Type *m_attached; -}; - struct Parameter { Type *type; QString name; }; class Method { public: Method(); Method(const QString &name); Method(Type *returnType, QString name); Type *returnType; QString name; QVector parameters; }; class Signal { public: Signal(); Signal(QString name); QString name; QVector parameters; }; class Property { public: Property(); Property(const QString &name); Property(Type *type, QString name); Type *type; QString name; bool readOnly :1; bool constant :1; bool dummy :6; }; } // namespace IR } // namespace QmlJSc #endif // TYPESYSTEM_H diff --git a/src/qmljsc/moduleloading/javascriptmoduleloader.cpp b/src/qmljsc/moduleloading/javascriptmoduleloader.cpp index 4af4b9f..c98be3d 100644 --- a/src/qmljsc/moduleloading/javascriptmoduleloader.cpp +++ b/src/qmljsc/moduleloading/javascriptmoduleloader.cpp @@ -1,510 +1,510 @@ /* * Qml.js Compiler - a QML to JS compiler bringing QML's power to the web. * * Copyright (C) 2015 Anton Kreuzkamp * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ // Own #include "javascriptmoduleloader.h" #include "moduleloading.h" #include "ir/module.h" #include "ir/typesystem.h" #include "compiler.h" #include "error.h" // Qt #include #include #include #include // Qt private #include #include #include #define assert(condition, token, errorMessage) \ if (!condition) { \ assertFailed(token, errorMessage); \ } using namespace QmlJSc; using namespace QQmlJS; static void assertFailed(const AST::SourceLocation &token, QString errorMessage) { // Normally you wouldn't throw by reference but by value. We need to create // the error object on the stack and throw by pointer, because we'll need it // to be available on another thread. Error *error = new Error(Error::ModuleImportError, errorMessage); error->setLine(token.startLine); error->setColumn(token.startColumn); throw error; } RegisterModuleVisitor::RegisterModuleVisitor(IR::Module* module) : QQmlJS::AST::Visitor() , m_module(module) { } bool RegisterModuleVisitor::visit(AST::CallExpression *call) { if (call->base->kind != AST::Node::Kind_FieldMemberExpression) { return true; } AST::FieldMemberExpression *base = AST::cast(call->base); if (!base || base->name != QStringLiteral("registerModule")) { return true; } AST::IdentifierExpression *probablyEngine = AST::cast(base->base); if (!probablyEngine || probablyEngine->name != QStringLiteral("__engine")) { return true; } // Ok, apparently, it's the __engine.registerModule expression, we're looking for. // If now still some assumption fails, throw an error. if (!call->arguments) { Error *error = new Error(Error::ModuleImportError, "Malformed registerModule call: No argument provided."); error->setLine(call->lparenToken.startLine); error->setColumn(call->lparenToken.startColumn); throw error; } AST::ObjectLiteral *moduleInfoLiteral = AST::cast(call->arguments->expression); assert(moduleInfoLiteral, call->lparenToken, "Malformed registerModule call: Wrong argument type provided. Expected Object Literal."); AST::PropertyAssignmentList *assignment = moduleInfoLiteral->properties; while(assignment) { AST::PropertyNameAndValue *nameAndValue = AST::cast(assignment->assignment); assert(nameAndValue, assignment->assignment->firstSourceLocation(), "Malformed registerModule call: Invalid type specification." ); AST::IdentifierExpression *functionId = AST::cast(nameAndValue->value); assert(functionId, nameAndValue->value->firstSourceLocation(), "Malformed registerModule call: Can't recognize function identifier. " "Please use a simple identifier as value on type object." ); - IR::LibraryClass *c = new IR::LibraryClass; + IR::Type *c = new IR::Type; c->setName(nameAndValue->name->asString()); c->setJavaScriptName(functionId->name.toString()); m_module->addType(c); assignment = assignment->next; } return true; } TypeDefinitionVisitor::TypeDefinitionVisitor(IR::Module* module) : QQmlJS::AST::Visitor() , m_module(module) { } bool TypeDefinitionVisitor::visit(AST::FunctionExpression* func) { m_currentFunctionStack << func; return true; } void TypeDefinitionVisitor::endVisit(AST::FunctionExpression* func) { m_currentFunctionStack.removeLast(); } bool TypeDefinitionVisitor::visit(AST::FunctionDeclaration* func) { m_currentFunctionStack << func; return true; } void TypeDefinitionVisitor::endVisit(AST::FunctionDeclaration* func) { m_currentFunctionStack.removeLast(); } bool TypeDefinitionVisitor::visit(AST::BinaryExpression* expr) { // --- Might be a property, a method, a signal, a class or uninteresting. if (expr->right->kind == AST::Node::Kind_FunctionExpression) { findMethodDefinition(expr); // Each function expression is a potential class definition. Give it // a name, so we may reference it later on. QStringRef name; if (expr->left->kind == AST::Node::Kind_FieldMemberExpression) { name = AST::cast(expr->left)->name; } else if (expr->left->kind == AST::Node::Kind_FunctionExpression) { name = AST::cast(expr->left)->name; } else { return true; } AST::cast(expr->right)->name = name; } else if (expr->right->kind == AST::Node::Kind_CallExpression) { findSignalDefinition(expr); } else if (expr->right->kind == AST::Node::Kind_NewMemberExpression) { findPropertyDefinition(expr); } return true; } bool TypeDefinitionVisitor::visit(AST::VariableDeclaration *var) { AST::FunctionExpression *func = AST::cast(var->expression); if (!func) { return true; } // This is a potential class definition. Give the function a name, so we may // reference it later on. func->name = var->name; return true; } bool TypeDefinitionVisitor::visit(AST::CallExpression *call) { if (call->base->kind != AST::Node::Kind_IdentifierExpression) { return true; } AST::IdentifierExpression *maybeInheritance = AST::cast(call->base); if (!maybeInheritance || maybeInheritance->name != QStringLiteral("QW_INHERIT")) { return true; } // Apparently this is a QW_INHERIT call, we're looking for. // If now still some assumption fails, throw an error. assert(call->arguments && call->arguments->next, call->lparenToken, "Malformed QW_INHERIT call: One or no argument provided. Expected two." ); AST::IdentifierExpression *constructor = AST::cast(call->arguments->expression); AST::IdentifierExpression *baseClass = AST::cast(call->arguments->next->expression); assert(constructor && baseClass, call->lparenToken, "Malformed QW_INHERIT call: Wrong argument types provided. Expected two identifier expressions." ); IR::Type *t = m_module->typeFromJSName(constructor->name.toString()); assert(t, constructor->firstSourceLocation(), "Using a type that won't get registered."); t->setSuper(getType(baseClass->name)); return true; } void TypeDefinitionVisitor::findPropertyDefinition(AST::BinaryExpression *expr) { if (expr->op != QSOperator::Assign) { return; } AST::FieldMemberExpression *lValue = AST::cast(expr->left); AST::NewMemberExpression *rValue = AST::cast(expr->right); if (!rValue || !lValue) { return; } AST::IdentifierExpression *constructor = AST::cast(rValue->base); AST::ThisExpression *maybeThis = AST::cast(lValue->base); if (!constructor || constructor->name != QStringLiteral("QWProperty") || !maybeThis) { return; } // Ok, this is a property definition IR::Type *t = m_module->typeFromJSName(m_currentFunctionStack.last()->name.toString()); assert(t, lValue->firstSourceLocation(), "Registering properties to a type that won't get registered."); IR::Property *property = t->addProperty(lValue->name.toString()); AST::ObjectLiteral *parameters = AST::cast(rValue->arguments->expression); if (!parameters) { return; } for (AST::PropertyAssignmentList *aList = parameters->properties; aList; aList = aList->next) { AST::PropertyNameAndValue *nameAndValue = AST::cast(aList->assignment); assert(nameAndValue, aList->assignment->firstSourceLocation(), "Malformed QWProperty call: Expected argument to be a name value pair." ); if (nameAndValue->name->asString() == "type") { AST::IdentifierExpression *id = AST::cast(nameAndValue->value); assert(id, nameAndValue->value->firstSourceLocation(), "Malformed QWProperty call: Expected argument 'type' to have an identifier expression as value." ); property->type = getType(id->name); continue; } if (nameAndValue->name->asString() == "typeArg") { AST::IdentifierExpression *id = AST::cast(nameAndValue->value); assert(id, nameAndValue->value->firstSourceLocation(), "Malformed QWProperty call: Expected argument 'typeArg' to have an identifier expression as value." ); property->type = getType(id->name); continue; } if (nameAndValue->name->asString() == "readonly") { assert(nameAndValue->value->kind == AST::Node::Kind_TrueLiteral || nameAndValue->value->kind == AST::Node::Kind_FalseLiteral, nameAndValue->colonToken, "Malformed QWProperty call: readonly may only have true or false as value." ); property->readOnly = nameAndValue->value->kind == AST::Node::Kind_TrueLiteral; continue; } if (nameAndValue->name->asString() == "constant") { assert(nameAndValue->value->kind == AST::Node::Kind_TrueLiteral || nameAndValue->value->kind == AST::Node::Kind_FalseLiteral, nameAndValue->colonToken, "Malformed QWProperty call: constant may only have true or false as value." ); property->constant = nameAndValue->value->kind == AST::Node::Kind_TrueLiteral; continue; } } } void TypeDefinitionVisitor::findMethodDefinition(AST::BinaryExpression *expr) { if (expr->op != QSOperator::Assign) { return; } AST::FieldMemberExpression *lValue = AST::cast(expr->left); AST::FunctionExpression *func = AST::cast(expr->right); IR::Type *t; if (lValue->base->kind == AST::Node::Kind_ThisExpression) { t = m_module->typeFromJSName(m_currentFunctionStack.last()->name.toString()); } else { AST::FieldMemberExpression *first = AST::cast(lValue->base); if (!first || first->name != QStringLiteral("prototype")) { return; } AST::IdentifierExpression *constructor = AST::cast(first->base); if (!first) { return; } t = m_module->typeFromJSName(constructor->name.toString()); } if (!t) { return; } // Treat as a method definiton of a class. We can't ever be sure, but let's // try and discard later, if it turns out not to be one. IR::Method *method = t->addMethod(lValue->name.toString()); AST::FormalParameterList *parameter = func->formals; while (parameter) { method->parameters << parameter->name.toString(); parameter = parameter->next; } } void TypeDefinitionVisitor::findSignalDefinition(AST::BinaryExpression *expr) { if (expr->op != QSOperator::Assign) { return; } AST::FieldMemberExpression *lValue = AST::cast(expr->left); AST::CallExpression *rValue = AST::cast(expr->right); if (!rValue || !lValue) { return; } AST::IdentifierExpression *maybeSignal = AST::cast(rValue->base); AST::ThisExpression *maybeThis = AST::cast(lValue->base); if (!maybeSignal || maybeSignal->name != QStringLiteral("QWSignal") || !maybeThis) { return; } // Ok, this is a signal definition IR::Type *t = m_module->typeFromJSName(m_currentFunctionStack.last()->name.toString()); assert(t, lValue->firstSourceLocation(), "Registering a signal to a type that won't get registered."); IR::Signal *signal = t->addSignal(lValue->name.toString()); AST::ArgumentList *argumentList = rValue->arguments; if (!argumentList) { return; // Ok, no arguments, so we're done here. } AST::ArrayLiteral *arrayLit = AST::cast(argumentList->expression); assert(arrayLit, argumentList->expression->firstSourceLocation(), "Malformed Signal definition:" " First argument must be an array literal."); AST::ElementList *array = arrayLit->elements; // Go through all the elements in the list, each of which is an object // literal describing one parameter while (array) { AST::ObjectLiteral *parameterObject = AST::cast(array->expression); assert(parameterObject, array->expression->firstSourceLocation(), "Malformed Signal definition: Array elements must be object literals."); AST::PropertyAssignmentList *parameterData = parameterObject->properties; IR::Type *type = 0; QString name; // Go through all properties of the object literal. Basically we're // looking for "type" and "name" while (parameterData) { AST::PropertyNameAndValue *nameAndValue = AST::cast(parameterData->assignment); assert(nameAndValue, parameterData->assignment->firstSourceLocation(), "Malformed Signal definition: The definition of a parameter " "must only contain name and value."); if (nameAndValue->name->asString() == QStringLiteral("type")) { AST::IdentifierExpression *t = AST::cast(nameAndValue->value); assert(t, nameAndValue->value->firstSourceLocation(), "Malformed Signal definition:" "The type definition of a parameter must be an identifier expression" "that refers to a type."); type = getType(t->name); } else if (nameAndValue->name->asString() == QStringLiteral("name")) { AST::StringLiteral *n = AST::cast(nameAndValue->value); assert(n, nameAndValue->value->firstSourceLocation(), "Malformed Signal definition:" "The name definition of a parameter must be a string literal."); name = n->value.toString(); } parameterData = parameterData->next; } signal->parameters.append({type, name}); array = array->next; } } IR::Type *TypeDefinitionVisitor::getType(const QStringRef& name) { IR::Type *t = 0; t = m_module->typeFromJSName(name.toString()); // TODO: Search different locations (Task T488). return t; } JavaScriptModuleLoader *JavaScriptModuleLoader::create(IR::Module *module) { return new JavaScriptModuleLoader(module); } JavaScriptModuleLoader::JavaScriptModuleLoader(IR::Module *module) : AbstractModuleLoader(module) {} bool JavaScriptModuleLoader::canLoad() { IR::Module *module = AbstractModuleLoader::module(); QString moduleFileName = QStringLiteral("%1.%2.%3.js").arg(module->importDescription().name) .arg(module->importDescription().versionMajor) .arg(module->importDescription().versionMinor); // For now we only support local files. const QStringList &includePaths = compiler->includePaths(); foreach (QString includePath, includePaths) { QDir includeDir(includePath); if (includeDir.exists(moduleFileName)) { m_moduleFile.setFileName(includeDir.absoluteFilePath(moduleFileName)); break; } } return m_moduleFile.exists(); } void JavaScriptModuleLoader::doLoad() { IR::Module *module = AbstractModuleLoader::module(); if (!m_moduleFile.exists()) { // We checked that already, so it should never happen. throw new Error(Error::ModuleImportError, QStringLiteral("Could not find file %1 in path.").arg(m_moduleFile.fileName())); } // Read file m_moduleFile.open(QFile::ReadOnly); QTextStream modueFileStream(&m_moduleFile); QString moduleSource = modueFileStream.readAll(); // === Parse file === // parsing happens in three steps: Calling the QQmlJS-parser to parse the // file and return an AST, then using the visit functions of this class to // collect the data we need and and third calling finalizeParse() to // evaluate the parse data and transform it to actual type information. QQmlJS::Engine* engine = new QQmlJS::Engine(); QQmlJS::Lexer* lexer = new QQmlJS::Lexer(engine); lexer->setCode(moduleSource, 1, true); QQmlJS::Parser* parser = new QQmlJS::Parser(engine); bool successfullyParsed = parser->parseProgram(); if (!successfullyParsed) { Error *err = new Error(Error::ParseError, parser->errorMessage()); err->setColumn(parser->errorColumnNumber()); err->setLine(parser->errorLineNumber()); throw new Error(Error::ModuleImportError, QStringLiteral("Error while processing module %1 %2.%3") .arg(module->importDescription().name) .arg(module->importDescription().versionMajor) .arg(module->importDescription().versionMinor), err); } AST::Program *ast = AST::cast(parser->rootNode()); try { RegisterModuleVisitor registerModuleVisitor(module); TypeDefinitionVisitor typeDefinitionVisitor(module); ast->accept(®isterModuleVisitor); ast->accept(&typeDefinitionVisitor); } catch (Error *e) { e->setFile(m_moduleFile.fileName()); throw e; } module->setLoadingState(IR::Module::Successful); } diff --git a/tests/auto/qmljsc/testir.cpp b/tests/auto/qmljsc/testir.cpp index 30baef9..4804fe5 100644 --- a/tests/auto/qmljsc/testir.cpp +++ b/tests/auto/qmljsc/testir.cpp @@ -1,362 +1,362 @@ /* * Qml.js Compiler - a QML to JS compiler bringing QML's power to the web. * * Copyright (C) 2015 Anton Kreuzkamp * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include #include #include #include #include "../../../src/qmljsc/compiler.h" #include "../../../src/qmljsc/ir/objecttree.h" #include "../../../src/qmljsc/ir/visitor.h" #include "../../../src/qmljsc/ir/typesystem.h" // Qt private #include namespace QmlJSc { namespace IR { class TestIR : public QObject { Q_OBJECT public: TestIR(); private slots: void initTestCase(); void testBasics(); void testAdd(); void testVisitorAPI(); private: - LibraryClass city; + Type city; Object christiania; Object copenhagen; - LibraryClass state; - LibraryClass democracy; + Type state; + Type democracy; Object ottomanEmpire; Object denmark; QString christianiaName; QString copenhagenName; QString ottomanEmpireName; QString ottomanEmpireLanguage; QString denmarkName; QString denmarkLanguage; QString denmarkRParty; QStringRef christianiaNameRef; QStringRef copenhagenNameRef; QStringRef ottomanEmpireNameRef; QStringRef ottomanEmpireLangRef; QStringRef denmarkNameRef; QStringRef denmarkLangRef; QStringRef denmarkRPartyRef; QQmlJS::AST::StringLiteral christianiaNameNode; QQmlJS::AST::StringLiteral copenhagenNameNode; QQmlJS::AST::StringLiteral ottomanEmpireNameNode; QQmlJS::AST::StringLiteral ottomanEmpireLangNode; QQmlJS::AST::StringLiteral denmarkNameNode; QQmlJS::AST::StringLiteral denmarkLangNode; QQmlJS::AST::StringLiteral denmarkRPartyNode; QQmlJS::AST::NumericLiteral christianiaPostCodeNode; }; TestIR::TestIR() : QObject() , christianiaName(QStringLiteral("Fristad Christiania")) , copenhagenName(QStringLiteral("København")) , ottomanEmpireName(QStringLiteral("Osmanlı İmparatorluğu")) , ottomanEmpireLanguage(QStringLiteral("Ottoman Turkish")) , denmarkName(QStringLiteral("Danmark")) , denmarkLanguage(QStringLiteral("Danish")) , denmarkRParty(QStringLiteral("S-RV")) , christianiaNameRef(&christianiaName) , copenhagenNameRef(&copenhagenName) , ottomanEmpireNameRef(&ottomanEmpireName) , ottomanEmpireLangRef(&ottomanEmpireLanguage) , denmarkNameRef(&denmarkName) , denmarkLangRef(&denmarkLanguage) , denmarkRPartyRef(&denmarkRParty) , christianiaNameNode(christianiaNameRef) , copenhagenNameNode(copenhagenNameRef) , ottomanEmpireNameNode(ottomanEmpireNameRef) , ottomanEmpireLangNode(ottomanEmpireLangRef) , denmarkNameNode(denmarkNameRef) , denmarkLangNode(denmarkLangRef) , denmarkRPartyNode(denmarkRPartyRef) , christianiaPostCodeNode(1050) { } void TestIR::initTestCase() { city.m_name = "City"; city.m_properties = { {"name", {0,"name"}}, {"postCode", {0,"postCode"}} }; city.m_methods = { {"visit", {0, "visit"}}, }; state.m_name = "State"; state.m_properties = { {"name", {0,"name"}}, {"language", {0,"language"}}, {"capital", {&city, "capital"}} }; state.m_methods = { {"visit", {0, "visit"}}, }; Signal isOffensive("warStarted"); isOffensive.parameters.append({0, "isOffensive"}); state.m_signals = { {"warStarted", isOffensive}, }; democracy.m_name = "Democracy"; democracy.m_super = &state; democracy.m_properties = { {"reigningParty", {0,"reigningParty"}}, }; democracy.m_methods = { {"elect", {0, "elect"}}, }; democracy.m_signals = { {"lawAdopted", {"lawAdopted"}}, }; copenhagen.m_super = &city; christiania.m_super = &city; ottomanEmpire.m_name = "OttomanEmpire"; ottomanEmpire.m_super = &state; ottomanEmpire.m_methods = { {"capital", {0, "capital"}}, // Capital for year, overrides property capital. }; ottomanEmpire.m_valueAssignments = { {&state.m_properties["name"], 0, &ottomanEmpireNameNode}, {&state.m_properties["language"], 0, &ottomanEmpireLangNode} }; denmark.m_name = "Denmark"; denmark.m_super = &democracy; } void TestIR::testBasics() { QCOMPARE(city.name(), QStringLiteral("City")); QVERIFY(city.property("name")); QCOMPARE(city.property("name")->name, QStringLiteral("name")); QVERIFY(city.property("postCode")); QVERIFY(city.property("postCode") == city.property("postCode")); // Check that no copying happens QVERIFY(!city.property("capital")); QVERIFY(!city.property("visit")); QVERIFY(city.method("visit")); QCOMPARE(city.method("visit")->name, QStringLiteral("visit")); QVERIFY(city.method("visit") == city.method("visit")); // Check that no copying happens QCOMPARE(state.name(), QStringLiteral("State")); QVERIFY(state.property("name")); QCOMPARE(state.property("name")->name, QStringLiteral("name")); QVERIFY(state.property("language")); QVERIFY(state.property("capital")); QCOMPARE(state.property("capital")->type, &city); QCOMPARE(state.property("capital")->type->name(), QStringLiteral("City")); QVERIFY(!state.property("reigningParty")); QVERIFY(!state.property("postCode")); QVERIFY(state.method("visit")); QVERIFY(state.method("visit") != city.method("visit")); QVERIFY(state.signal("warStarted")); QVERIFY(state.signal("warStarted") == state.signal("warStarted")); // Check that no copying happens QCOMPARE(state.signal("warStarted")->name, QStringLiteral("warStarted")); QCOMPARE(state.signal("warStarted")->parameters[0].name, QStringLiteral("isOffensive")); QCOMPARE(democracy.name(), QStringLiteral("Democracy")); QVERIFY(democracy.property("name")); QCOMPARE(democracy.property("name")->name, QStringLiteral("name")); QVERIFY(democracy.property("language")); QVERIFY(democracy.property("capital")); QCOMPARE(democracy.property("capital")->type, &city); QCOMPARE(democracy.property("capital")->type->name(), QStringLiteral("City")); QVERIFY(democracy.property("reigningParty")); QVERIFY(!democracy.property("postCode")); QCOMPARE(ottomanEmpire.name(), QStringLiteral("OttomanEmpire")); QVERIFY(ottomanEmpire.property("name")); QVERIFY(!ottomanEmpire.property("reigningParty")); QVERIFY(!ottomanEmpire.property("postCode")); QCOMPARE(ottomanEmpire.valueAssignments().count(), 2); QCOMPARE(ottomanEmpire.valueAssignments()[0].property, &state.m_properties["name"]); QCOMPARE(reinterpret_cast( ottomanEmpire.valueAssignments()[0].jsValue)->value.toString(), QStringLiteral("Osmanlı İmparatorluğu")); } void TestIR::testAdd() { ValueAssignment *denmarkNameAssignment = denmark.addValueAssignment(); denmarkNameAssignment->property = &state.m_properties["name"]; denmarkNameAssignment->jsValue = &denmarkNameNode; ValueAssignment *denmarkLanguageAssignment = denmark.addValueAssignment(); denmarkLanguageAssignment->property = &state.m_properties["language"]; denmarkLanguageAssignment->jsValue = &denmarkLangNode; ValueAssignment *denmarkCapitalAssignment = denmark.addValueAssignment(); denmarkCapitalAssignment->property = &state.m_properties["capital"]; denmarkCapitalAssignment->objectValue = &copenhagen; ValueAssignment *denmarkReigningPartyAssignment = denmark.addValueAssignment(); denmarkReigningPartyAssignment->property = &democracy.m_properties["reigningParty"]; denmarkReigningPartyAssignment->jsValue = &denmarkRPartyNode; Property *christianiaProperty = copenhagen.addProperty("christiania"); christianiaProperty->type = &city; ValueAssignment *christianiaAssignment = copenhagen.addValueAssignment(); christianiaAssignment->objectValue = &christiania; ValueAssignment *copenhagenNameAssignment = copenhagen.addValueAssignment(); copenhagenNameAssignment->property = &city.m_properties["name"]; copenhagenNameAssignment->jsValue = &copenhagenNameNode; Method *buyWeed = christiania.addMethod("buyWeed"); Signal *policeRaid = christiania.addSignal("policeRaid"); ValueAssignment *christianiaNameAssignment = christiania.addValueAssignment(); christianiaNameAssignment->property = &city.m_properties["name"]; christianiaNameAssignment->jsValue = &christianiaNameNode; ValueAssignment *christianiaPostCodeAssignment = christiania.addValueAssignment(); christianiaPostCodeAssignment->property = &city.m_properties["postCode"]; christianiaPostCodeAssignment->jsValue = &christianiaPostCodeNode; QVERIFY(denmark.property("capital")); QVERIFY(denmark.property("reigningParty")); QVERIFY(!denmark.property("postCode")); QCOMPARE(denmark.valueAssignments().count(), 4); QVERIFY(denmark.valueAssignments()[2].property); QVERIFY(denmark.valueAssignments()[2].property == denmark.valueAssignments()[2].property); QCOMPARE(denmark.valueAssignments()[3].property, &democracy.m_properties["reigningParty"]); QCOMPARE(reinterpret_cast( denmark.valueAssignments()[3].jsValue)->value.toString(), QStringLiteral("S-RV")); QVERIFY(copenhagen.property("name")); QVERIFY(copenhagen.property("christiania")); QCOMPARE(copenhagen.valueAssignments().count(), 2); QVERIFY(christiania.method("visit")); QVERIFY(christiania.method("buyWeed")); QCOMPARE(christiania.method("buyWeed")->name, QStringLiteral("buyWeed")); QVERIFY(christiania.method("buyWeed") == buyWeed); // Check that no copying happens QVERIFY(christiania.signal("policeRaid")); QCOMPARE(christiania.signal("policeRaid")->name, QStringLiteral("policeRaid")); QVERIFY(christiania.signal("policeRaid") == policeRaid); // Check that no copying happens } class TestVisitor : public Visitor { public: TestVisitor() : Visitor() , objectsVisited(0) , propertiesVisited(0) , methodsVisited(0) , signalsVisited(0) , currentDepth(0) , valueAssignmentsVisited(0) , bindingAssignmentsVisited(0) , lastValueAssigned(0) {} virtual void visit(Object *object) { currentDepth++; objectsVisited++; } virtual void visit(ValueAssignment *valueAssignment) { currentDepth++; valueAssignmentsVisited++; lastValueAssigned = valueAssignment->jsValue; } virtual void visit(BindingAssignment *bindingAssignment) { currentDepth++; bindingAssignmentsVisited++; } virtual void endVisit(Object *object) { currentDepth--; } virtual void endVisit(ValueAssignment *valueAssignment) { currentDepth--; } virtual void endVisit(BindingAssignment *bindingAssignment) { currentDepth--; } int objectsVisited; int propertiesVisited; int methodsVisited; int signalsVisited; int valueAssignmentsVisited; int bindingAssignmentsVisited; int currentDepth; QString lastPropertyVisited; QQmlJS::AST::ExpressionNode *lastValueAssigned; }; void TestIR::testVisitorAPI() { QSKIP("Needs propertydef to be added to succeed."); TestVisitor visitor; copenhagen.accept(&visitor); QCOMPARE(visitor.currentDepth, 0); QCOMPARE(visitor.objectsVisited, 2); QCOMPARE(visitor.propertiesVisited, 1); QCOMPARE(visitor.methodsVisited, 1); QCOMPARE(visitor.signalsVisited, 1); QCOMPARE(visitor.valueAssignmentsVisited, 3); QCOMPARE(visitor.bindingAssignmentsVisited, 0); QCOMPARE(visitor.lastPropertyVisited, QStringLiteral("christiania")); QCOMPARE(visitor.lastValueAssigned->kind, (int)QQmlJS::AST::Node::Kind_StringLiteral); QQmlJS::AST::StringLiteral* lastValueAssigned = QQmlJS::AST::cast(visitor.lastValueAssigned); if (lastValueAssigned) QCOMPARE(lastValueAssigned->value.toString(), QStringLiteral("København")); } } // namespace IR } // namespace QMLJSc QTEST_MAIN(QmlJSc::IR::TestIR) #include "testir.moc" diff --git a/tests/auto/qmljsc/testprettygeneratorpass.cpp b/tests/auto/qmljsc/testprettygeneratorpass.cpp index b230de2..556c20c 100644 --- a/tests/auto/qmljsc/testprettygeneratorpass.cpp +++ b/tests/auto/qmljsc/testprettygeneratorpass.cpp @@ -1,150 +1,150 @@ /* * Qml.js Compiler - a QML to JS compiler bringing QML's power to the web. * * Copyright (C) 2015 Jan Marker * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #include #include #include #include #include "../../../src/qmljsc/ir/objecttree.h" #include "../../../src/qmljsc/compiler.h" #include "../../../src/qmljsc/compilerpasses/prettygeneratorpass.h" template class TestNodeFile : public QmlJSc::IR::File { public: TestNodeFile(TestedVisitorNodeType& testedNode) : m_testedNode(testedNode) { } virtual void accept(QmlJSc::IR::Visitor* visitor) override { m_testedNode.accept(visitor); } private: TestedVisitorNodeType& m_testedNode; }; class TestPrettyGeneratorPass : public QObject { Q_OBJECT private: void initBasicTypes(); QString readTestFileContent(const char* fileName); QmlJSc::PrettyGeneratorPass* m_prettyGeneratorPass = Q_NULLPTR; QString m_result; - QmlJSc::IR::LibraryClass* m_qtObjectType = Q_NULLPTR; + QmlJSc::IR::Type* m_qtObjectType = Q_NULLPTR; private slots: void setResult(QString); private slots: void initTestCase(); void init(); void emitsFinishedSignal(); void visitFile(); }; void TestPrettyGeneratorPass::setResult(QString result) { if (!m_result.isEmpty()) { QFAIL("finished emitted multiple times"); } else { m_result = result; } } void TestPrettyGeneratorPass::initTestCase() { initBasicTypes(); } void TestPrettyGeneratorPass::initBasicTypes() { QmlJSc::IR::Type* stringType = new QmlJSc::IR::Type(); stringType->setName("string"); - m_qtObjectType = new QmlJSc::IR::LibraryClass(); + m_qtObjectType = new QmlJSc::IR::Type(); m_qtObjectType->setName("QtObject"); QmlJSc::IR::Property *p = m_qtObjectType->addProperty("objectName"); p->type = stringType; } QString TestPrettyGeneratorPass::readTestFileContent(const char *fileName) { QFile testFile( QString(":/test/%1").arg(fileName) ); Q_ASSERT(testFile.open(QFile::ReadOnly)); QTextStream input(&testFile); return input.readAll(); } void TestPrettyGeneratorPass::init() { if (m_prettyGeneratorPass) { disconnect(m_prettyGeneratorPass, SIGNAL(finished(QString)), this, SLOT(setResult(QString))); delete m_prettyGeneratorPass; } m_prettyGeneratorPass = new QmlJSc::PrettyGeneratorPass(); m_result.clear(); connect(m_prettyGeneratorPass, SIGNAL(finished(QString)), this, SLOT(setResult(QString))); } void TestPrettyGeneratorPass::emitsFinishedSignal() { // Setup QmlJSc::IR::File file; file.setRootObject(new QmlJSc::IR::Object); file.rootObject()->setSuper(m_qtObjectType); TestNodeFile testNodeFile(file); QSignalSpy finishedSpy(m_prettyGeneratorPass, SIGNAL(finished(QString))); // Do m_prettyGeneratorPass->process(&testNodeFile); // Verify QCOMPARE(finishedSpy.count(), 1); } void TestPrettyGeneratorPass::visitFile() { // Setup QString minimalFileJs = readTestFileContent("minimal.qml.js"); QmlJSc::IR::File file; file.setRootObject(new QmlJSc::IR::Object); file.rootObject()->setSuper(m_qtObjectType); TestNodeFile testNodeFile(file); // Do m_prettyGeneratorPass->process(&testNodeFile); // Verify QCOMPARE(m_result, minimalFileJs); } QTEST_MAIN(TestPrettyGeneratorPass) #include "testprettygeneratorpass.moc" \ No newline at end of file