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;
74 extObject.d.static_metacall = 0;
75 extObject.d.relatedMetaObjects = 0;
78 QQmlScript::Object::~Object()
80 if (synthCache) synthCache->release();
83 void Object::setBindingBit(int b)
85 while (bindingBitmask.size() < 4 * (1 + b / 32))
86 bindingBitmask.append(char(0));
88 quint32 *bits = (quint32 *)bindingBitmask.data();
89 bits[b / 32] |= (1 << (b % 32));
92 const QMetaObject *Object::metaObject() const
94 if (!metadata.isEmpty() && metatype)
100 QQmlScript::Property *Object::getDefaultProperty()
102 if (!defaultProperty) {
103 defaultProperty = pool()->New<Property>();
104 defaultProperty->parent = this;
106 return defaultProperty;
109 void QQmlScript::Object::addValueProperty(Property *p)
111 valueProperties.append(p);
114 void QQmlScript::Object::addSignalProperty(Property *p)
116 signalProperties.append(p);
119 void QQmlScript::Object::addAttachedProperty(Property *p)
121 attachedProperties.append(p);
124 void QQmlScript::Object::addGroupedProperty(Property *p)
126 groupedProperties.append(p);
129 void QQmlScript::Object::addValueTypeProperty(Property *p)
131 valueTypeProperties.append(p);
134 void QQmlScript::Object::addScriptStringProperty(Property *p)
136 scriptStringProperties.append(p);
139 // This lookup is optimized for missing, and having to create a new property.
140 Property *QQmlScript::Object::getProperty(const QHashedStringRef &name, bool create)
143 quint32 h = name.hash();
144 if (propertiesHashField.testAndSet(h)) {
145 for (Property *p = properties.first(); p; p = properties.next(p)) {
146 if (p->name() == name)
151 Property *property = pool()->New<Property>();
152 property->parent = this;
153 property->_name = name;
154 property->isDefault = false;
155 properties.prepend(property);
158 for (Property *p = properties.first(); p; p = properties.next(p)) {
159 if (p->name() == name)
167 Property *QQmlScript::Object::getProperty(const QStringRef &name, bool create)
169 return getProperty(QHashedStringRef(name), create);
172 Property *QQmlScript::Object::getProperty(const QString &name, bool create)
174 for (Property *p = properties.first(); p; p = properties.next(p)) {
175 if (p->name() == name)
180 Property *property = pool()->New<Property>();
181 property->parent = this;
182 property->_name = QStringRef(pool()->NewString(name));
183 propertiesHashField.testAndSet(property->_name.hash());
184 property->isDefault = false;
185 properties.prepend(property);
192 int QQmlScript::Object::aggregateDynamicSignalParameterCount() const
195 for (DynamicSignal *s = dynamicSignals.first(); s; s = dynamicSignals.next(s))
196 sum += s->parameterTypes.count() + 1; // +1 for return type
200 int QQmlScript::Object::aggregateDynamicSlotParameterCount() const
203 for (DynamicSlot *s = dynamicSlots.first(); s; s = dynamicSlots.next(s))
204 sum += s->parameterNames.count() + 1; // +1 for return type
208 QQmlScript::Object::DynamicProperty::DynamicProperty()
209 : isDefaultProperty(false), isReadOnly(false), type(Variant), defaultValue(0), nextProperty(0)
213 QQmlScript::Object::DynamicSignal::DynamicSignal()
218 QQmlScript::Object::DynamicSlot::DynamicSlot()
223 int QQmlScript::Object::DynamicSlot::parameterNamesLength() const
226 for (int ii = 0; ii < parameterNames.count(); ++ii)
227 rv += parameterNames.at(ii).length();
231 QQmlScript::Property::Property()
232 : parent(0), type(0), index(-1), value(0), isDefault(true), isDeferred(false),
233 isValueTypeSubProperty(false), isAlias(false), isReadOnlyDeclaration(false),
234 scriptStringScope(-1), nextMainProperty(0), nextProperty(0)
238 QQmlScript::Object *QQmlScript::Property::getValue(const LocationSpan &l)
240 if (!value) { value = pool()->New<Object>(); value->location = l; }
244 void QQmlScript::Property::addValue(Value *v)
249 void QQmlScript::Property::addOnValue(Value *v)
254 bool QQmlScript::Property::isEmpty() const
256 return !value && values.isEmpty() && onValues.isEmpty();
259 QQmlScript::Value::Value()
260 : type(Unknown), object(0), bindingReference(0), nextValue(0)
264 QQmlScript::Variant::Variant()
269 QQmlScript::Variant::Variant(const Variant &o)
270 : t(o.t), d(o.d), asWritten(o.asWritten)
274 QQmlScript::Variant::Variant(bool v)
279 QQmlScript::Variant::Variant(double v, const QStringRef &asWritten)
280 : t(Number), d(v), asWritten(asWritten)
284 QQmlScript::Variant::Variant(QQmlJS::AST::StringLiteral *v)
289 QQmlScript::Variant::Variant(const QStringRef &asWritten, QQmlJS::AST::Node *n)
290 : t(Script), n(n), asWritten(asWritten)
294 QQmlScript::Variant &QQmlScript::Variant::operator=(const Variant &o)
298 asWritten = o.asWritten;
302 QQmlScript::Variant::Type QQmlScript::Variant::type() const
307 bool QQmlScript::Variant::asBoolean() const
312 QString QQmlScript::Variant::asString() const
315 return l->value.toString();
317 return asWritten.toString();
321 double QQmlScript::Variant::asNumber() const
326 //reverse of Lexer::singleEscape()
327 QString escapedString(const QString &string)
329 QString tmp = QLatin1String("\"");
330 for (int i = 0; i < string.length(); ++i) {
331 const QChar &c = string.at(i);
332 switch(c.unicode()) {
334 tmp += QLatin1String("\\b");
337 tmp += QLatin1String("\\t");
340 tmp += QLatin1String("\\n");
343 tmp += QLatin1String("\\v");
346 tmp += QLatin1String("\\f");
349 tmp += QLatin1String("\\r");
352 tmp += QLatin1String("\\\"");
355 tmp += QLatin1String("\\\'");
358 tmp += QLatin1String("\\\\");
365 tmp += QLatin1Char('\"');
369 QString QQmlScript::Variant::asScript() const
376 return b?QLatin1String("true"):QLatin1String("false");
378 if (asWritten.isEmpty())
379 return QString::number(d);
381 return asWritten.toString();
383 return escapedString(asString());
385 if (AST::IdentifierExpression *i = AST::cast<AST::IdentifierExpression *>(n)) {
386 return i->name.toString();
388 return asWritten.toString();
392 QQmlJS::AST::Node *QQmlScript::Variant::asAST() const
394 if (type() == Script)
400 bool QQmlScript::Variant::isStringList() const
405 if (type() != Script || !n)
408 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
412 AST::ElementList *elements = array->elements;
416 if (!AST::cast<AST::StringLiteral *>(elements->expression))
419 elements = elements->next;
425 QStringList QQmlScript::Variant::asStringList() const
433 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
437 AST::ElementList *elements = array->elements;
440 AST::StringLiteral *string = AST::cast<AST::StringLiteral *>(elements->expression);
442 return QStringList();
443 rv.append(string->value.toString());
445 elements = elements->next;
452 // Actual parser classes
454 void QQmlScript::Import::extractVersion(int *maj, int *min) const
456 *maj = -1; *min = -1;
458 if (!version.isEmpty()) {
459 int dot = version.indexOf(QLatin1Char('.'));
461 *maj = version.toInt();
464 *maj = version.left(dot).toInt();
465 *min = version.mid(dot+1).toInt();
472 class ProcessAST: protected AST::Visitor
475 State() : object(0), property(0) {}
476 State(QQmlScript::Object *o) : object(o), property(0) {}
477 State(QQmlScript::Object *o, Property *p) : object(o), property(p) {}
479 QQmlScript::Object *object;
483 struct StateStack : public QStack<State>
485 void pushObject(QQmlScript::Object *obj)
490 void pushProperty(const QString &name, const LocationSpan &location)
492 const State &state = top();
493 if (state.property) {
494 State s(state.property->getValue(location),
495 state.property->getValue(location)->getProperty(name));
496 s.property->location = location;
499 State s(state.object, state.object->getProperty(name));
501 s.property->location = location;
506 void pushProperty(const QStringRef &name, const LocationSpan &location)
508 const State &state = top();
509 if (state.property) {
510 State s(state.property->getValue(location),
511 state.property->getValue(location)->getProperty(name));
512 s.property->location = location;
515 State s(state.object, state.object->getProperty(name));
517 s.property->location = location;
524 ProcessAST(QQmlScript::Parser *parser);
525 virtual ~ProcessAST();
527 void operator()(const QString &code, AST::Node *node);
531 QQmlScript::Object *defineObjectBinding(AST::UiQualifiedId *propertyName, bool onAssignment,
532 const QString &objectType,
533 AST::SourceLocation typeLocation,
534 LocationSpan location,
535 AST::UiObjectInitializer *initializer = 0);
537 QQmlScript::Variant getVariant(AST::Statement *stmt);
538 QQmlScript::Variant getVariant(AST::ExpressionNode *expr);
540 LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
541 LocationSpan location(AST::UiQualifiedId *);
543 using AST::Visitor::visit;
544 using AST::Visitor::endVisit;
546 virtual bool visit(AST::UiProgram *node);
547 virtual bool visit(AST::UiImport *node);
548 virtual bool visit(AST::UiObjectDefinition *node);
549 virtual bool visit(AST::UiPublicMember *node);
550 virtual bool visit(AST::UiObjectBinding *node);
552 virtual bool visit(AST::UiScriptBinding *node);
553 virtual bool visit(AST::UiArrayBinding *node);
554 virtual bool visit(AST::UiSourceElement *node);
556 void accept(AST::Node *node);
558 QString asString(AST::UiQualifiedId *node) const;
560 const State state() const;
561 QQmlScript::Object *currentObject() const;
562 Property *currentProperty() const;
564 QString qualifiedNameId() const;
566 QString textAt(const AST::SourceLocation &loc) const
567 { return _contents->mid(loc.offset, loc.length); }
569 QStringRef textRefAt(const AST::SourceLocation &loc) const
570 { return QStringRef(_contents, loc.offset, loc.length); }
572 QString textAt(const AST::SourceLocation &first,
573 const AST::SourceLocation &last) const
574 { return _contents->mid(first.offset, last.offset + last.length - first.offset); }
576 QStringRef textRefAt(const AST::SourceLocation &first,
577 const AST::SourceLocation &last) const
578 { return QStringRef(_contents, first.offset, last.offset + last.length - first.offset); }
580 QString asString(AST::ExpressionNode *expr)
585 return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
588 QStringRef asStringRef(AST::ExpressionNode *expr)
593 return textRefAt(expr->firstSourceLocation(), expr->lastSourceLocation());
596 QString asString(AST::Statement *stmt)
601 QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
602 s += QLatin1Char('\n');
606 QStringRef asStringRef(AST::Statement *stmt)
611 return textRefAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
615 QQmlScript::Parser *_parser;
616 StateStack _stateStack;
618 const QString *_contents;
621 ProcessAST::ProcessAST(QQmlScript::Parser *parser)
626 ProcessAST::~ProcessAST()
630 void ProcessAST::operator()(const QString &code, AST::Node *node)
636 void ProcessAST::accept(AST::Node *node)
638 AST::Node::acceptChild(node, this);
641 const ProcessAST::State ProcessAST::state() const
643 if (_stateStack.isEmpty())
646 return _stateStack.back();
649 QQmlScript::Object *ProcessAST::currentObject() const
651 return state().object;
654 Property *ProcessAST::currentProperty() const
656 return state().property;
659 QString ProcessAST::qualifiedNameId() const
661 return _scope.join(QLatin1String("/"));
664 QString ProcessAST::asString(AST::UiQualifiedId *node) const
668 for (AST::UiQualifiedId *it = node; it; it = it->next) {
669 s.append(it->name.toString());
672 s.append(QLatin1Char('.'));
679 ProcessAST::defineObjectBinding(AST::UiQualifiedId *propertyName,
681 const QString &objectType,
682 AST::SourceLocation typeLocation,
683 LocationSpan location,
684 AST::UiObjectInitializer *initializer)
686 int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
688 // With no preceding qualification, first char is at (-1 + 1) == 0
689 bool isType = !objectType.isEmpty() && objectType.at(lastTypeDot+1).isUpper();
691 int propertyCount = 0;
692 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
694 _stateStack.pushProperty(name->name,
695 this->location(name));
698 if (!onAssignment && propertyCount && currentProperty() && !currentProperty()->values.isEmpty()) {
700 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
701 error.setLine(this->location(propertyName).start.line);
702 error.setColumn(this->location(propertyName).start.column);
703 _parser->_errors << error;
709 // Is the identifier qualified by a namespace?
710 int namespaceLength = 0;
711 if (lastTypeDot > 0) {
712 const QString qualifier(objectType.left(lastTypeDot));
714 for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
715 const QQmlScript::Import &import = _parser->_imports.at(ii);
716 if (import.qualifier == qualifier) {
717 // The qualifier is a namespace - expect a type here
718 namespaceLength = qualifier.length() + 1;
724 if (propertyCount || !currentObject() || namespaceLength) {
726 error.setDescription(QCoreApplication::translate("QQmlParser","Expected type name"));
727 error.setLine(typeLocation.startLine);
728 error.setColumn(typeLocation.startColumn + namespaceLength);
729 _parser->_errors << error;
733 LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
735 loc = ProcessAST::location(propertyName);
737 _stateStack.pushProperty(objectType, loc);
746 QString resolvableObjectType = objectType;
747 if (lastTypeDot >= 0)
748 resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
750 QQmlScript::Object *obj = _parser->_pool.New<QQmlScript::Object>();
752 QQmlScript::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
753 obj->type = typeRef->id;
755 typeRef->refObjects.append(obj);
757 // XXX this doesn't do anything (_scope never builds up)
758 _scope.append(resolvableObjectType);
759 obj->typeName = qualifiedNameId();
762 obj->location = location;
765 Property *prop = currentProperty();
766 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
768 v->location = obj->location;
774 while (propertyCount--)
779 if (! _parser->tree()) {
780 _parser->setTree(obj);
782 const State state = _stateStack.top();
783 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
785 v->location = obj->location;
786 if (state.property) {
787 state.property->addValue(v);
789 Property *defaultProp = state.object->getDefaultProperty();
790 if (defaultProp->location.start.line == -1) {
791 defaultProp->location = v->location;
792 defaultProp->location.end = defaultProp->location.start;
793 defaultProp->location.range.length = 0;
795 defaultProp->addValue(v);
800 _stateStack.pushObject(obj);
808 LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
810 return location(id->identifierToken, id->identifierToken);
813 LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
816 rv.start.line = start.startLine;
817 rv.start.column = start.startColumn;
818 rv.end.line = end.startLine;
819 rv.end.column = end.startColumn + end.length - 1;
820 rv.range.offset = start.offset;
821 rv.range.length = end.offset + end.length - start.offset;
825 // UiProgram: UiImportListOpt UiObjectMemberList ;
826 bool ProcessAST::visit(AST::UiProgram *node)
828 accept(node->imports);
829 accept(node->members->member);
833 // UiImport: T_IMPORT T_STRING_LITERAL ;
834 bool ProcessAST::visit(AST::UiImport *node)
837 QQmlScript::Import import;
839 if (!node->fileName.isNull()) {
840 uri = node->fileName.toString();
842 if (uri.endsWith(QLatin1String(".js"))) {
843 import.type = QQmlScript::Import::Script;
845 import.type = QQmlScript::Import::File;
848 import.type = QQmlScript::Import::Library;
849 uri = asString(node->importUri);
852 AST::SourceLocation startLoc = node->importToken;
853 AST::SourceLocation endLoc = node->semicolonToken;
856 if (!node->importId.isNull()) {
857 import.qualifier = node->importId.toString();
858 if (!import.qualifier.at(0).isUpper()) {
860 error.setDescription(QCoreApplication::translate("QQmlParser","Invalid import qualifier ID"));
861 error.setLine(node->importIdToken.startLine);
862 error.setColumn(node->importIdToken.startColumn);
863 _parser->_errors << error;
866 if (import.qualifier == QLatin1String("Qt")) {
868 error.setDescription(QCoreApplication::translate("QQmlParser","Reserved name \"Qt\" cannot be used as an qualifier"));
869 error.setLine(node->importIdToken.startLine);
870 error.setColumn(node->importIdToken.startColumn);
871 _parser->_errors << error;
875 // Check for script qualifier clashes
876 bool isScript = import.type == QQmlScript::Import::Script;
877 for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
878 const QQmlScript::Import &other = _parser->_imports.at(ii);
879 bool otherIsScript = other.type == QQmlScript::Import::Script;
881 if ((isScript || otherIsScript) && import.qualifier == other.qualifier) {
883 error.setDescription(QCoreApplication::translate("QQmlParser","Script import qualifiers must be unique."));
884 error.setLine(node->importIdToken.startLine);
885 error.setColumn(node->importIdToken.startColumn);
886 _parser->_errors << error;
891 } else if (import.type == QQmlScript::Import::Script) {
893 error.setDescription(QCoreApplication::translate("QQmlParser","Script import requires a qualifier"));
894 error.setLine(node->fileNameToken.startLine);
895 error.setColumn(node->fileNameToken.startColumn);
896 _parser->_errors << error;
900 if (node->versionToken.isValid()) {
901 import.version = textAt(node->versionToken);
902 } else if (import.type == QQmlScript::Import::Library) {
904 error.setDescription(QCoreApplication::translate("QQmlParser","Library import requires a version"));
905 error.setLine(node->importIdToken.startLine);
906 error.setColumn(node->importIdToken.startColumn);
907 _parser->_errors << error;
912 import.location = location(startLoc, endLoc);
915 _parser->_imports << import;
920 bool ProcessAST::visit(AST::UiPublicMember *node)
922 static const struct TypeNameToType {
925 Object::DynamicProperty::Type type;
926 } propTypeNameToTypes[] = {
927 { "int", strlen("int"), Object::DynamicProperty::Int },
928 { "bool", strlen("bool"), Object::DynamicProperty::Bool },
929 { "double", strlen("double"), Object::DynamicProperty::Real },
930 { "real", strlen("real"), Object::DynamicProperty::Real },
931 { "string", strlen("string"), Object::DynamicProperty::String },
932 { "url", strlen("url"), Object::DynamicProperty::Url },
933 { "color", strlen("color"), Object::DynamicProperty::Color },
934 // Internally QTime, QDate and QDateTime are all supported.
935 // To be more consistent with JavaScript we expose only
936 // QDateTime as it matches closely with the Date JS type.
937 // We also call it "date" to match.
938 // { "time", strlen("time"), Object::DynamicProperty::Time },
939 // { "date", strlen("date"), Object::DynamicProperty::Date },
940 { "date", strlen("date"), Object::DynamicProperty::DateTime },
941 { "variant", strlen("variant"), Object::DynamicProperty::Variant },
942 { "var", strlen("var"), Object::DynamicProperty::Var }
944 static const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
945 sizeof(propTypeNameToTypes[0]);
947 if(node->type == AST::UiPublicMember::Signal) {
948 Object::DynamicSignal *signal = _parser->_pool.New<Object::DynamicSignal>();
949 signal->name = node->name;
951 AST::UiParameterList *p = node->parameters;
953 while (p) { paramLength++; p = p->next; }
954 p = node->parameters;
957 signal->parameterTypes = _parser->_pool.NewRawList<Object::DynamicProperty::Type>(paramLength);
958 signal->parameterNames = _parser->_pool.NewRawList<QHashedStringRef>(paramLength);
963 const QStringRef &memberType = p->type;
965 const TypeNameToType *type = 0;
966 for(int typeIndex = 0; typeIndex < propTypeNameToTypesCount; ++typeIndex) {
967 const TypeNameToType *t = propTypeNameToTypes + typeIndex;
968 if (t->nameLength == memberType.length() &&
969 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
977 error.setDescription(QCoreApplication::translate("QQmlParser","Expected parameter type"));
978 error.setLine(node->typeToken.startLine);
979 error.setColumn(node->typeToken.startColumn);
980 _parser->_errors << error;
984 signal->parameterTypes[index] = type->type;
985 signal->parameterNames[index] = QHashedStringRef(p->name);
990 signal->location = location(node->typeToken, node->semicolonToken);
991 _stateStack.top().object->dynamicSignals.append(signal);
993 const QStringRef &memberType = node->memberType;
994 const QStringRef &name = node->name;
996 bool typeFound = false;
997 Object::DynamicProperty::Type type;
999 if ((unsigned)memberType.length() == strlen("alias") &&
1000 QHashedString::compare(memberType.constData(), "alias", strlen("alias"))) {
1001 type = Object::DynamicProperty::Alias;
1005 for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
1006 const TypeNameToType *t = propTypeNameToTypes + ii;
1007 if (t->nameLength == memberType.length() &&
1008 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
1014 if (!typeFound && memberType.at(0).isUpper()) {
1015 const QStringRef &typeModifier = node->typeModifier;
1017 if (typeModifier.isEmpty()) {
1018 type = Object::DynamicProperty::Custom;
1019 } else if((unsigned)typeModifier.length() == strlen("list") &&
1020 QHashedString::compare(typeModifier.constData(), "list", strlen("list"))) {
1021 type = Object::DynamicProperty::CustomList;
1024 error.setDescription(QCoreApplication::translate("QQmlParser","Invalid property type modifier"));
1025 error.setLine(node->typeModifierToken.startLine);
1026 error.setColumn(node->typeModifierToken.startColumn);
1027 _parser->_errors << error;
1031 } else if (!node->typeModifier.isNull()) {
1033 error.setDescription(QCoreApplication::translate("QQmlParser","Unexpected property type modifier"));
1034 error.setLine(node->typeModifierToken.startLine);
1035 error.setColumn(node->typeModifierToken.startColumn);
1036 _parser->_errors << error;
1042 error.setDescription(QCoreApplication::translate("QQmlParser","Expected property type"));
1043 error.setLine(node->typeToken.startLine);
1044 error.setColumn(node->typeToken.startColumn);
1045 _parser->_errors << error;
1049 Object::DynamicProperty *property = _parser->_pool.New<Object::DynamicProperty>();
1050 property->isDefaultProperty = node->isDefaultMember;
1051 property->isReadOnly = node->isReadonlyMember;
1052 property->type = type;
1053 property->nameLocation.line = node->identifierToken.startLine;
1054 property->nameLocation.column = node->identifierToken.startColumn;
1055 if (type >= Object::DynamicProperty::Custom) {
1056 QQmlScript::TypeReference *typeRef =
1057 _parser->findOrCreateType(memberType.toString());
1058 typeRef->refObjects.append(_stateStack.top().object);
1059 property->customType = memberType;
1062 property->name = QHashedStringRef(name);
1063 property->location = location(node->firstSourceLocation(),
1064 node->lastSourceLocation());
1066 if (node->statement) { // default value
1067 property->defaultValue = _parser->_pool.New<Property>();
1068 property->defaultValue->parent = _stateStack.top().object;
1069 property->defaultValue->location =
1070 location(node->statement->firstSourceLocation(),
1071 node->statement->lastSourceLocation());
1072 QQmlScript::Value *value = _parser->_pool.New<QQmlScript::Value>();
1073 value->location = location(node->statement->firstSourceLocation(),
1074 node->statement->lastSourceLocation());
1075 value->value = getVariant(node->statement);
1076 property->defaultValue->values.append(value);
1079 _stateStack.top().object->dynamicProperties.append(property);
1081 // process QML-like initializers (e.g. property Object o: Object {})
1082 accept(node->binding);
1089 // UiObjectMember: UiQualifiedId UiObjectInitializer ;
1090 bool ProcessAST::visit(AST::UiObjectDefinition *node)
1092 LocationSpan l = location(node->firstSourceLocation(),
1093 node->lastSourceLocation());
1095 const QString objectType = asString(node->qualifiedTypeNameId);
1096 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1098 defineObjectBinding(/*propertyName = */ 0, false, objectType,
1099 typeLocation, l, node->initializer);
1105 // UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
1106 bool ProcessAST::visit(AST::UiObjectBinding *node)
1108 LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
1109 node->initializer->rbraceToken);
1111 const QString objectType = asString(node->qualifiedTypeNameId);
1112 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1114 defineObjectBinding(node->qualifiedId, node->hasOnToken, objectType,
1115 typeLocation, l, node->initializer);
1120 QQmlScript::Variant ProcessAST::getVariant(AST::Statement *stmt)
1123 if (AST::ExpressionStatement *exprStmt = AST::cast<AST::ExpressionStatement *>(stmt))
1124 return getVariant(exprStmt->expression);
1126 return QQmlScript::Variant(asStringRef(stmt), stmt);
1129 return QQmlScript::Variant();
1132 QQmlScript::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
1134 if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
1135 return QQmlScript::Variant(lit);
1136 } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
1137 return QQmlScript::Variant(true);
1138 } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
1139 return QQmlScript::Variant(false);
1140 } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
1141 return QQmlScript::Variant(lit->value, asStringRef(expr));
1144 if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
1145 if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
1146 return QQmlScript::Variant(-lit->value, asStringRef(expr));
1150 return QQmlScript::Variant(asStringRef(expr), expr);
1155 // UiObjectMember: UiQualifiedId T_COLON Statement ;
1156 bool ProcessAST::visit(AST::UiScriptBinding *node)
1158 int propertyCount = 0;
1159 AST::UiQualifiedId *propertyName = node->qualifiedId;
1160 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1162 _stateStack.pushProperty(name->name,
1166 Property *prop = currentProperty();
1168 if (!prop->values.isEmpty()) {
1170 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
1171 error.setLine(this->location(propertyName).start.line);
1172 error.setColumn(this->location(propertyName).start.column);
1173 _parser->_errors << error;
1177 QQmlScript::Variant primitive;
1179 if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
1180 primitive = getVariant(stmt->expression);
1181 } else { // do binding
1182 primitive = QQmlScript::Variant(asStringRef(node->statement), node->statement);
1185 prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
1186 prop->location.range.offset = node->qualifiedId->identifierToken.offset;
1187 QQmlScript::Value *v = _parser->_pool.New<QQmlScript::Value>();
1188 v->value = primitive;
1189 v->location = location(node->statement->firstSourceLocation(),
1190 node->statement->lastSourceLocation());
1194 while (propertyCount--)
1200 // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
1201 bool ProcessAST::visit(AST::UiArrayBinding *node)
1203 int propertyCount = 0;
1204 AST::UiQualifiedId *propertyName = node->qualifiedId;
1205 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1207 _stateStack.pushProperty(name->name,
1211 Property* prop = currentProperty();
1213 if (!prop->values.isEmpty()) {
1215 error.setDescription(QCoreApplication::translate("QQmlParser","Property value set multiple times"));
1216 error.setLine(this->location(propertyName).start.line);
1217 error.setColumn(this->location(propertyName).start.column);
1218 _parser->_errors << error;
1222 accept(node->members);
1224 // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
1225 prop->listValueRange.offset = node->lbracketToken.offset;
1226 prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
1228 while (propertyCount--)
1234 bool ProcessAST::visit(AST::UiSourceElement *node)
1236 QQmlScript::Object *obj = currentObject();
1238 if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
1240 Object::DynamicSlot *slot = _parser->_pool.New<Object::DynamicSlot>();
1241 slot->location = location(funDecl->identifierToken, funDecl->lastSourceLocation());
1243 AST::FormalParameterList *f = funDecl->formals;
1245 slot->parameterNames << f->name.toUtf8();
1249 AST::SourceLocation loc = funDecl->rparenToken;
1250 loc.offset = loc.end();
1251 loc.startColumn += 1;
1252 QString body = textAt(loc, funDecl->rbraceToken);
1253 slot->name = funDecl->name;
1255 obj->dynamicSlots.append(slot);
1259 error.setDescription(QCoreApplication::translate("QQmlParser","JavaScript declaration outside Script element"));
1260 error.setLine(node->firstSourceLocation().startLine);
1261 error.setColumn(node->firstSourceLocation().startColumn);
1262 _parser->_errors << error;
1267 } // end of anonymous namespace
1270 QQmlScript::Parser::Parser()
1276 QQmlScript::Parser::~Parser()
1281 namespace QQmlScript {
1282 class ParserJsASTData
1285 ParserJsASTData(const QString &filename)
1286 : filename(filename) {}
1293 bool QQmlScript::Parser::parse(const QByteArray &qmldata, const QUrl &url,
1294 const QString &urlString)
1298 if (urlString.isEmpty()) {
1299 _scriptFile = url.toString();
1301 // Q_ASSERT(urlString == url.toString());
1302 _scriptFile = urlString;
1305 QTextStream stream(qmldata, QIODevice::ReadOnly);
1306 #ifndef QT_NO_TEXTCODEC
1307 stream.setCodec("UTF-8");
1309 QString *code = _pool.NewString(stream.readAll());
1311 data = new QQmlScript::ParserJsASTData(_scriptFile);
1313 Lexer lexer(&data->engine);
1314 lexer.setCode(*code, /*line = */ 1);
1316 QQmlJS::Parser parser(&data->engine);
1318 if (! parser.parse() || !_errors.isEmpty()) {
1320 // Extract errors from the parser
1321 foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
1328 error.setDescription(m.message);
1329 error.setLine(m.loc.startLine);
1330 error.setColumn(m.loc.startColumn);
1336 if (_errors.isEmpty()) {
1337 ProcessAST process(this);
1338 process(*code, parser.ast());
1340 // Set the url for process errors
1341 for(int ii = 0; ii < _errors.count(); ++ii)
1342 _errors[ii].setUrl(url);
1345 return _errors.isEmpty();
1348 QList<QQmlScript::TypeReference*> QQmlScript::Parser::referencedTypes() const
1353 QQmlScript::Object *QQmlScript::Parser::tree() const
1358 QList<QQmlScript::Import> QQmlScript::Parser::imports() const
1363 QList<QQmlError> QQmlScript::Parser::errors() const
1368 static void replaceWithSpace(QString &str, int idx, int n)
1370 QChar *data = str.data() + idx;
1371 const QChar space(QLatin1Char(' '));
1372 for (int ii = 0; ii < n; ++ii)
1376 static QQmlScript::LocationSpan
1377 locationFromLexer(const QQmlJS::Lexer &lex, int startLine, int startColumn, int startOffset)
1379 QQmlScript::LocationSpan l;
1381 l.start.line = startLine; l.start.column = startColumn;
1382 l.end.line = lex.tokenEndLine(); l.end.column = lex.tokenEndColumn();
1383 l.range.offset = startOffset;
1384 l.range.length = lex.tokenOffset() + lex.tokenLength() - startOffset;
1390 Searches for ".pragma <value>" declarations within \a script. Currently supported pragmas
1394 QQmlScript::Object::ScriptBlock::Pragmas QQmlScript::Parser::extractPragmas(QString &script)
1396 QQmlScript::Object::ScriptBlock::Pragmas rv = QQmlScript::Object::ScriptBlock::None;
1398 const QString pragma(QLatin1String("pragma"));
1399 const QString library(QLatin1String("library"));
1402 l.setCode(script, 0);
1404 int token = l.lex();
1407 if (token != QQmlJSGrammar::T_DOT)
1410 int startOffset = l.tokenOffset();
1411 int startLine = l.tokenStartLine();
1415 if (token != QQmlJSGrammar::T_IDENTIFIER ||
1416 l.tokenStartLine() != startLine ||
1417 script.mid(l.tokenOffset(), l.tokenLength()) != pragma)
1422 if (token != QQmlJSGrammar::T_IDENTIFIER ||
1423 l.tokenStartLine() != startLine)
1426 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1427 int endOffset = l.tokenLength() + l.tokenOffset();
1430 if (l.tokenStartLine() == startLine)
1433 if (pragmaValue == library) {
1434 rv |= QQmlScript::Object::ScriptBlock::Shared;
1435 replaceWithSpace(script, startOffset, endOffset - startOffset);
1443 #define CHECK_LINE if (l.tokenStartLine() != startLine) return rv;
1444 #define CHECK_TOKEN(t) if (token != QQmlJSGrammar:: t) return rv;
1446 static const int uriTokens[] = {
1447 QQmlJSGrammar::T_IDENTIFIER,
1448 QQmlJSGrammar::T_PROPERTY,
1449 QQmlJSGrammar::T_SIGNAL,
1450 QQmlJSGrammar::T_READONLY,
1451 QQmlJSGrammar::T_ON,
1452 QQmlJSGrammar::T_BREAK,
1453 QQmlJSGrammar::T_CASE,
1454 QQmlJSGrammar::T_CATCH,
1455 QQmlJSGrammar::T_CONTINUE,
1456 QQmlJSGrammar::T_DEFAULT,
1457 QQmlJSGrammar::T_DELETE,
1458 QQmlJSGrammar::T_DO,
1459 QQmlJSGrammar::T_ELSE,
1460 QQmlJSGrammar::T_FALSE,
1461 QQmlJSGrammar::T_FINALLY,
1462 QQmlJSGrammar::T_FOR,
1463 QQmlJSGrammar::T_FUNCTION,
1464 QQmlJSGrammar::T_IF,
1465 QQmlJSGrammar::T_IN,
1466 QQmlJSGrammar::T_INSTANCEOF,
1467 QQmlJSGrammar::T_NEW,
1468 QQmlJSGrammar::T_NULL,
1469 QQmlJSGrammar::T_RETURN,
1470 QQmlJSGrammar::T_SWITCH,
1471 QQmlJSGrammar::T_THIS,
1472 QQmlJSGrammar::T_THROW,
1473 QQmlJSGrammar::T_TRUE,
1474 QQmlJSGrammar::T_TRY,
1475 QQmlJSGrammar::T_TYPEOF,
1476 QQmlJSGrammar::T_VAR,
1477 QQmlJSGrammar::T_VOID,
1478 QQmlJSGrammar::T_WHILE,
1479 QQmlJSGrammar::T_CONST,
1480 QQmlJSGrammar::T_DEBUGGER,
1481 QQmlJSGrammar::T_RESERVED_WORD,
1482 QQmlJSGrammar::T_WITH,
1484 QQmlJSGrammar::EOF_SYMBOL
1486 static inline bool isUriToken(int token)
1488 const int *current = uriTokens;
1489 while (*current != QQmlJSGrammar::EOF_SYMBOL) {
1490 if (*current == token)
1497 QQmlScript::Parser::JavaScriptMetaData QQmlScript::Parser::extractMetaData(QString &script)
1499 JavaScriptMetaData rv;
1501 QQmlScript::Object::ScriptBlock::Pragmas &pragmas = rv.pragmas;
1503 const QString pragma(QLatin1String("pragma"));
1504 const QString js(QLatin1String(".js"));
1505 const QString library(QLatin1String("library"));
1508 l.setCode(script, 0);
1510 int token = l.lex();
1513 if (token != QQmlJSGrammar::T_DOT)
1516 int startOffset = l.tokenOffset();
1517 int startLine = l.tokenStartLine();
1518 int startColumn = l.tokenStartColumn();
1524 if (token == QQmlJSGrammar::T_IMPORT) {
1526 // .import <URI> <Version> as <Identifier>
1527 // .import <file.js> as <Identifier>
1533 if (token == QQmlJSGrammar::T_STRING_LITERAL) {
1535 QString file = l.tokenText();
1537 if (!file.endsWith(js))
1547 CHECK_TOKEN(T_IDENTIFIER);
1550 int endOffset = l.tokenLength() + l.tokenOffset();
1552 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1554 if (!importId.at(0).isUpper())
1557 QQmlScript::LocationSpan location =
1558 locationFromLexer(l, startLine, startColumn, startOffset);
1561 if (l.tokenStartLine() == startLine)
1564 replaceWithSpace(script, startOffset, endOffset - startOffset);
1567 import.type = Import::Script;
1569 import.qualifier = importId;
1570 import.location = location;
1572 rv.imports << import;
1579 if (!isUriToken(token))
1582 uri.append(l.tokenText());
1586 if (token != QQmlJSGrammar::T_DOT)
1589 uri.append(QLatin1Char('.'));
1595 CHECK_TOKEN(T_NUMERIC_LITERAL);
1596 version = script.mid(l.tokenOffset(), l.tokenLength());
1605 CHECK_TOKEN(T_IDENTIFIER);
1608 int endOffset = l.tokenLength() + l.tokenOffset();
1610 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1612 if (!importId.at(0).isUpper())
1615 QQmlScript::LocationSpan location =
1616 locationFromLexer(l, startLine, startColumn, startOffset);
1619 if (l.tokenStartLine() == startLine)
1622 replaceWithSpace(script, startOffset, endOffset - startOffset);
1625 import.type = Import::Library;
1627 import.version = version;
1628 import.qualifier = importId;
1629 import.location = location;
1631 rv.imports << import;
1634 } else if (token == QQmlJSGrammar::T_IDENTIFIER &&
1635 script.mid(l.tokenOffset(), l.tokenLength()) == pragma) {
1639 CHECK_TOKEN(T_IDENTIFIER);
1642 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1643 int endOffset = l.tokenLength() + l.tokenOffset();
1645 if (pragmaValue == library) {
1646 pragmas |= QQmlScript::Object::ScriptBlock::Shared;
1647 replaceWithSpace(script, startOffset, endOffset - startOffset);
1653 if (l.tokenStartLine() == startLine)
1663 void QQmlScript::Parser::clear()
1666 qDeleteAll(_refTypes);
1678 QQmlScript::TypeReference *QQmlScript::Parser::findOrCreateType(const QString &name)
1680 TypeReference *type = 0;
1682 for (; i < _refTypes.size(); ++i) {
1683 if (_refTypes.at(i)->name == name) {
1684 type = _refTypes.at(i);
1689 type = new TypeReference(i, name);
1690 _refTypes.append(type);
1696 void QQmlScript::Parser::setTree(QQmlScript::Object *tree)