1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qqmlscript_p.h"
44 #include "parser/qqmljsengine_p.h"
45 #include "parser/qqmljsparser_p.h"
46 #include "parser/qqmljslexer_p.h"
47 #include "parser/qqmljsmemorypool_p.h"
48 #include "parser/qqmljsastvisitor_p.h"
49 #include "parser/qqmljsast_p.h"
50 #include <private/qqmlrewrite_p.h>
53 #include <QStringList>
54 #include <QCoreApplication>
59 using namespace QQmlJS;
60 using namespace QQmlScript;
65 QQmlScript::Object::Object()
66 : type(-1), idIndex(-1), metatype(0), synthCache(0), defaultProperty(0), parserStatusCast(-1),
67 componentCompileState(0), nextAliasingObject(0), nextIdObject(0)
69 // initialize the members in the meta object
70 extObject.d.superdata = 0;
71 extObject.d.stringdata = 0;
73 extObject.d.extradata = 0;
76 QQmlScript::Object::~Object()
78 if (synthCache) synthCache->release();
81 void Object::setBindingBit(int b)
83 while (bindingBitmask.size() < 4 * (1 + b / 32))
84 bindingBitmask.append(char(0));
86 quint32 *bits = (quint32 *)bindingBitmask.data();
87 bits[b / 32] |= (1 << (b % 32));
90 const QMetaObject *Object::metaObject() const
92 if (!metadata.isEmpty() && metatype)
98 QQmlScript::Property *Object::getDefaultProperty()
100 if (!defaultProperty) {
101 defaultProperty = pool()->New<Property>();
102 defaultProperty->parent = this;
104 return defaultProperty;
107 void QQmlScript::Object::addValueProperty(Property *p)
109 valueProperties.append(p);
112 void QQmlScript::Object::addSignalProperty(Property *p)
114 signalProperties.append(p);
117 void QQmlScript::Object::addAttachedProperty(Property *p)
119 attachedProperties.append(p);
122 void QQmlScript::Object::addGroupedProperty(Property *p)
124 groupedProperties.append(p);
127 void QQmlScript::Object::addValueTypeProperty(Property *p)
129 valueTypeProperties.append(p);
132 void QQmlScript::Object::addScriptStringProperty(Property *p)
134 scriptStringProperties.append(p);
137 // This lookup is optimized for missing, and having to create a new property.
138 Property *QQmlScript::Object::getProperty(const QHashedStringRef &name, bool create)
141 quint32 h = name.hash();
142 if (propertiesHashField.testAndSet(h)) {
143 for (Property *p = properties.first(); p; p = properties.next(p)) {
144 if (p->name() == name)
149 Property *property = pool()->New<Property>();
150 property->parent = this;
151 property->_name = name;
152 property->isDefault = false;
153 properties.prepend(property);
156 for (Property *p = properties.first(); p; p = properties.next(p)) {
157 if (p->name() == name)
165 Property *QQmlScript::Object::getProperty(const QStringRef &name, bool create)
167 return getProperty(QHashedStringRef(name), create);
170 Property *QQmlScript::Object::getProperty(const QString &name, bool create)
172 for (Property *p = properties.first(); p; p = properties.next(p)) {
173 if (p->name() == name)
178 Property *property = pool()->New<Property>();
179 property->parent = this;
180 property->_name = QStringRef(pool()->NewString(name));
181 propertiesHashField.testAndSet(property->_name.hash());
182 property->isDefault = false;
183 properties.prepend(property);
190 QQmlScript::Object::DynamicProperty::DynamicProperty()
191 : isDefaultProperty(false), isReadOnly(false), type(Variant), defaultValue(0), nextProperty(0),
192 resolvedCustomTypeName(0)
196 QQmlScript::Object::DynamicSignal::DynamicSignal()
201 // Returns length in utf8 bytes
202 int QQmlScript::Object::DynamicSignal::parameterTypesLength() const
205 for (int ii = 0; ii < parameterTypes.count(); ++ii)
206 rv += parameterTypes.at(ii).length();
210 // Returns length in utf8 bytes
211 int QQmlScript::Object::DynamicSignal::parameterNamesLength() const
214 for (int ii = 0; ii < parameterNames.count(); ++ii)
215 rv += parameterNames.at(ii).utf8length();
219 QQmlScript::Object::DynamicSlot::DynamicSlot()
224 int QQmlScript::Object::DynamicSlot::parameterNamesLength() const
227 for (int ii = 0; ii < parameterNames.count(); ++ii)
228 rv += parameterNames.at(ii).length();
232 QQmlScript::Property::Property()
233 : parent(0), type(0), index(-1), value(0), isDefault(true), isDeferred(false),
234 isValueTypeSubProperty(false), isAlias(false), isReadOnlyDeclaration(false),
235 scriptStringScope(-1), nextMainProperty(0), nextProperty(0)
239 QQmlScript::Object *QQmlScript::Property::getValue(const LocationSpan &l)
241 if (!value) { value = pool()->New<Object>(); value->location = l; }
245 void QQmlScript::Property::addValue(Value *v)
250 void QQmlScript::Property::addOnValue(Value *v)
255 bool QQmlScript::Property::isEmpty() const
257 return !value && values.isEmpty() && onValues.isEmpty();
260 QQmlScript::Value::Value()
261 : type(Unknown), object(0), bindingReference(0), nextValue(0)
265 QQmlScript::Variant::Variant()
270 QQmlScript::Variant::Variant(const Variant &o)
271 : t(o.t), d(o.d), asWritten(o.asWritten)
275 QQmlScript::Variant::Variant(bool v)
280 QQmlScript::Variant::Variant(double v, const QStringRef &asWritten)
281 : t(Number), d(v), asWritten(asWritten)
285 QQmlScript::Variant::Variant(QQmlJS::AST::StringLiteral *v)
290 QQmlScript::Variant::Variant(const QStringRef &asWritten, QQmlJS::AST::Node *n)
291 : t(Script), n(n), asWritten(asWritten)
295 QQmlScript::Variant &QQmlScript::Variant::operator=(const Variant &o)
299 asWritten = o.asWritten;
303 QQmlScript::Variant::Type QQmlScript::Variant::type() const
308 bool QQmlScript::Variant::asBoolean() const
313 QString QQmlScript::Variant::asString() const
316 return l->value.toString();
318 return asWritten.toString();
322 double QQmlScript::Variant::asNumber() const
327 //reverse of Lexer::singleEscape()
328 QString escapedString(const QString &string)
330 QString tmp = QLatin1String("\"");
331 for (int i = 0; i < string.length(); ++i) {
332 const QChar &c = string.at(i);
333 switch(c.unicode()) {
335 tmp += QLatin1String("\\b");
338 tmp += QLatin1String("\\t");
341 tmp += QLatin1String("\\n");
344 tmp += QLatin1String("\\v");
347 tmp += QLatin1String("\\f");
350 tmp += QLatin1String("\\r");
353 tmp += QLatin1String("\\\"");
356 tmp += QLatin1String("\\\'");
359 tmp += QLatin1String("\\\\");
366 tmp += QLatin1Char('\"');
370 QString QQmlScript::Variant::asScript() const
377 return b?QLatin1String("true"):QLatin1String("false");
379 if (asWritten.isEmpty())
380 return QString::number(d);
382 return asWritten.toString();
384 return escapedString(asString());
386 if (AST::IdentifierExpression *i = AST::cast<AST::IdentifierExpression *>(n)) {
387 return i->name.toString();
389 return asWritten.toString();
393 QQmlJS::AST::Node *QQmlScript::Variant::asAST() const
395 if (type() == Script)
401 bool QQmlScript::Variant::isStringList() const
406 if (type() != Script || !n)
409 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
413 AST::ElementList *elements = array->elements;
417 if (!AST::cast<AST::StringLiteral *>(elements->expression))
420 elements = elements->next;
426 QStringList QQmlScript::Variant::asStringList() const
434 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
438 AST::ElementList *elements = array->elements;
441 AST::StringLiteral *string = AST::cast<AST::StringLiteral *>(elements->expression);
443 return QStringList();
444 rv.append(string->value.toString());
446 elements = elements->next;
453 // Actual parser classes
455 void QQmlScript::Import::extractVersion(int *maj, int *min) const
457 *maj = -1; *min = -1;
459 if (!version.isEmpty()) {
460 int dot = version.indexOf(QLatin1Char('.'));
462 *maj = version.toInt();
465 *maj = version.left(dot).toInt();
466 *min = version.mid(dot+1).toInt();
473 class ProcessAST: protected AST::Visitor
476 State() : object(0), property(0) {}
477 State(QQmlScript::Object *o) : object(o), property(0) {}
478 State(QQmlScript::Object *o, Property *p) : object(o), property(p) {}
480 QQmlScript::Object *object;
484 struct StateStack : public QStack<State>
486 void pushObject(QQmlScript::Object *obj)
491 void pushProperty(const QString &name, const LocationSpan &location)
493 const State &state = top();
494 if (state.property) {
495 State s(state.property->getValue(location),
496 state.property->getValue(location)->getProperty(name));
497 s.property->location = location;
500 State s(state.object, state.object->getProperty(name));
502 s.property->location = location;
507 void pushProperty(const QStringRef &name, const LocationSpan &location)
509 const State &state = top();
510 if (state.property) {
511 State s(state.property->getValue(location),
512 state.property->getValue(location)->getProperty(name));
513 s.property->location = location;
516 State s(state.object, state.object->getProperty(name));
518 s.property->location = location;
525 ProcessAST(QQmlScript::Parser *parser);
526 virtual ~ProcessAST();
528 void operator()(const QString &code, AST::Node *node);
532 QQmlScript::Object *defineObjectBinding(AST::UiQualifiedId *propertyName, bool onAssignment,
533 const QString &objectType,
534 AST::SourceLocation typeLocation,
535 LocationSpan location,
536 AST::UiObjectInitializer *initializer = 0);
538 QQmlScript::Variant getVariant(AST::Statement *stmt);
539 QQmlScript::Variant getVariant(AST::ExpressionNode *expr);
541 LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
542 LocationSpan location(AST::UiQualifiedId *);
544 using AST::Visitor::visit;
545 using AST::Visitor::endVisit;
547 virtual bool visit(AST::UiProgram *node);
548 virtual bool visit(AST::UiImport *node);
549 virtual bool visit(AST::UiObjectDefinition *node);
550 virtual bool visit(AST::UiPublicMember *node);
551 virtual bool visit(AST::UiObjectBinding *node);
553 virtual bool visit(AST::UiScriptBinding *node);
554 virtual bool visit(AST::UiArrayBinding *node);
555 virtual bool visit(AST::UiSourceElement *node);
557 void accept(AST::Node *node);
559 QString asString(AST::UiQualifiedId *node) const;
561 const State state() const;
562 QQmlScript::Object *currentObject() const;
563 Property *currentProperty() const;
565 QString qualifiedNameId() const;
567 QString textAt(const AST::SourceLocation &loc) const
568 { return _contents->mid(loc.offset, loc.length); }
570 QStringRef textRefAt(const AST::SourceLocation &loc) const
571 { return QStringRef(_contents, loc.offset, loc.length); }
573 QString textAt(const AST::SourceLocation &first,
574 const AST::SourceLocation &last) const
575 { return _contents->mid(first.offset, last.offset + last.length - first.offset); }
577 QStringRef textRefAt(const AST::SourceLocation &first,
578 const AST::SourceLocation &last) const
579 { return QStringRef(_contents, first.offset, last.offset + last.length - first.offset); }
581 QString asString(AST::ExpressionNode *expr)
586 return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
589 QStringRef asStringRef(AST::ExpressionNode *expr)
594 return textRefAt(expr->firstSourceLocation(), expr->lastSourceLocation());
597 QString asString(AST::Statement *stmt)
602 QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
603 s += QLatin1Char('\n');
607 QStringRef asStringRef(AST::Statement *stmt)
612 return textRefAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
616 QQmlScript::Parser *_parser;
617 StateStack _stateStack;
619 const QString *_contents;
622 ProcessAST::ProcessAST(QQmlScript::Parser *parser)
627 ProcessAST::~ProcessAST()
631 void ProcessAST::operator()(const QString &code, AST::Node *node)
637 void ProcessAST::accept(AST::Node *node)
639 AST::Node::acceptChild(node, this);
642 const ProcessAST::State ProcessAST::state() const
644 if (_stateStack.isEmpty())
647 return _stateStack.back();
650 QQmlScript::Object *ProcessAST::currentObject() const
652 return state().object;
655 Property *ProcessAST::currentProperty() const
657 return state().property;
660 QString ProcessAST::qualifiedNameId() const
662 return _scope.join(QLatin1String("/"));
665 QString ProcessAST::asString(AST::UiQualifiedId *node) const
669 for (AST::UiQualifiedId *it = node; it; it = it->next) {
670 s.append(it->name.toString());
673 s.append(QLatin1Char('.'));
680 ProcessAST::defineObjectBinding(AST::UiQualifiedId *propertyName,
682 const QString &objectType,
683 AST::SourceLocation typeLocation,
684 LocationSpan location,
685 AST::UiObjectInitializer *initializer)
687 int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
689 // With no preceding qualification, first char is at (-1 + 1) == 0
690 bool isType = !objectType.isEmpty() && objectType.at(lastTypeDot+1).isUpper();
692 int propertyCount = 0;
693 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
695 _stateStack.pushProperty(name->name,
696 this->location(name));
699 if (!onAssignment && propertyCount && currentProperty() && !currentProperty()->values.isEmpty()) {
701 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
702 error.setLine(this->location(propertyName).start.line);
703 error.setColumn(this->location(propertyName).start.column);
704 _parser->_errors << error;
710 // Is the identifier qualified by a namespace?
711 int namespaceLength = 0;
712 if (lastTypeDot > 0) {
713 const QString qualifier(objectType.left(lastTypeDot));
715 for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
716 const QQmlScript::Import &import = _parser->_imports.at(ii);
717 if (import.qualifier == qualifier) {
718 // The qualifier is a namespace - expect a type here
719 namespaceLength = qualifier.length() + 1;
725 if (propertyCount || !currentObject() || namespaceLength) {
727 error.setDescription(QCoreApplication::translate("QQmlParser","Expected type name"));
728 error.setLine(typeLocation.startLine);
729 error.setColumn(typeLocation.startColumn + namespaceLength);
730 _parser->_errors << error;
734 LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
736 loc = ProcessAST::location(propertyName);
738 _stateStack.pushProperty(objectType, loc);
747 QString resolvableObjectType = objectType;
748 if (lastTypeDot >= 0)
749 resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
751 QQmlScript::Object *obj = _parser->_pool.New<QQmlScript::Object>();
753 QQmlScript::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
754 obj->type = typeRef->id;
756 typeRef->refObjects.append(obj);
758 // XXX this doesn't do anything (_scope never builds up)
759 _scope.append(resolvableObjectType);
760 obj->typeName = qualifiedNameId();
763 obj->location = location;
766 Property *prop = currentProperty();
767 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
769 v->location = obj->location;
775 while (propertyCount--)
780 if (! _parser->tree()) {
781 _parser->setTree(obj);
783 const State state = _stateStack.top();
784 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
786 v->location = obj->location;
787 if (state.property) {
788 state.property->addValue(v);
790 Property *defaultProp = state.object->getDefaultProperty();
791 if (defaultProp->location.start.line == -1) {
792 defaultProp->location = v->location;
793 defaultProp->location.end = defaultProp->location.start;
794 defaultProp->location.range.length = 0;
796 defaultProp->addValue(v);
801 _stateStack.pushObject(obj);
809 LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
811 return location(id->identifierToken, id->identifierToken);
814 LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
817 rv.start.line = start.startLine;
818 rv.start.column = start.startColumn;
819 rv.end.line = end.startLine;
820 rv.end.column = end.startColumn + end.length - 1;
821 rv.range.offset = start.offset;
822 rv.range.length = end.offset + end.length - start.offset;
826 // UiProgram: UiImportListOpt UiObjectMemberList ;
827 bool ProcessAST::visit(AST::UiProgram *node)
829 accept(node->imports);
830 accept(node->members->member);
834 // UiImport: T_IMPORT T_STRING_LITERAL ;
835 bool ProcessAST::visit(AST::UiImport *node)
838 QQmlScript::Import import;
840 if (!node->fileName.isNull()) {
841 uri = node->fileName.toString();
843 if (uri.endsWith(QLatin1String(".js"))) {
844 import.type = QQmlScript::Import::Script;
846 import.type = QQmlScript::Import::File;
849 import.type = QQmlScript::Import::Library;
850 uri = asString(node->importUri);
853 AST::SourceLocation startLoc = node->importToken;
854 AST::SourceLocation endLoc = node->semicolonToken;
857 if (!node->importId.isNull()) {
858 import.qualifier = node->importId.toString();
859 if (!import.qualifier.at(0).isUpper()) {
861 error.setDescription(QCoreApplication::translate("QQmlParser","Invalid import qualifier ID"));
862 error.setLine(node->importIdToken.startLine);
863 error.setColumn(node->importIdToken.startColumn);
864 _parser->_errors << error;
867 if (import.qualifier == QLatin1String("Qt")) {
869 error.setDescription(QCoreApplication::translate("QQmlParser","Reserved name \"Qt\" cannot be used as an qualifier"));
870 error.setLine(node->importIdToken.startLine);
871 error.setColumn(node->importIdToken.startColumn);
872 _parser->_errors << error;
876 // Check for script qualifier clashes
877 bool isScript = import.type == QQmlScript::Import::Script;
878 for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
879 const QQmlScript::Import &other = _parser->_imports.at(ii);
880 bool otherIsScript = other.type == QQmlScript::Import::Script;
882 if ((isScript || otherIsScript) && import.qualifier == other.qualifier) {
884 error.setDescription(QCoreApplication::translate("QQmlParser","Script import qualifiers must be unique."));
885 error.setLine(node->importIdToken.startLine);
886 error.setColumn(node->importIdToken.startColumn);
887 _parser->_errors << error;
892 } else if (import.type == QQmlScript::Import::Script) {
894 error.setDescription(QCoreApplication::translate("QQmlParser","Script import requires a qualifier"));
895 error.setLine(node->fileNameToken.startLine);
896 error.setColumn(node->fileNameToken.startColumn);
897 _parser->_errors << error;
901 if (node->versionToken.isValid()) {
902 import.version = textAt(node->versionToken);
903 } else if (import.type == QQmlScript::Import::Library) {
905 error.setDescription(QCoreApplication::translate("QQmlParser","Library import requires a version"));
906 error.setLine(node->importIdToken.startLine);
907 error.setColumn(node->importIdToken.startColumn);
908 _parser->_errors << error;
913 import.location = location(startLoc, endLoc);
916 _parser->_imports << import;
921 bool ProcessAST::visit(AST::UiPublicMember *node)
923 static const struct TypeNameToType {
926 Object::DynamicProperty::Type type;
929 } propTypeNameToTypes[] = {
930 { "int", strlen("int"), Object::DynamicProperty::Int, "int", strlen("int") },
931 { "bool", strlen("bool"), Object::DynamicProperty::Bool, "bool", strlen("bool") },
932 { "double", strlen("double"), Object::DynamicProperty::Real, "double", strlen("double") },
933 { "real", strlen("real"), Object::DynamicProperty::Real, "double", strlen("double") },
934 { "string", strlen("string"), Object::DynamicProperty::String, "QString", strlen("QString") },
935 { "url", strlen("url"), Object::DynamicProperty::Url, "QUrl", strlen("QUrl") },
936 { "color", strlen("color"), Object::DynamicProperty::Color, "QColor", strlen("QColor") },
937 // Internally QTime, QDate and QDateTime are all supported.
938 // To be more consistent with JavaScript we expose only
939 // QDateTime as it matches closely with the Date JS type.
940 // We also call it "date" to match.
941 // { "time", strlen("time"), Object::DynamicProperty::Time, "QTime", strlen("QTime") },
942 // { "date", strlen("date"), Object::DynamicProperty::Date, "QDate", strlen("QDate") },
943 { "date", strlen("date"), Object::DynamicProperty::DateTime, "QDateTime", strlen("QDateTime") },
944 { "variant", strlen("variant"), Object::DynamicProperty::Variant, "QVariant", strlen("QVariant") },
945 { "var", strlen("var"), Object::DynamicProperty::Var, "QVariant", strlen("QVariant") }
947 static const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
948 sizeof(propTypeNameToTypes[0]);
950 if(node->type == AST::UiPublicMember::Signal) {
951 Object::DynamicSignal *signal = _parser->_pool.New<Object::DynamicSignal>();
952 signal->name = node->name;
954 AST::UiParameterList *p = node->parameters;
956 while (p) { paramLength++; p = p->next; }
957 p = node->parameters;
960 signal->parameterTypes = _parser->_pool.NewRawList<QHashedCStringRef>(paramLength);
961 signal->parameterNames = _parser->_pool.NewRawList<QHashedStringRef>(paramLength);
966 const QStringRef &memberType = p->type;
968 const TypeNameToType *type = 0;
969 for(int typeIndex = 0; typeIndex < propTypeNameToTypesCount; ++typeIndex) {
970 const TypeNameToType *t = propTypeNameToTypes + typeIndex;
971 if (t->nameLength == memberType.length() &&
972 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
980 error.setDescription(QCoreApplication::translate("QQmlParser","Expected parameter type"));
981 error.setLine(node->typeToken.startLine);
982 error.setColumn(node->typeToken.startColumn);
983 _parser->_errors << error;
987 signal->parameterTypes[index] = QHashedCStringRef(type->qtName, type->qtNameLength);
988 signal->parameterNames[index] = QHashedStringRef(p->name);
993 signal->location = location(node->typeToken, node->semicolonToken);
994 _stateStack.top().object->dynamicSignals.append(signal);
996 const QStringRef &memberType = node->memberType;
997 const QStringRef &name = node->name;
999 bool typeFound = false;
1000 Object::DynamicProperty::Type type;
1002 if ((unsigned)memberType.length() == strlen("alias") &&
1003 QHashedString::compare(memberType.constData(), "alias", strlen("alias"))) {
1004 type = Object::DynamicProperty::Alias;
1008 for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
1009 const TypeNameToType *t = propTypeNameToTypes + ii;
1010 if (t->nameLength == memberType.length() &&
1011 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
1017 if (!typeFound && memberType.at(0).isUpper()) {
1018 const QStringRef &typeModifier = node->typeModifier;
1020 if (typeModifier.isEmpty()) {
1021 type = Object::DynamicProperty::Custom;
1022 } else if((unsigned)typeModifier.length() == strlen("list") &&
1023 QHashedString::compare(typeModifier.constData(), "list", strlen("list"))) {
1024 type = Object::DynamicProperty::CustomList;
1027 error.setDescription(QCoreApplication::translate("QQmlParser","Invalid property type modifier"));
1028 error.setLine(node->typeModifierToken.startLine);
1029 error.setColumn(node->typeModifierToken.startColumn);
1030 _parser->_errors << error;
1034 } else if (!node->typeModifier.isNull()) {
1036 error.setDescription(QCoreApplication::translate("QQmlParser","Unexpected property type modifier"));
1037 error.setLine(node->typeModifierToken.startLine);
1038 error.setColumn(node->typeModifierToken.startColumn);
1039 _parser->_errors << error;
1045 error.setDescription(QCoreApplication::translate("QQmlParser","Expected property type"));
1046 error.setLine(node->typeToken.startLine);
1047 error.setColumn(node->typeToken.startColumn);
1048 _parser->_errors << error;
1052 Object::DynamicProperty *property = _parser->_pool.New<Object::DynamicProperty>();
1053 property->isDefaultProperty = node->isDefaultMember;
1054 property->isReadOnly = node->isReadonlyMember;
1055 property->type = type;
1056 property->nameLocation.line = node->identifierToken.startLine;
1057 property->nameLocation.column = node->identifierToken.startColumn;
1058 if (type >= Object::DynamicProperty::Custom) {
1059 QQmlScript::TypeReference *typeRef =
1060 _parser->findOrCreateType(memberType.toString());
1061 typeRef->refObjects.append(_stateStack.top().object);
1062 property->customType = memberType;
1065 property->name = QHashedStringRef(name);
1066 property->location = location(node->firstSourceLocation(),
1067 node->lastSourceLocation());
1069 if (node->statement) { // default value
1070 property->defaultValue = _parser->_pool.New<Property>();
1071 property->defaultValue->parent = _stateStack.top().object;
1072 property->defaultValue->location =
1073 location(node->statement->firstSourceLocation(),
1074 node->statement->lastSourceLocation());
1075 QQmlScript::Value *value = _parser->_pool.New<QQmlScript::Value>();
1076 value->location = location(node->statement->firstSourceLocation(),
1077 node->statement->lastSourceLocation());
1078 value->value = getVariant(node->statement);
1079 property->defaultValue->values.append(value);
1082 _stateStack.top().object->dynamicProperties.append(property);
1084 // process QML-like initializers (e.g. property Object o: Object {})
1085 accept(node->binding);
1092 // UiObjectMember: UiQualifiedId UiObjectInitializer ;
1093 bool ProcessAST::visit(AST::UiObjectDefinition *node)
1095 LocationSpan l = location(node->firstSourceLocation(),
1096 node->lastSourceLocation());
1098 const QString objectType = asString(node->qualifiedTypeNameId);
1099 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1101 defineObjectBinding(/*propertyName = */ 0, false, objectType,
1102 typeLocation, l, node->initializer);
1108 // UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
1109 bool ProcessAST::visit(AST::UiObjectBinding *node)
1111 LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
1112 node->initializer->rbraceToken);
1114 const QString objectType = asString(node->qualifiedTypeNameId);
1115 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1117 defineObjectBinding(node->qualifiedId, node->hasOnToken, objectType,
1118 typeLocation, l, node->initializer);
1123 QQmlScript::Variant ProcessAST::getVariant(AST::Statement *stmt)
1126 if (AST::ExpressionStatement *exprStmt = AST::cast<AST::ExpressionStatement *>(stmt))
1127 return getVariant(exprStmt->expression);
1129 return QQmlScript::Variant(asStringRef(stmt), stmt);
1132 return QQmlScript::Variant();
1135 QQmlScript::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
1137 if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
1138 return QQmlScript::Variant(lit);
1139 } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
1140 return QQmlScript::Variant(true);
1141 } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
1142 return QQmlScript::Variant(false);
1143 } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
1144 return QQmlScript::Variant(lit->value, asStringRef(expr));
1147 if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
1148 if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
1149 return QQmlScript::Variant(-lit->value, asStringRef(expr));
1153 return QQmlScript::Variant(asStringRef(expr), expr);
1158 // UiObjectMember: UiQualifiedId T_COLON Statement ;
1159 bool ProcessAST::visit(AST::UiScriptBinding *node)
1161 int propertyCount = 0;
1162 AST::UiQualifiedId *propertyName = node->qualifiedId;
1163 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1165 _stateStack.pushProperty(name->name,
1169 Property *prop = currentProperty();
1171 if (!prop->values.isEmpty()) {
1173 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
1174 error.setLine(this->location(propertyName).start.line);
1175 error.setColumn(this->location(propertyName).start.column);
1176 _parser->_errors << error;
1180 QQmlScript::Variant primitive;
1182 if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
1183 primitive = getVariant(stmt->expression);
1184 } else { // do binding
1185 primitive = QQmlScript::Variant(asStringRef(node->statement), node->statement);
1188 prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
1189 prop->location.range.offset = node->qualifiedId->identifierToken.offset;
1190 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
1191 v->value = primitive;
1192 v->location = location(node->statement->firstSourceLocation(),
1193 node->statement->lastSourceLocation());
1197 while (propertyCount--)
1203 // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
1204 bool ProcessAST::visit(AST::UiArrayBinding *node)
1206 int propertyCount = 0;
1207 AST::UiQualifiedId *propertyName = node->qualifiedId;
1208 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1210 _stateStack.pushProperty(name->name,
1214 Property* prop = currentProperty();
1216 if (!prop->values.isEmpty()) {
1218 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
1219 error.setLine(this->location(propertyName).start.line);
1220 error.setColumn(this->location(propertyName).start.column);
1221 _parser->_errors << error;
1225 accept(node->members);
1227 // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
1228 prop->listValueRange.offset = node->lbracketToken.offset;
1229 prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
1231 while (propertyCount--)
1237 bool ProcessAST::visit(AST::UiSourceElement *node)
1239 QQmlScript::Object *obj = currentObject();
1241 if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
1243 Object::DynamicSlot *slot = _parser->_pool.New<Object::DynamicSlot>();
1244 slot->location = location(funDecl->identifierToken, funDecl->lastSourceLocation());
1246 AST::FormalParameterList *f = funDecl->formals;
1248 slot->parameterNames << f->name.toUtf8();
1252 AST::SourceLocation loc = funDecl->rparenToken;
1253 loc.offset = loc.end();
1254 loc.startColumn += 1;
1255 QString body = textAt(loc, funDecl->rbraceToken);
1256 slot->name = funDecl->name;
1258 obj->dynamicSlots.append(slot);
1262 error.setDescription(QCoreApplication::translate("QQmlParser","JavaScript declaration outside Script element"));
1263 error.setLine(node->firstSourceLocation().startLine);
1264 error.setColumn(node->firstSourceLocation().startColumn);
1265 _parser->_errors << error;
1270 } // end of anonymous namespace
1273 QQmlScript::Parser::Parser()
1279 QQmlScript::Parser::~Parser()
1284 namespace QQmlScript {
1285 class ParserJsASTData
1288 ParserJsASTData(const QString &filename)
1289 : filename(filename) {}
1296 bool QQmlScript::Parser::parse(const QByteArray &qmldata, const QUrl &url,
1297 const QString &urlString)
1301 if (urlString.isEmpty()) {
1302 _scriptFile = url.toString();
1304 // Q_ASSERT(urlString == url.toString());
1305 _scriptFile = urlString;
1308 QTextStream stream(qmldata, QIODevice::ReadOnly);
1309 #ifndef QT_NO_TEXTCODEC
1310 stream.setCodec("UTF-8");
1312 QString *code = _pool.NewString(stream.readAll());
1314 data = new QQmlScript::ParserJsASTData(_scriptFile);
1316 Lexer lexer(&data->engine);
1317 lexer.setCode(*code, /*line = */ 1);
1319 QQmlJS::Parser parser(&data->engine);
1321 if (! parser.parse() || !_errors.isEmpty()) {
1323 // Extract errors from the parser
1324 foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
1331 error.setDescription(m.message);
1332 error.setLine(m.loc.startLine);
1333 error.setColumn(m.loc.startColumn);
1339 if (_errors.isEmpty()) {
1340 ProcessAST process(this);
1341 process(*code, parser.ast());
1343 // Set the url for process errors
1344 for(int ii = 0; ii < _errors.count(); ++ii)
1345 _errors[ii].setUrl(url);
1348 return _errors.isEmpty();
1351 QList<QQmlScript::TypeReference*> QQmlScript::Parser::referencedTypes() const
1356 QQmlScript::Object *QQmlScript::Parser::tree() const
1361 QList<QQmlScript::Import> QQmlScript::Parser::imports() const
1366 QList<QQmlError> QQmlScript::Parser::errors() const
1371 static void replaceWithSpace(QString &str, int idx, int n)
1373 QChar *data = str.data() + idx;
1374 const QChar space(QLatin1Char(' '));
1375 for (int ii = 0; ii < n; ++ii)
1379 static QQmlScript::LocationSpan
1380 locationFromLexer(const QQmlJS::Lexer &lex, int startLine, int startColumn, int startOffset)
1382 QQmlScript::LocationSpan l;
1384 l.start.line = startLine; l.start.column = startColumn;
1385 l.end.line = lex.tokenEndLine(); l.end.column = lex.tokenEndColumn();
1386 l.range.offset = startOffset;
1387 l.range.length = lex.tokenOffset() + lex.tokenLength() - startOffset;
1393 Searches for ".pragma <value>" declarations within \a script. Currently supported pragmas
1397 QQmlScript::Object::ScriptBlock::Pragmas QQmlScript::Parser::extractPragmas(QString &script)
1399 QQmlScript::Object::ScriptBlock::Pragmas rv = QQmlScript::Object::ScriptBlock::None;
1401 const QString pragma(QLatin1String("pragma"));
1402 const QString library(QLatin1String("library"));
1405 l.setCode(script, 0);
1407 int token = l.lex();
1410 if (token != QQmlJSGrammar::T_DOT)
1413 int startOffset = l.tokenOffset();
1414 int startLine = l.tokenStartLine();
1418 if (token != QQmlJSGrammar::T_IDENTIFIER ||
1419 l.tokenStartLine() != startLine ||
1420 script.mid(l.tokenOffset(), l.tokenLength()) != pragma)
1425 if (token != QQmlJSGrammar::T_IDENTIFIER ||
1426 l.tokenStartLine() != startLine)
1429 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1430 int endOffset = l.tokenLength() + l.tokenOffset();
1433 if (l.tokenStartLine() == startLine)
1436 if (pragmaValue == library) {
1437 rv |= QQmlScript::Object::ScriptBlock::Shared;
1438 replaceWithSpace(script, startOffset, endOffset - startOffset);
1446 #define CHECK_LINE if (l.tokenStartLine() != startLine) return rv;
1447 #define CHECK_TOKEN(t) if (token != QQmlJSGrammar:: t) return rv;
1449 static const int uriTokens[] = {
1450 QQmlJSGrammar::T_IDENTIFIER,
1451 QQmlJSGrammar::T_PROPERTY,
1452 QQmlJSGrammar::T_SIGNAL,
1453 QQmlJSGrammar::T_READONLY,
1454 QQmlJSGrammar::T_ON,
1455 QQmlJSGrammar::T_BREAK,
1456 QQmlJSGrammar::T_CASE,
1457 QQmlJSGrammar::T_CATCH,
1458 QQmlJSGrammar::T_CONTINUE,
1459 QQmlJSGrammar::T_DEFAULT,
1460 QQmlJSGrammar::T_DELETE,
1461 QQmlJSGrammar::T_DO,
1462 QQmlJSGrammar::T_ELSE,
1463 QQmlJSGrammar::T_FALSE,
1464 QQmlJSGrammar::T_FINALLY,
1465 QQmlJSGrammar::T_FOR,
1466 QQmlJSGrammar::T_FUNCTION,
1467 QQmlJSGrammar::T_IF,
1468 QQmlJSGrammar::T_IN,
1469 QQmlJSGrammar::T_INSTANCEOF,
1470 QQmlJSGrammar::T_NEW,
1471 QQmlJSGrammar::T_NULL,
1472 QQmlJSGrammar::T_RETURN,
1473 QQmlJSGrammar::T_SWITCH,
1474 QQmlJSGrammar::T_THIS,
1475 QQmlJSGrammar::T_THROW,
1476 QQmlJSGrammar::T_TRUE,
1477 QQmlJSGrammar::T_TRY,
1478 QQmlJSGrammar::T_TYPEOF,
1479 QQmlJSGrammar::T_VAR,
1480 QQmlJSGrammar::T_VOID,
1481 QQmlJSGrammar::T_WHILE,
1482 QQmlJSGrammar::T_CONST,
1483 QQmlJSGrammar::T_DEBUGGER,
1484 QQmlJSGrammar::T_RESERVED_WORD,
1485 QQmlJSGrammar::T_WITH,
1487 QQmlJSGrammar::EOF_SYMBOL
1489 static inline bool isUriToken(int token)
1491 const int *current = uriTokens;
1492 while (*current != QQmlJSGrammar::EOF_SYMBOL) {
1493 if (*current == token)
1500 QQmlScript::Parser::JavaScriptMetaData QQmlScript::Parser::extractMetaData(QString &script)
1502 JavaScriptMetaData rv;
1504 QQmlScript::Object::ScriptBlock::Pragmas &pragmas = rv.pragmas;
1506 const QString pragma(QLatin1String("pragma"));
1507 const QString js(QLatin1String(".js"));
1508 const QString library(QLatin1String("library"));
1511 l.setCode(script, 0);
1513 int token = l.lex();
1516 if (token != QQmlJSGrammar::T_DOT)
1519 int startOffset = l.tokenOffset();
1520 int startLine = l.tokenStartLine();
1521 int startColumn = l.tokenStartColumn();
1527 if (token == QQmlJSGrammar::T_IMPORT) {
1529 // .import <URI> <Version> as <Identifier>
1530 // .import <file.js> as <Identifier>
1536 if (token == QQmlJSGrammar::T_STRING_LITERAL) {
1538 QString file = l.tokenText();
1540 if (!file.endsWith(js))
1550 CHECK_TOKEN(T_IDENTIFIER);
1553 int endOffset = l.tokenLength() + l.tokenOffset();
1555 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1557 if (!importId.at(0).isUpper())
1560 QQmlScript::LocationSpan location =
1561 locationFromLexer(l, startLine, startColumn, startOffset);
1564 if (l.tokenStartLine() == startLine)
1567 replaceWithSpace(script, startOffset, endOffset - startOffset);
1570 import.type = Import::Script;
1572 import.qualifier = importId;
1573 import.location = location;
1575 rv.imports << import;
1582 if (!isUriToken(token))
1585 uri.append(l.tokenText());
1589 if (token != QQmlJSGrammar::T_DOT)
1592 uri.append(QLatin1Char('.'));
1598 CHECK_TOKEN(T_NUMERIC_LITERAL);
1599 version = script.mid(l.tokenOffset(), l.tokenLength());
1608 CHECK_TOKEN(T_IDENTIFIER);
1611 int endOffset = l.tokenLength() + l.tokenOffset();
1613 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1615 if (!importId.at(0).isUpper())
1618 QQmlScript::LocationSpan location =
1619 locationFromLexer(l, startLine, startColumn, startOffset);
1622 if (l.tokenStartLine() == startLine)
1625 replaceWithSpace(script, startOffset, endOffset - startOffset);
1628 import.type = Import::Library;
1630 import.version = version;
1631 import.qualifier = importId;
1632 import.location = location;
1634 rv.imports << import;
1637 } else if (token == QQmlJSGrammar::T_IDENTIFIER &&
1638 script.mid(l.tokenOffset(), l.tokenLength()) == pragma) {
1642 CHECK_TOKEN(T_IDENTIFIER);
1645 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1646 int endOffset = l.tokenLength() + l.tokenOffset();
1648 if (pragmaValue == library) {
1649 pragmas |= QQmlScript::Object::ScriptBlock::Shared;
1650 replaceWithSpace(script, startOffset, endOffset - startOffset);
1656 if (l.tokenStartLine() == startLine)
1666 void QQmlScript::Parser::clear()
1669 qDeleteAll(_refTypes);
1681 QQmlScript::TypeReference *QQmlScript::Parser::findOrCreateType(const QString &name)
1683 TypeReference *type = 0;
1685 for (; i < _refTypes.size(); ++i) {
1686 if (_refTypes.at(i)->name == name) {
1687 type = _refTypes.at(i);
1692 type = new TypeReference(i, name);
1693 _refTypes.append(type);
1699 void QQmlScript::Parser::setTree(QQmlScript::Object *tree)