1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qdeclarativescript_p.h"
44 #include "parser/qdeclarativejsengine_p.h"
45 #include "parser/qdeclarativejsparser_p.h"
46 #include "parser/qdeclarativejslexer_p.h"
47 #include "parser/qdeclarativejsmemorypool_p.h"
48 #include "parser/qdeclarativejsastvisitor_p.h"
49 #include "parser/qdeclarativejsast_p.h"
50 #include <private/qdeclarativerewrite_p.h>
53 #include <QCoreApplication>
58 using namespace QDeclarativeJS;
59 using namespace QDeclarativeScript;
64 QDeclarativeScript::Object::Object()
65 : type(-1), idIndex(-1), metatype(0), synthCache(0), defaultProperty(0), parserStatusCast(-1),
66 componentCompileState(0), nextAliasingObject(0), nextIdObject(0)
70 QDeclarativeScript::Object::~Object()
72 if (synthCache) synthCache->release();
75 void Object::setBindingBit(int b)
77 while (bindingBitmask.size() < 4 * (1 + b / 32))
78 bindingBitmask.append(char(0));
80 quint32 *bits = (quint32 *)bindingBitmask.data();
81 bits[b / 32] |= (1 << (b % 32));
84 const QMetaObject *Object::metaObject() const
86 if (!metadata.isEmpty() && metatype)
92 QDeclarativeScript::Property *Object::getDefaultProperty()
94 if (!defaultProperty) {
95 defaultProperty = pool()->New<Property>();
96 defaultProperty->parent = this;
98 return defaultProperty;
101 void QDeclarativeScript::Object::addValueProperty(Property *p)
103 valueProperties.append(p);
106 void QDeclarativeScript::Object::addSignalProperty(Property *p)
108 signalProperties.append(p);
111 void QDeclarativeScript::Object::addAttachedProperty(Property *p)
113 attachedProperties.append(p);
116 void QDeclarativeScript::Object::addGroupedProperty(Property *p)
118 groupedProperties.append(p);
121 void QDeclarativeScript::Object::addValueTypeProperty(Property *p)
123 valueTypeProperties.append(p);
126 void QDeclarativeScript::Object::addScriptStringProperty(Property *p)
128 scriptStringProperties.append(p);
131 // This lookup is optimized for missing, and having to create a new property.
132 Property *QDeclarativeScript::Object::getProperty(const QHashedStringRef &name, bool create)
135 quint32 h = name.hash();
136 if (propertiesHashField.testAndSet(h)) {
137 for (Property *p = properties.first(); p; p = properties.next(p)) {
138 if (p->name() == name)
143 Property *property = pool()->New<Property>();
144 property->parent = this;
145 property->_name = name;
146 property->isDefault = false;
147 properties.prepend(property);
150 for (Property *p = properties.first(); p; p = properties.next(p)) {
151 if (p->name() == name)
159 Property *QDeclarativeScript::Object::getProperty(const QStringRef &name, bool create)
161 return getProperty(QHashedStringRef(name), create);
164 Property *QDeclarativeScript::Object::getProperty(const QString &name, bool create)
166 for (Property *p = properties.first(); p; p = properties.next(p)) {
167 if (p->name() == name)
172 Property *property = pool()->New<Property>();
173 property->parent = this;
174 property->_name = QStringRef(pool()->NewString(name));
175 propertiesHashField.testAndSet(property->_name.hash());
176 property->isDefault = false;
177 properties.prepend(property);
184 QDeclarativeScript::Object::DynamicProperty::DynamicProperty()
185 : isDefaultProperty(false), isReadOnly(false), type(Variant), defaultValue(0), nextProperty(0),
186 resolvedCustomTypeName(0)
190 QDeclarativeScript::Object::DynamicSignal::DynamicSignal()
195 // Returns length in utf8 bytes
196 int QDeclarativeScript::Object::DynamicSignal::parameterTypesLength() const
199 for (int ii = 0; ii < parameterTypes.count(); ++ii)
200 rv += parameterTypes.at(ii).length();
204 // Returns length in utf8 bytes
205 int QDeclarativeScript::Object::DynamicSignal::parameterNamesLength() const
208 for (int ii = 0; ii < parameterNames.count(); ++ii)
209 rv += parameterNames.at(ii).utf8length();
213 QDeclarativeScript::Object::DynamicSlot::DynamicSlot()
218 int QDeclarativeScript::Object::DynamicSlot::parameterNamesLength() const
221 for (int ii = 0; ii < parameterNames.count(); ++ii)
222 rv += parameterNames.at(ii).length();
226 QDeclarativeScript::Property::Property()
227 : parent(0), type(0), index(-1), value(0), isDefault(true), isDeferred(false),
228 isValueTypeSubProperty(false), isAlias(false), isReadOnlyDeclaration(false),
229 scriptStringScope(-1), nextMainProperty(0), nextProperty(0)
233 QDeclarativeScript::Object *QDeclarativeScript::Property::getValue(const LocationSpan &l)
235 if (!value) { value = pool()->New<Object>(); value->location = l; }
239 void QDeclarativeScript::Property::addValue(Value *v)
244 void QDeclarativeScript::Property::addOnValue(Value *v)
249 bool QDeclarativeScript::Property::isEmpty() const
251 return !value && values.isEmpty() && onValues.isEmpty();
254 QDeclarativeScript::Value::Value()
255 : type(Unknown), object(0), bindingReference(0), nextValue(0)
259 QDeclarativeScript::Variant::Variant()
264 QDeclarativeScript::Variant::Variant(const Variant &o)
265 : t(o.t), d(o.d), asWritten(o.asWritten)
269 QDeclarativeScript::Variant::Variant(bool v)
274 QDeclarativeScript::Variant::Variant(double v, const QStringRef &asWritten)
275 : t(Number), d(v), asWritten(asWritten)
279 QDeclarativeScript::Variant::Variant(QDeclarativeJS::AST::StringLiteral *v)
284 QDeclarativeScript::Variant::Variant(const QStringRef &asWritten, QDeclarativeJS::AST::Node *n)
285 : t(Script), n(n), asWritten(asWritten)
289 QDeclarativeScript::Variant &QDeclarativeScript::Variant::operator=(const Variant &o)
293 asWritten = o.asWritten;
297 QDeclarativeScript::Variant::Type QDeclarativeScript::Variant::type() const
302 bool QDeclarativeScript::Variant::asBoolean() const
307 QString QDeclarativeScript::Variant::asString() const
310 return l->value.toString();
312 return asWritten.toString();
316 double QDeclarativeScript::Variant::asNumber() const
321 //reverse of Lexer::singleEscape()
322 QString escapedString(const QString &string)
324 QString tmp = QLatin1String("\"");
325 for (int i = 0; i < string.length(); ++i) {
326 const QChar &c = string.at(i);
327 switch(c.unicode()) {
329 tmp += QLatin1String("\\b");
332 tmp += QLatin1String("\\t");
335 tmp += QLatin1String("\\n");
338 tmp += QLatin1String("\\v");
341 tmp += QLatin1String("\\f");
344 tmp += QLatin1String("\\r");
347 tmp += QLatin1String("\\\"");
350 tmp += QLatin1String("\\\'");
353 tmp += QLatin1String("\\\\");
360 tmp += QLatin1Char('\"');
364 QString QDeclarativeScript::Variant::asScript() const
371 return b?QLatin1String("true"):QLatin1String("false");
373 if (asWritten.isEmpty())
374 return QString::number(d);
376 return asWritten.toString();
378 return escapedString(asString());
380 if (AST::IdentifierExpression *i = AST::cast<AST::IdentifierExpression *>(n)) {
381 return i->name.toString();
383 return asWritten.toString();
387 QDeclarativeJS::AST::Node *QDeclarativeScript::Variant::asAST() const
389 if (type() == Script)
395 bool QDeclarativeScript::Variant::isStringList() const
400 if (type() != Script || !n)
403 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
407 AST::ElementList *elements = array->elements;
411 if (!AST::cast<AST::StringLiteral *>(elements->expression))
414 elements = elements->next;
420 QStringList QDeclarativeScript::Variant::asStringList() const
428 AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
432 AST::ElementList *elements = array->elements;
435 AST::StringLiteral *string = AST::cast<AST::StringLiteral *>(elements->expression);
437 return QStringList();
438 rv.append(string->value.toString());
440 elements = elements->next;
447 // Actual parser classes
449 void QDeclarativeScript::Import::extractVersion(int *maj, int *min) const
451 *maj = -1; *min = -1;
453 if (!version.isEmpty()) {
454 int dot = version.indexOf(QLatin1Char('.'));
456 *maj = version.toInt();
459 *maj = version.left(dot).toInt();
460 *min = version.mid(dot+1).toInt();
467 class ProcessAST: protected AST::Visitor
470 State() : object(0), property(0) {}
471 State(QDeclarativeScript::Object *o) : object(o), property(0) {}
472 State(QDeclarativeScript::Object *o, Property *p) : object(o), property(p) {}
474 QDeclarativeScript::Object *object;
478 struct StateStack : public QStack<State>
480 void pushObject(QDeclarativeScript::Object *obj)
485 void pushProperty(const QString &name, const LocationSpan &location)
487 const State &state = top();
488 if (state.property) {
489 State s(state.property->getValue(location),
490 state.property->getValue(location)->getProperty(name));
491 s.property->location = location;
494 State s(state.object, state.object->getProperty(name));
496 s.property->location = location;
501 void pushProperty(const QStringRef &name, const LocationSpan &location)
503 const State &state = top();
504 if (state.property) {
505 State s(state.property->getValue(location),
506 state.property->getValue(location)->getProperty(name));
507 s.property->location = location;
510 State s(state.object, state.object->getProperty(name));
512 s.property->location = location;
519 ProcessAST(QDeclarativeScript::Parser *parser);
520 virtual ~ProcessAST();
522 void operator()(const QString &code, AST::Node *node);
526 QDeclarativeScript::Object *defineObjectBinding(AST::UiQualifiedId *propertyName, bool onAssignment,
527 const QString &objectType,
528 AST::SourceLocation typeLocation,
529 LocationSpan location,
530 AST::UiObjectInitializer *initializer = 0);
532 QDeclarativeScript::Variant getVariant(AST::Statement *stmt);
533 QDeclarativeScript::Variant getVariant(AST::ExpressionNode *expr);
535 LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
536 LocationSpan location(AST::UiQualifiedId *);
538 using AST::Visitor::visit;
539 using AST::Visitor::endVisit;
541 virtual bool visit(AST::UiProgram *node);
542 virtual bool visit(AST::UiImport *node);
543 virtual bool visit(AST::UiObjectDefinition *node);
544 virtual bool visit(AST::UiPublicMember *node);
545 virtual bool visit(AST::UiObjectBinding *node);
547 virtual bool visit(AST::UiScriptBinding *node);
548 virtual bool visit(AST::UiArrayBinding *node);
549 virtual bool visit(AST::UiSourceElement *node);
551 void accept(AST::Node *node);
553 QString asString(AST::UiQualifiedId *node) const;
555 const State state() const;
556 QDeclarativeScript::Object *currentObject() const;
557 Property *currentProperty() const;
559 QString qualifiedNameId() const;
561 QString textAt(const AST::SourceLocation &loc) const
562 { return _contents->mid(loc.offset, loc.length); }
564 QStringRef textRefAt(const AST::SourceLocation &loc) const
565 { return QStringRef(_contents, loc.offset, loc.length); }
567 QString textAt(const AST::SourceLocation &first,
568 const AST::SourceLocation &last) const
569 { return _contents->mid(first.offset, last.offset + last.length - first.offset); }
571 QStringRef textRefAt(const AST::SourceLocation &first,
572 const AST::SourceLocation &last) const
573 { return QStringRef(_contents, first.offset, last.offset + last.length - first.offset); }
575 QString asString(AST::ExpressionNode *expr)
580 return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
583 QStringRef asStringRef(AST::ExpressionNode *expr)
588 return textRefAt(expr->firstSourceLocation(), expr->lastSourceLocation());
591 QString asString(AST::Statement *stmt)
596 QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
597 s += QLatin1Char('\n');
601 QStringRef asStringRef(AST::Statement *stmt)
606 return textRefAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
610 QDeclarativeScript::Parser *_parser;
611 StateStack _stateStack;
613 const QString *_contents;
616 ProcessAST::ProcessAST(QDeclarativeScript::Parser *parser)
621 ProcessAST::~ProcessAST()
625 void ProcessAST::operator()(const QString &code, AST::Node *node)
631 void ProcessAST::accept(AST::Node *node)
633 AST::Node::acceptChild(node, this);
636 const ProcessAST::State ProcessAST::state() const
638 if (_stateStack.isEmpty())
641 return _stateStack.back();
644 QDeclarativeScript::Object *ProcessAST::currentObject() const
646 return state().object;
649 Property *ProcessAST::currentProperty() const
651 return state().property;
654 QString ProcessAST::qualifiedNameId() const
656 return _scope.join(QLatin1String("/"));
659 QString ProcessAST::asString(AST::UiQualifiedId *node) const
663 for (AST::UiQualifiedId *it = node; it; it = it->next) {
664 s.append(it->name.toString());
667 s.append(QLatin1Char('.'));
673 QDeclarativeScript::Object *
674 ProcessAST::defineObjectBinding(AST::UiQualifiedId *propertyName,
676 const QString &objectType,
677 AST::SourceLocation typeLocation,
678 LocationSpan location,
679 AST::UiObjectInitializer *initializer)
681 int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
682 bool isType = !objectType.isEmpty() &&
683 (objectType.at(0).isUpper() ||
684 (lastTypeDot >= 0 && objectType.at(lastTypeDot+1).isUpper()));
686 int propertyCount = 0;
687 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
689 _stateStack.pushProperty(name->name,
690 this->location(name));
693 if (!onAssignment && propertyCount && currentProperty() && !currentProperty()->values.isEmpty()) {
694 QDeclarativeError error;
695 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
696 error.setLine(this->location(propertyName).start.line);
697 error.setColumn(this->location(propertyName).start.column);
698 _parser->_errors << error;
704 if(propertyCount || !currentObject()) {
705 QDeclarativeError error;
706 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected type name"));
707 error.setLine(typeLocation.startLine);
708 error.setColumn(typeLocation.startColumn);
709 _parser->_errors << error;
713 LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
715 loc = ProcessAST::location(propertyName);
717 _stateStack.pushProperty(objectType, loc);
726 QString resolvableObjectType = objectType;
727 if (lastTypeDot >= 0)
728 resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
730 QDeclarativeScript::Object *obj = _parser->_pool.New<QDeclarativeScript::Object>();
732 QDeclarativeScript::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
733 obj->type = typeRef->id;
735 typeRef->refObjects.append(obj);
737 // XXX this doesn't do anything (_scope never builds up)
738 _scope.append(resolvableObjectType);
739 obj->typeName = qualifiedNameId();
742 obj->location = location;
745 Property *prop = currentProperty();
746 QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
748 v->location = obj->location;
754 while (propertyCount--)
759 if (! _parser->tree()) {
760 _parser->setTree(obj);
762 const State state = _stateStack.top();
763 QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
765 v->location = obj->location;
766 if (state.property) {
767 state.property->addValue(v);
769 Property *defaultProp = state.object->getDefaultProperty();
770 if (defaultProp->location.start.line == -1) {
771 defaultProp->location = v->location;
772 defaultProp->location.end = defaultProp->location.start;
773 defaultProp->location.range.length = 0;
775 defaultProp->addValue(v);
780 _stateStack.pushObject(obj);
788 LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
790 return location(id->identifierToken, id->identifierToken);
793 LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
796 rv.start.line = start.startLine;
797 rv.start.column = start.startColumn;
798 rv.end.line = end.startLine;
799 rv.end.column = end.startColumn + end.length - 1;
800 rv.range.offset = start.offset;
801 rv.range.length = end.offset + end.length - start.offset;
805 // UiProgram: UiImportListOpt UiObjectMemberList ;
806 bool ProcessAST::visit(AST::UiProgram *node)
808 accept(node->imports);
809 accept(node->members->member);
813 // UiImport: T_IMPORT T_STRING_LITERAL ;
814 bool ProcessAST::visit(AST::UiImport *node)
817 QDeclarativeScript::Import import;
819 if (!node->fileName.isNull()) {
820 uri = node->fileName.toString();
822 if (uri.endsWith(QLatin1String(".js"))) {
823 import.type = QDeclarativeScript::Import::Script;
825 import.type = QDeclarativeScript::Import::File;
828 import.type = QDeclarativeScript::Import::Library;
829 uri = asString(node->importUri);
832 AST::SourceLocation startLoc = node->importToken;
833 AST::SourceLocation endLoc = node->semicolonToken;
836 if (!node->importId.isNull()) {
837 import.qualifier = node->importId.toString();
838 if (!import.qualifier.at(0).isUpper()) {
839 QDeclarativeError error;
840 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Invalid import qualifier ID"));
841 error.setLine(node->importIdToken.startLine);
842 error.setColumn(node->importIdToken.startColumn);
843 _parser->_errors << error;
846 if (import.qualifier == QLatin1String("Qt")) {
847 QDeclarativeError error;
848 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Reserved name \"Qt\" cannot be used as an qualifier"));
849 error.setLine(node->importIdToken.startLine);
850 error.setColumn(node->importIdToken.startColumn);
851 _parser->_errors << error;
855 // Check for script qualifier clashes
856 bool isScript = import.type == QDeclarativeScript::Import::Script;
857 for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
858 const QDeclarativeScript::Import &other = _parser->_imports.at(ii);
859 bool otherIsScript = other.type == QDeclarativeScript::Import::Script;
861 if ((isScript || otherIsScript) && import.qualifier == other.qualifier) {
862 QDeclarativeError error;
863 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Script import qualifiers must be unique."));
864 error.setLine(node->importIdToken.startLine);
865 error.setColumn(node->importIdToken.startColumn);
866 _parser->_errors << error;
871 } else if (import.type == QDeclarativeScript::Import::Script) {
872 QDeclarativeError error;
873 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Script import requires a qualifier"));
874 error.setLine(node->fileNameToken.startLine);
875 error.setColumn(node->fileNameToken.startColumn);
876 _parser->_errors << error;
880 if (node->versionToken.isValid()) {
881 import.version = textAt(node->versionToken);
882 } else if (import.type == QDeclarativeScript::Import::Library) {
883 QDeclarativeError error;
884 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Library import requires a version"));
885 error.setLine(node->importIdToken.startLine);
886 error.setColumn(node->importIdToken.startColumn);
887 _parser->_errors << error;
892 import.location = location(startLoc, endLoc);
895 _parser->_imports << import;
900 bool ProcessAST::visit(AST::UiPublicMember *node)
902 static const struct TypeNameToType {
905 Object::DynamicProperty::Type type;
908 } propTypeNameToTypes[] = {
909 { "int", strlen("int"), Object::DynamicProperty::Int, "int", strlen("int") },
910 { "bool", strlen("bool"), Object::DynamicProperty::Bool, "bool", strlen("bool") },
911 { "double", strlen("double"), Object::DynamicProperty::Real, "double", strlen("double") },
912 { "real", strlen("real"), Object::DynamicProperty::Real, "qreal", strlen("qreal") },
913 { "string", strlen("string"), Object::DynamicProperty::String, "QString", strlen("QString") },
914 { "url", strlen("url"), Object::DynamicProperty::Url, "QUrl", strlen("QUrl") },
915 { "color", strlen("color"), Object::DynamicProperty::Color, "QColor", strlen("QColor") },
916 // Internally QTime, QDate and QDateTime are all supported.
917 // To be more consistent with JavaScript we expose only
918 // QDateTime as it matches closely with the Date JS type.
919 // We also call it "date" to match.
920 // { "time", strlen("time"), Object::DynamicProperty::Time, "QTime", strlen("QTime") },
921 // { "date", strlen("date"), Object::DynamicProperty::Date, "QDate", strlen("QDate") },
922 { "date", strlen("date"), Object::DynamicProperty::DateTime, "QDateTime", strlen("QDateTime") },
923 { "variant", strlen("variant"), Object::DynamicProperty::Variant, "QVariant", strlen("QVariant") },
924 { "var", strlen("var"), Object::DynamicProperty::Var, "QVariant", strlen("QVariant") }
926 static const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
927 sizeof(propTypeNameToTypes[0]);
929 if(node->type == AST::UiPublicMember::Signal) {
930 Object::DynamicSignal *signal = _parser->_pool.New<Object::DynamicSignal>();
931 signal->name = node->name;
933 AST::UiParameterList *p = node->parameters;
935 while (p) { paramLength++; p = p->next; }
936 p = node->parameters;
939 signal->parameterTypes = _parser->_pool.NewRawList<QHashedCStringRef>(paramLength);
940 signal->parameterNames = _parser->_pool.NewRawList<QHashedStringRef>(paramLength);
945 const QStringRef &memberType = p->type;
947 const TypeNameToType *type = 0;
948 for(int typeIndex = 0; typeIndex < propTypeNameToTypesCount; ++typeIndex) {
949 const TypeNameToType *t = propTypeNameToTypes + typeIndex;
950 if (t->nameLength == memberType.length() &&
951 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
958 QDeclarativeError error;
959 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected parameter type"));
960 error.setLine(node->typeToken.startLine);
961 error.setColumn(node->typeToken.startColumn);
962 _parser->_errors << error;
966 signal->parameterTypes[index] = QHashedCStringRef(type->qtName, type->qtNameLength);
967 signal->parameterNames[index] = QHashedStringRef(p->name);
972 signal->location = location(node->typeToken, node->semicolonToken);
973 _stateStack.top().object->dynamicSignals.append(signal);
975 const QStringRef &memberType = node->memberType;
976 const QStringRef &name = node->name;
978 bool typeFound = false;
979 Object::DynamicProperty::Type type;
981 if ((unsigned)memberType.length() == strlen("alias") &&
982 QHashedString::compare(memberType.constData(), "alias", strlen("alias"))) {
983 type = Object::DynamicProperty::Alias;
987 for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
988 const TypeNameToType *t = propTypeNameToTypes + ii;
989 if (t->nameLength == memberType.length() &&
990 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
996 if (!typeFound && memberType.at(0).isUpper()) {
997 const QStringRef &typeModifier = node->typeModifier;
999 if (typeModifier.isEmpty()) {
1000 type = Object::DynamicProperty::Custom;
1001 } else if((unsigned)typeModifier.length() == strlen("list") &&
1002 QHashedString::compare(typeModifier.constData(), "list", strlen("list"))) {
1003 type = Object::DynamicProperty::CustomList;
1005 QDeclarativeError error;
1006 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Invalid property type modifier"));
1007 error.setLine(node->typeModifierToken.startLine);
1008 error.setColumn(node->typeModifierToken.startColumn);
1009 _parser->_errors << error;
1013 } else if (!node->typeModifier.isNull()) {
1014 QDeclarativeError error;
1015 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Unexpected property type modifier"));
1016 error.setLine(node->typeModifierToken.startLine);
1017 error.setColumn(node->typeModifierToken.startColumn);
1018 _parser->_errors << error;
1023 QDeclarativeError error;
1024 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected property type"));
1025 error.setLine(node->typeToken.startLine);
1026 error.setColumn(node->typeToken.startColumn);
1027 _parser->_errors << error;
1031 Object::DynamicProperty *property = _parser->_pool.New<Object::DynamicProperty>();
1032 property->isDefaultProperty = node->isDefaultMember;
1033 property->isReadOnly = node->isReadonlyMember;
1034 property->type = type;
1035 if (type >= Object::DynamicProperty::Custom) {
1036 QDeclarativeScript::TypeReference *typeRef =
1037 _parser->findOrCreateType(memberType.toString());
1038 typeRef->refObjects.append(_stateStack.top().object);
1039 property->customType = memberType;
1042 property->name = QHashedStringRef(name);
1043 property->location = location(node->firstSourceLocation(),
1044 node->lastSourceLocation());
1046 if (node->statement) { // default value
1047 property->defaultValue = _parser->_pool.New<Property>();
1048 property->defaultValue->parent = _stateStack.top().object;
1049 property->defaultValue->location =
1050 location(node->statement->firstSourceLocation(),
1051 node->statement->lastSourceLocation());
1052 QDeclarativeScript::Value *value = _parser->_pool.New<QDeclarativeScript::Value>();
1053 value->location = location(node->statement->firstSourceLocation(),
1054 node->statement->lastSourceLocation());
1055 value->value = getVariant(node->statement);
1056 property->defaultValue->values.append(value);
1059 _stateStack.top().object->dynamicProperties.append(property);
1061 // process QML-like initializers (e.g. property Object o: Object {})
1062 accept(node->binding);
1069 // UiObjectMember: UiQualifiedId UiObjectInitializer ;
1070 bool ProcessAST::visit(AST::UiObjectDefinition *node)
1072 LocationSpan l = location(node->firstSourceLocation(),
1073 node->lastSourceLocation());
1075 const QString objectType = asString(node->qualifiedTypeNameId);
1076 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1078 defineObjectBinding(/*propertyName = */ 0, false, objectType,
1079 typeLocation, l, node->initializer);
1085 // UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
1086 bool ProcessAST::visit(AST::UiObjectBinding *node)
1088 LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
1089 node->initializer->rbraceToken);
1091 const QString objectType = asString(node->qualifiedTypeNameId);
1092 const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1094 defineObjectBinding(node->qualifiedId, node->hasOnToken, objectType,
1095 typeLocation, l, node->initializer);
1100 QDeclarativeScript::Variant ProcessAST::getVariant(AST::Statement *stmt)
1103 if (AST::ExpressionStatement *exprStmt = AST::cast<AST::ExpressionStatement *>(stmt))
1104 return getVariant(exprStmt->expression);
1106 return QDeclarativeScript::Variant(asStringRef(stmt), stmt);
1109 return QDeclarativeScript::Variant();
1112 QDeclarativeScript::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
1114 if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
1115 return QDeclarativeScript::Variant(lit);
1116 } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
1117 return QDeclarativeScript::Variant(true);
1118 } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
1119 return QDeclarativeScript::Variant(false);
1120 } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
1121 return QDeclarativeScript::Variant(lit->value, asStringRef(expr));
1124 if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
1125 if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
1126 return QDeclarativeScript::Variant(-lit->value, asStringRef(expr));
1130 return QDeclarativeScript::Variant(asStringRef(expr), expr);
1135 // UiObjectMember: UiQualifiedId T_COLON Statement ;
1136 bool ProcessAST::visit(AST::UiScriptBinding *node)
1138 int propertyCount = 0;
1139 AST::UiQualifiedId *propertyName = node->qualifiedId;
1140 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1142 _stateStack.pushProperty(name->name,
1146 Property *prop = currentProperty();
1148 if (!prop->values.isEmpty()) {
1149 QDeclarativeError error;
1150 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
1151 error.setLine(this->location(propertyName).start.line);
1152 error.setColumn(this->location(propertyName).start.column);
1153 _parser->_errors << error;
1157 QDeclarativeScript::Variant primitive;
1159 if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
1160 primitive = getVariant(stmt->expression);
1161 } else { // do binding
1162 primitive = QDeclarativeScript::Variant(asStringRef(node->statement), node->statement);
1165 prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
1166 prop->location.range.offset = node->qualifiedId->identifierToken.offset;
1167 QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
1168 v->value = primitive;
1169 v->location = location(node->statement->firstSourceLocation(),
1170 node->statement->lastSourceLocation());
1174 while (propertyCount--)
1180 // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
1181 bool ProcessAST::visit(AST::UiArrayBinding *node)
1183 int propertyCount = 0;
1184 AST::UiQualifiedId *propertyName = node->qualifiedId;
1185 for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1187 _stateStack.pushProperty(name->name,
1191 Property* prop = currentProperty();
1193 if (!prop->values.isEmpty()) {
1194 QDeclarativeError error;
1195 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
1196 error.setLine(this->location(propertyName).start.line);
1197 error.setColumn(this->location(propertyName).start.column);
1198 _parser->_errors << error;
1202 accept(node->members);
1204 // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
1205 prop->listValueRange.offset = node->lbracketToken.offset;
1206 prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
1208 while (propertyCount--)
1214 bool ProcessAST::visit(AST::UiSourceElement *node)
1216 QDeclarativeScript::Object *obj = currentObject();
1218 if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
1220 Object::DynamicSlot *slot = _parser->_pool.New<Object::DynamicSlot>();
1221 slot->location = location(funDecl->firstSourceLocation(), funDecl->lastSourceLocation());
1223 AST::FormalParameterList *f = funDecl->formals;
1225 slot->parameterNames << f->name.toUtf8();
1229 AST::SourceLocation loc = funDecl->rparenToken;
1230 loc.offset = loc.end();
1231 loc.startColumn += 1;
1232 QString body = textAt(loc, funDecl->rbraceToken);
1233 slot->name = funDecl->name;
1235 obj->dynamicSlots.append(slot);
1238 QDeclarativeError error;
1239 error.setDescription(QCoreApplication::translate("QDeclarativeParser","JavaScript declaration outside Script element"));
1240 error.setLine(node->firstSourceLocation().startLine);
1241 error.setColumn(node->firstSourceLocation().startColumn);
1242 _parser->_errors << error;
1247 } // end of anonymous namespace
1250 QDeclarativeScript::Parser::Parser()
1256 QDeclarativeScript::Parser::~Parser()
1261 namespace QDeclarativeScript {
1262 class ParserJsASTData
1265 ParserJsASTData(const QString &filename)
1266 : filename(filename) {}
1273 bool QDeclarativeScript::Parser::parse(const QByteArray &qmldata, const QUrl &url)
1277 const QString fileName = url.toString();
1278 _scriptFile = fileName;
1280 QTextStream stream(qmldata, QIODevice::ReadOnly);
1281 #ifndef QT_NO_TEXTCODEC
1282 stream.setCodec("UTF-8");
1284 QString *code = _pool.NewString(stream.readAll());
1286 data = new QDeclarativeScript::ParserJsASTData(fileName);
1288 Lexer lexer(&data->engine);
1289 lexer.setCode(*code, /*line = */ 1);
1291 QDeclarativeJS::Parser parser(&data->engine);
1293 if (! parser.parse() || !_errors.isEmpty()) {
1295 // Extract errors from the parser
1296 foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
1301 QDeclarativeError error;
1303 error.setDescription(m.message);
1304 error.setLine(m.loc.startLine);
1305 error.setColumn(m.loc.startColumn);
1311 if (_errors.isEmpty()) {
1312 ProcessAST process(this);
1313 process(*code, parser.ast());
1315 // Set the url for process errors
1316 for(int ii = 0; ii < _errors.count(); ++ii)
1317 _errors[ii].setUrl(url);
1320 return _errors.isEmpty();
1323 QList<QDeclarativeScript::TypeReference*> QDeclarativeScript::Parser::referencedTypes() const
1328 QDeclarativeScript::Object *QDeclarativeScript::Parser::tree() const
1333 QList<QDeclarativeScript::Import> QDeclarativeScript::Parser::imports() const
1338 QList<QDeclarativeError> QDeclarativeScript::Parser::errors() const
1343 static void replaceWithSpace(QString &str, int idx, int n)
1345 QChar *data = str.data() + idx;
1346 const QChar space(QLatin1Char(' '));
1347 for (int ii = 0; ii < n; ++ii)
1351 static QDeclarativeScript::LocationSpan
1352 locationFromLexer(const QDeclarativeJS::Lexer &lex, int startLine, int startColumn, int startOffset)
1354 QDeclarativeScript::LocationSpan l;
1356 l.start.line = startLine; l.start.column = startColumn;
1357 l.end.line = lex.tokenEndLine(); l.end.column = lex.tokenEndColumn();
1358 l.range.offset = startOffset;
1359 l.range.length = lex.tokenOffset() + lex.tokenLength() - startOffset;
1365 Searches for ".pragma <value>" declarations within \a script. Currently supported pragmas
1369 QDeclarativeScript::Object::ScriptBlock::Pragmas QDeclarativeScript::Parser::extractPragmas(QString &script)
1371 QDeclarativeScript::Object::ScriptBlock::Pragmas rv = QDeclarativeScript::Object::ScriptBlock::None;
1373 const QString pragma(QLatin1String("pragma"));
1374 const QString library(QLatin1String("library"));
1376 QDeclarativeJS::Lexer l(0);
1377 l.setCode(script, 0);
1379 int token = l.lex();
1382 if (token != QDeclarativeJSGrammar::T_DOT)
1385 int startOffset = l.tokenOffset();
1386 int startLine = l.tokenStartLine();
1390 if (token != QDeclarativeJSGrammar::T_IDENTIFIER ||
1391 l.tokenStartLine() != startLine ||
1392 script.mid(l.tokenOffset(), l.tokenLength()) != pragma)
1397 if (token != QDeclarativeJSGrammar::T_IDENTIFIER ||
1398 l.tokenStartLine() != startLine)
1401 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1402 int endOffset = l.tokenLength() + l.tokenOffset();
1405 if (l.tokenStartLine() == startLine)
1408 if (pragmaValue == library) {
1409 rv |= QDeclarativeScript::Object::ScriptBlock::Shared;
1410 replaceWithSpace(script, startOffset, endOffset - startOffset);
1418 #define CHECK_LINE if (l.tokenStartLine() != startLine) return rv;
1419 #define CHECK_TOKEN(t) if (token != QDeclarativeJSGrammar:: t) return rv;
1421 static const int uriTokens[] = {
1422 QDeclarativeJSGrammar::T_IDENTIFIER,
1423 QDeclarativeJSGrammar::T_PROPERTY,
1424 QDeclarativeJSGrammar::T_SIGNAL,
1425 QDeclarativeJSGrammar::T_READONLY,
1426 QDeclarativeJSGrammar::T_ON,
1427 QDeclarativeJSGrammar::T_BREAK,
1428 QDeclarativeJSGrammar::T_CASE,
1429 QDeclarativeJSGrammar::T_CATCH,
1430 QDeclarativeJSGrammar::T_CONTINUE,
1431 QDeclarativeJSGrammar::T_DEFAULT,
1432 QDeclarativeJSGrammar::T_DELETE,
1433 QDeclarativeJSGrammar::T_DO,
1434 QDeclarativeJSGrammar::T_ELSE,
1435 QDeclarativeJSGrammar::T_FALSE,
1436 QDeclarativeJSGrammar::T_FINALLY,
1437 QDeclarativeJSGrammar::T_FOR,
1438 QDeclarativeJSGrammar::T_FUNCTION,
1439 QDeclarativeJSGrammar::T_IF,
1440 QDeclarativeJSGrammar::T_IN,
1441 QDeclarativeJSGrammar::T_INSTANCEOF,
1442 QDeclarativeJSGrammar::T_NEW,
1443 QDeclarativeJSGrammar::T_NULL,
1444 QDeclarativeJSGrammar::T_RETURN,
1445 QDeclarativeJSGrammar::T_SWITCH,
1446 QDeclarativeJSGrammar::T_THIS,
1447 QDeclarativeJSGrammar::T_THROW,
1448 QDeclarativeJSGrammar::T_TRUE,
1449 QDeclarativeJSGrammar::T_TRY,
1450 QDeclarativeJSGrammar::T_TYPEOF,
1451 QDeclarativeJSGrammar::T_VAR,
1452 QDeclarativeJSGrammar::T_VOID,
1453 QDeclarativeJSGrammar::T_WHILE,
1454 QDeclarativeJSGrammar::T_CONST,
1455 QDeclarativeJSGrammar::T_DEBUGGER,
1456 QDeclarativeJSGrammar::T_RESERVED_WORD,
1457 QDeclarativeJSGrammar::T_WITH,
1459 QDeclarativeJSGrammar::EOF_SYMBOL
1461 static inline bool isUriToken(int token)
1463 const int *current = uriTokens;
1464 while (*current != QDeclarativeJSGrammar::EOF_SYMBOL) {
1465 if (*current == token)
1472 QDeclarativeScript::Parser::JavaScriptMetaData QDeclarativeScript::Parser::extractMetaData(QString &script)
1474 JavaScriptMetaData rv;
1476 QDeclarativeScript::Object::ScriptBlock::Pragmas &pragmas = rv.pragmas;
1478 const QString pragma(QLatin1String("pragma"));
1479 const QString js(QLatin1String(".js"));
1480 const QString library(QLatin1String("library"));
1482 QDeclarativeJS::Lexer l(0);
1483 l.setCode(script, 0);
1485 int token = l.lex();
1488 if (token != QDeclarativeJSGrammar::T_DOT)
1491 int startOffset = l.tokenOffset();
1492 int startLine = l.tokenStartLine();
1493 int startColumn = l.tokenStartColumn();
1499 if (token == QDeclarativeJSGrammar::T_IMPORT) {
1501 // .import <URI> <Version> as <Identifier>
1502 // .import <file.js> as <Identifier>
1508 if (token == QDeclarativeJSGrammar::T_STRING_LITERAL) {
1510 QString file = l.tokenText();
1512 if (!file.endsWith(js))
1522 CHECK_TOKEN(T_IDENTIFIER);
1525 int endOffset = l.tokenLength() + l.tokenOffset();
1527 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1529 if (!importId.at(0).isUpper())
1532 QDeclarativeScript::LocationSpan location =
1533 locationFromLexer(l, startLine, startColumn, startOffset);
1536 if (l.tokenStartLine() == startLine)
1539 replaceWithSpace(script, startOffset, endOffset - startOffset);
1542 import.type = Import::Script;
1544 import.qualifier = importId;
1545 import.location = location;
1547 rv.imports << import;
1554 if (!isUriToken(token))
1557 uri.append(l.tokenText());
1561 if (token != QDeclarativeJSGrammar::T_DOT)
1564 uri.append(QLatin1Char('.'));
1570 CHECK_TOKEN(T_NUMERIC_LITERAL);
1571 version = script.mid(l.tokenOffset(), l.tokenLength());
1580 CHECK_TOKEN(T_IDENTIFIER);
1583 int endOffset = l.tokenLength() + l.tokenOffset();
1585 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1587 if (!importId.at(0).isUpper())
1590 QDeclarativeScript::LocationSpan location =
1591 locationFromLexer(l, startLine, startColumn, startOffset);
1594 if (l.tokenStartLine() == startLine)
1597 replaceWithSpace(script, startOffset, endOffset - startOffset);
1600 import.type = Import::Library;
1602 import.version = version;
1603 import.qualifier = importId;
1604 import.location = location;
1606 rv.imports << import;
1609 } else if (token == QDeclarativeJSGrammar::T_IDENTIFIER &&
1610 script.mid(l.tokenOffset(), l.tokenLength()) == pragma) {
1614 CHECK_TOKEN(T_IDENTIFIER);
1617 QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1618 int endOffset = l.tokenLength() + l.tokenOffset();
1620 if (pragmaValue == library) {
1621 pragmas |= QDeclarativeScript::Object::ScriptBlock::Shared;
1622 replaceWithSpace(script, startOffset, endOffset - startOffset);
1628 if (l.tokenStartLine() == startLine)
1638 void QDeclarativeScript::Parser::clear()
1641 qDeleteAll(_refTypes);
1653 QDeclarativeScript::TypeReference *QDeclarativeScript::Parser::findOrCreateType(const QString &name)
1655 TypeReference *type = 0;
1657 for (; i < _refTypes.size(); ++i) {
1658 if (_refTypes.at(i)->name == name) {
1659 type = _refTypes.at(i);
1664 type = new TypeReference(i, name);
1665 _refTypes.append(type);
1671 void QDeclarativeScript::Parser::setTree(QDeclarativeScript::Object *tree)