src/declarative/qml/qdeclarativescriptparser.cpp
branchGCC_SURGE
changeset 31 5daf16870df6
parent 30 5dc02b23752f
child 33 3e2da88830cd
equal deleted inserted replaced
27:93b982ccede2 31:5daf16870df6
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 #include "private/qdeclarativescriptparser_p.h"
       
    43 
       
    44 #include "private/qdeclarativeparser_p.h"
       
    45 #include "parser/qdeclarativejsengine_p.h"
       
    46 #include "parser/qdeclarativejsparser_p.h"
       
    47 #include "parser/qdeclarativejslexer_p.h"
       
    48 #include "parser/qdeclarativejsnodepool_p.h"
       
    49 #include "parser/qdeclarativejsastvisitor_p.h"
       
    50 #include "parser/qdeclarativejsast_p.h"
       
    51 #include "private/qdeclarativerewrite_p.h"
       
    52 
       
    53 #include <QStack>
       
    54 #include <QCoreApplication>
       
    55 #include <QtDebug>
       
    56 
       
    57 QT_BEGIN_NAMESPACE
       
    58 
       
    59 using namespace QDeclarativeJS;
       
    60 using namespace QDeclarativeParser;
       
    61 
       
    62 namespace {
       
    63 
       
    64 class ProcessAST: protected AST::Visitor
       
    65 {
       
    66     struct State {
       
    67         State() : object(0), property(0) {}
       
    68         State(Object *o) : object(o), property(0) {}
       
    69         State(Object *o, Property *p) : object(o), property(p) {}
       
    70 
       
    71         Object *object;
       
    72         Property *property;
       
    73     };
       
    74 
       
    75     struct StateStack : public QStack<State>
       
    76     {
       
    77         void pushObject(Object *obj)
       
    78         {
       
    79             push(State(obj));
       
    80         }
       
    81 
       
    82         void pushProperty(const QString &name, const LocationSpan &location)
       
    83         {
       
    84             const State &state = top();
       
    85             if (state.property) {
       
    86                 State s(state.property->getValue(location),
       
    87                         state.property->getValue(location)->getProperty(name.toUtf8()));
       
    88                 s.property->location = location;
       
    89                 push(s);
       
    90             } else {
       
    91                 State s(state.object,
       
    92                         state.object->getProperty(name.toUtf8()));
       
    93 
       
    94                 s.property->location = location;
       
    95                 push(s);
       
    96             }
       
    97         }
       
    98     };
       
    99 
       
   100 public:
       
   101     ProcessAST(QDeclarativeScriptParser *parser);
       
   102     virtual ~ProcessAST();
       
   103 
       
   104     void operator()(const QString &code, AST::Node *node);
       
   105 
       
   106 protected:
       
   107 
       
   108     Object *defineObjectBinding(AST::UiQualifiedId *propertyName, bool onAssignment,
       
   109                                 const QString &objectType,
       
   110                                 AST::SourceLocation typeLocation,
       
   111                                 LocationSpan location,
       
   112                                 AST::UiObjectInitializer *initializer = 0);
       
   113 
       
   114     QDeclarativeParser::Variant getVariant(AST::ExpressionNode *expr);
       
   115 
       
   116     LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
       
   117     LocationSpan location(AST::UiQualifiedId *);
       
   118 
       
   119     using AST::Visitor::visit;
       
   120     using AST::Visitor::endVisit;
       
   121 
       
   122     virtual bool visit(AST::UiProgram *node);
       
   123     virtual bool visit(AST::UiImport *node);
       
   124     virtual bool visit(AST::UiObjectDefinition *node);
       
   125     virtual bool visit(AST::UiPublicMember *node);
       
   126     virtual bool visit(AST::UiObjectBinding *node);
       
   127 
       
   128     virtual bool visit(AST::UiScriptBinding *node);
       
   129     virtual bool visit(AST::UiArrayBinding *node);
       
   130     virtual bool visit(AST::UiSourceElement *node);
       
   131 
       
   132     void accept(AST::Node *node);
       
   133 
       
   134     QString asString(AST::UiQualifiedId *node) const;
       
   135 
       
   136     const State state() const;
       
   137     Object *currentObject() const;
       
   138     Property *currentProperty() const;
       
   139 
       
   140     QString qualifiedNameId() const;
       
   141 
       
   142     QString textAt(const AST::SourceLocation &loc) const
       
   143     { return _contents.mid(loc.offset, loc.length); }
       
   144 
       
   145 
       
   146     QString textAt(const AST::SourceLocation &first,
       
   147                    const AST::SourceLocation &last) const
       
   148     { return _contents.mid(first.offset, last.offset + last.length - first.offset); }
       
   149 
       
   150     QString asString(AST::ExpressionNode *expr)
       
   151     {
       
   152         if (! expr)
       
   153             return QString();
       
   154 
       
   155         return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
       
   156     }
       
   157 
       
   158     QString asString(AST::Statement *stmt)
       
   159     {
       
   160         if (! stmt)
       
   161             return QString();
       
   162 
       
   163         QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
       
   164         s += QLatin1Char('\n');
       
   165         return s;
       
   166     }
       
   167 
       
   168 private:
       
   169     QDeclarativeScriptParser *_parser;
       
   170     StateStack _stateStack;
       
   171     QStringList _scope;
       
   172     QString _contents;
       
   173 
       
   174     inline bool isSignalProperty(const QByteArray &propertyName) const {
       
   175         return (propertyName.length() >= 3 && propertyName.startsWith("on") &&
       
   176                 ('A' <= propertyName.at(2) && 'Z' >= propertyName.at(2)));
       
   177     }
       
   178 
       
   179 };
       
   180 
       
   181 ProcessAST::ProcessAST(QDeclarativeScriptParser *parser)
       
   182     : _parser(parser)
       
   183 {
       
   184 }
       
   185 
       
   186 ProcessAST::~ProcessAST()
       
   187 {
       
   188 }
       
   189 
       
   190 void ProcessAST::operator()(const QString &code, AST::Node *node)
       
   191 {
       
   192     _contents = code;
       
   193     accept(node);
       
   194 }
       
   195 
       
   196 void ProcessAST::accept(AST::Node *node)
       
   197 {
       
   198     AST::Node::acceptChild(node, this);
       
   199 }
       
   200 
       
   201 const ProcessAST::State ProcessAST::state() const
       
   202 {
       
   203     if (_stateStack.isEmpty())
       
   204         return State();
       
   205 
       
   206     return _stateStack.back();
       
   207 }
       
   208 
       
   209 Object *ProcessAST::currentObject() const
       
   210 {
       
   211     return state().object;
       
   212 }
       
   213 
       
   214 Property *ProcessAST::currentProperty() const
       
   215 {
       
   216     return state().property;
       
   217 }
       
   218 
       
   219 QString ProcessAST::qualifiedNameId() const
       
   220 {
       
   221     return _scope.join(QLatin1String("/"));
       
   222 }
       
   223 
       
   224 QString ProcessAST::asString(AST::UiQualifiedId *node) const
       
   225 {
       
   226     QString s;
       
   227 
       
   228     for (AST::UiQualifiedId *it = node; it; it = it->next) {
       
   229         s.append(it->name->asString());
       
   230 
       
   231         if (it->next)
       
   232             s.append(QLatin1Char('.'));
       
   233     }
       
   234 
       
   235     return s;
       
   236 }
       
   237 
       
   238 Object *
       
   239 ProcessAST::defineObjectBinding(AST::UiQualifiedId *propertyName,
       
   240                                 bool onAssignment,
       
   241                                 const QString &objectType,
       
   242                                 AST::SourceLocation typeLocation,
       
   243                                 LocationSpan location,
       
   244                                 AST::UiObjectInitializer *initializer)
       
   245 {
       
   246     int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
       
   247     bool isType = !objectType.isEmpty() &&
       
   248                     (objectType.at(0).isUpper() ||
       
   249                         (lastTypeDot >= 0 && objectType.at(lastTypeDot+1).isUpper()));
       
   250 
       
   251     int propertyCount = 0;
       
   252     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
       
   253         ++propertyCount;
       
   254         _stateStack.pushProperty(name->name->asString(),
       
   255                                  this->location(name));
       
   256     }
       
   257 
       
   258     if (!onAssignment && propertyCount && currentProperty() && currentProperty()->values.count()) {
       
   259         QDeclarativeError error;
       
   260         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
       
   261         error.setLine(this->location(propertyName).start.line);
       
   262         error.setColumn(this->location(propertyName).start.column);
       
   263         _parser->_errors << error;
       
   264         return 0;
       
   265     }
       
   266 
       
   267     if (!isType) {
       
   268 
       
   269         if(propertyCount || !currentObject()) {
       
   270             QDeclarativeError error;
       
   271             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected type name"));
       
   272             error.setLine(typeLocation.startLine);
       
   273             error.setColumn(typeLocation.startColumn);
       
   274             _parser->_errors << error;
       
   275             return 0;
       
   276         }
       
   277 
       
   278         LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
       
   279         if (propertyName)
       
   280             loc = ProcessAST::location(propertyName);
       
   281 
       
   282         _stateStack.pushProperty(objectType, loc);
       
   283        accept(initializer);
       
   284         _stateStack.pop();
       
   285 
       
   286         return 0;
       
   287 
       
   288     } else {
       
   289         // Class
       
   290 
       
   291         QString resolvableObjectType = objectType;
       
   292         if (lastTypeDot >= 0)
       
   293             resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
       
   294 
       
   295         Object *obj = new Object;
       
   296 
       
   297         QDeclarativeScriptParser::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
       
   298         obj->type = typeRef->id;
       
   299 
       
   300         typeRef->refObjects.append(obj);
       
   301 
       
   302         // XXX this doesn't do anything (_scope never builds up)
       
   303         _scope.append(resolvableObjectType);
       
   304         obj->typeName = qualifiedNameId().toUtf8();
       
   305         _scope.removeLast();
       
   306 
       
   307         obj->location = location;
       
   308 
       
   309         if (propertyCount) {
       
   310 
       
   311             Property *prop = currentProperty();
       
   312             Value *v = new Value;
       
   313             v->object = obj;
       
   314             v->location = obj->location;
       
   315             if (onAssignment)
       
   316                 prop->addOnValue(v);
       
   317             else
       
   318                 prop->addValue(v);
       
   319 
       
   320             while (propertyCount--)
       
   321                 _stateStack.pop();
       
   322 
       
   323         } else {
       
   324 
       
   325             if (! _parser->tree()) {
       
   326                 _parser->setTree(obj);
       
   327             } else {
       
   328                 const State state = _stateStack.top();
       
   329                 Value *v = new Value;
       
   330                 v->object = obj;
       
   331                 v->location = obj->location;
       
   332                 if (state.property) {
       
   333                     state.property->addValue(v);
       
   334                 } else {
       
   335                     Property *defaultProp = state.object->getDefaultProperty();
       
   336                     if (defaultProp->location.start.line == -1) {
       
   337                         defaultProp->location = v->location;
       
   338                         defaultProp->location.end = defaultProp->location.start;
       
   339                         defaultProp->location.range.length = 0;
       
   340                     }
       
   341                     defaultProp->addValue(v);
       
   342                 }
       
   343             }
       
   344         }
       
   345 
       
   346         _stateStack.pushObject(obj);
       
   347         accept(initializer);
       
   348         _stateStack.pop();
       
   349 
       
   350         return obj;
       
   351     }
       
   352 }
       
   353 
       
   354 LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
       
   355 {
       
   356     return location(id->identifierToken, id->identifierToken);
       
   357 }
       
   358 
       
   359 LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
       
   360 {
       
   361     LocationSpan rv;
       
   362     rv.start.line = start.startLine;
       
   363     rv.start.column = start.startColumn;
       
   364     rv.end.line = end.startLine;
       
   365     rv.end.column = end.startColumn + end.length - 1;
       
   366     rv.range.offset = start.offset;
       
   367     rv.range.length = end.offset + end.length - start.offset;
       
   368     return rv;
       
   369 }
       
   370 
       
   371 // UiProgram: UiImportListOpt UiObjectMemberList ;
       
   372 bool ProcessAST::visit(AST::UiProgram *node)
       
   373 {
       
   374     accept(node->imports);
       
   375     accept(node->members->member);
       
   376     return false;
       
   377 }
       
   378 
       
   379 // UiImport: T_IMPORT T_STRING_LITERAL ;
       
   380 bool ProcessAST::visit(AST::UiImport *node)
       
   381 {
       
   382     QString uri;
       
   383     QDeclarativeScriptParser::Import import;
       
   384 
       
   385     if (node->fileName) {
       
   386         uri = node->fileName->asString();
       
   387 
       
   388         if (uri.endsWith(QLatin1String(".js"))) {
       
   389             import.type = QDeclarativeScriptParser::Import::Script;
       
   390             _parser->_refUrls << QUrl(uri);
       
   391         } else {
       
   392             import.type = QDeclarativeScriptParser::Import::File;
       
   393         }
       
   394     } else {
       
   395         import.type = QDeclarativeScriptParser::Import::Library;
       
   396         uri = asString(node->importUri);
       
   397     }
       
   398 
       
   399     AST::SourceLocation startLoc = node->importToken;
       
   400     AST::SourceLocation endLoc = node->semicolonToken;
       
   401 
       
   402     // Qualifier
       
   403     if (node->importId) {
       
   404         import.qualifier = node->importId->asString();
       
   405         if (!import.qualifier.at(0).isUpper()) {
       
   406             QDeclarativeError error;
       
   407             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Invalid import qualifier ID"));
       
   408             error.setLine(node->importIdToken.startLine);
       
   409             error.setColumn(node->importIdToken.startColumn);
       
   410             _parser->_errors << error;
       
   411             return false;
       
   412         }
       
   413         if (import.qualifier == QLatin1String("Qt")) {
       
   414             QDeclarativeError error;
       
   415             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Reserved name \"Qt\" cannot be used as an qualifier"));
       
   416             error.setLine(node->importIdToken.startLine);
       
   417             error.setColumn(node->importIdToken.startColumn);
       
   418             _parser->_errors << error;
       
   419             return false;
       
   420         }
       
   421 
       
   422         // Check for script qualifier clashes
       
   423         bool isScript = import.type == QDeclarativeScriptParser::Import::Script;
       
   424         for (int ii = 0; ii < _parser->_imports.count(); ++ii) {
       
   425             const QDeclarativeScriptParser::Import &other = _parser->_imports.at(ii);
       
   426             bool otherIsScript = other.type == QDeclarativeScriptParser::Import::Script;
       
   427 
       
   428             if ((isScript || otherIsScript) && import.qualifier == other.qualifier) {
       
   429                 QDeclarativeError error;
       
   430                 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Script import qualifiers must be unique."));
       
   431                 error.setLine(node->importIdToken.startLine);
       
   432                 error.setColumn(node->importIdToken.startColumn);
       
   433                 _parser->_errors << error;
       
   434                 return false;
       
   435             }
       
   436         }
       
   437 
       
   438     } else if (import.type == QDeclarativeScriptParser::Import::Script) {
       
   439         QDeclarativeError error;
       
   440         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Script import requires a qualifier"));
       
   441         error.setLine(node->fileNameToken.startLine);
       
   442         error.setColumn(node->fileNameToken.startColumn);
       
   443         _parser->_errors << error;
       
   444         return false;
       
   445     }
       
   446 
       
   447     if (node->versionToken.isValid()) {
       
   448         import.version = textAt(node->versionToken);
       
   449     } else if (import.type == QDeclarativeScriptParser::Import::Library) {
       
   450         QDeclarativeError error;
       
   451         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Library import requires a version"));
       
   452         error.setLine(node->importIdToken.startLine);
       
   453         error.setColumn(node->importIdToken.startColumn);
       
   454         _parser->_errors << error;
       
   455         return false;
       
   456     }
       
   457 
       
   458 
       
   459     import.location = location(startLoc, endLoc);
       
   460     import.uri = uri;
       
   461 
       
   462     _parser->_imports << import;
       
   463 
       
   464     return false;
       
   465 }
       
   466 
       
   467 bool ProcessAST::visit(AST::UiPublicMember *node)
       
   468 {
       
   469     const struct TypeNameToType {
       
   470         const char *name;
       
   471         Object::DynamicProperty::Type type;
       
   472         const char *qtName;
       
   473     } propTypeNameToTypes[] = {
       
   474         { "int", Object::DynamicProperty::Int, "int" },
       
   475         { "bool", Object::DynamicProperty::Bool, "bool" },
       
   476         { "double", Object::DynamicProperty::Real, "double" },
       
   477         { "real", Object::DynamicProperty::Real, "qreal" },
       
   478         { "string", Object::DynamicProperty::String, "QString" },
       
   479         { "url", Object::DynamicProperty::Url, "QUrl" },
       
   480         { "color", Object::DynamicProperty::Color, "QColor" },
       
   481         // Internally QTime, QDate and QDateTime are all supported.
       
   482         // To be more consistent with JavaScript we expose only
       
   483         // QDateTime as it matches closely with the Date JS type.
       
   484         // We also call it "date" to match.
       
   485         // { "time", Object::DynamicProperty::Time, "QTime" },
       
   486         // { "date", Object::DynamicProperty::Date, "QDate" },
       
   487         { "date", Object::DynamicProperty::DateTime, "QDateTime" },
       
   488         { "variant", Object::DynamicProperty::Variant, "QVariant" }
       
   489     };
       
   490     const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
       
   491                                          sizeof(propTypeNameToTypes[0]);
       
   492 
       
   493     if(node->type == AST::UiPublicMember::Signal) {
       
   494         const QString name = node->name->asString();
       
   495 
       
   496         Object::DynamicSignal signal;
       
   497         signal.name = name.toUtf8();
       
   498 
       
   499         AST::UiParameterList *p = node->parameters;
       
   500         while (p) {
       
   501             const QString memberType = p->type->asString();
       
   502             const char *qtType = 0;
       
   503             for(int ii = 0; !qtType && ii < propTypeNameToTypesCount; ++ii) {
       
   504                 if(QLatin1String(propTypeNameToTypes[ii].name) == memberType)
       
   505                     qtType = propTypeNameToTypes[ii].qtName;
       
   506             }
       
   507 
       
   508             if (!qtType) {
       
   509                 QDeclarativeError error;
       
   510                 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected parameter type"));
       
   511                 error.setLine(node->typeToken.startLine);
       
   512                 error.setColumn(node->typeToken.startColumn);
       
   513                 _parser->_errors << error;
       
   514                 return false;
       
   515             }
       
   516             
       
   517             signal.parameterTypes << qtType;
       
   518             signal.parameterNames << p->name->asString().toUtf8();
       
   519             p = p->finish();
       
   520         }
       
   521 
       
   522         _stateStack.top().object->dynamicSignals << signal;
       
   523     } else {
       
   524         const QString memberType = node->memberType->asString();
       
   525         const QString name = node->name->asString();
       
   526 
       
   527         bool typeFound = false;
       
   528         Object::DynamicProperty::Type type;
       
   529 
       
   530         if (memberType == QLatin1String("alias")) {
       
   531             type = Object::DynamicProperty::Alias;
       
   532             typeFound = true;
       
   533         }
       
   534 
       
   535         for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
       
   536             if(QLatin1String(propTypeNameToTypes[ii].name) == memberType) {
       
   537                 type = propTypeNameToTypes[ii].type;
       
   538                 typeFound = true;
       
   539             }
       
   540         }
       
   541 
       
   542         if (!typeFound && memberType.at(0).isUpper()) {
       
   543             QString typemodifier;
       
   544             if(node->typeModifier)
       
   545                 typemodifier = node->typeModifier->asString();
       
   546             if (typemodifier == QString()) {
       
   547                 type = Object::DynamicProperty::Custom;
       
   548             } else if(typemodifier == QLatin1String("list")) {
       
   549                 type = Object::DynamicProperty::CustomList;
       
   550             } else {
       
   551                 QDeclarativeError error;
       
   552                 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Invalid property type modifier"));
       
   553                 error.setLine(node->typeModifierToken.startLine);
       
   554                 error.setColumn(node->typeModifierToken.startColumn);
       
   555                 _parser->_errors << error;
       
   556                 return false;
       
   557             }
       
   558             typeFound = true;
       
   559         } else if (node->typeModifier) {
       
   560             QDeclarativeError error;
       
   561             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Unexpected property type modifier"));
       
   562             error.setLine(node->typeModifierToken.startLine);
       
   563             error.setColumn(node->typeModifierToken.startColumn);
       
   564             _parser->_errors << error;
       
   565             return false;
       
   566         }
       
   567 
       
   568         if(!typeFound) {
       
   569             QDeclarativeError error;
       
   570             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected property type"));
       
   571             error.setLine(node->typeToken.startLine);
       
   572             error.setColumn(node->typeToken.startColumn);
       
   573             _parser->_errors << error;
       
   574             return false;
       
   575         }
       
   576 
       
   577         if (node->isReadonlyMember) {
       
   578             QDeclarativeError error;
       
   579             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Readonly not yet supported"));
       
   580             error.setLine(node->readonlyToken.startLine);
       
   581             error.setColumn(node->readonlyToken.startColumn);
       
   582             _parser->_errors << error;
       
   583             return false;
       
   584 
       
   585         }
       
   586         Object::DynamicProperty property;
       
   587         property.isDefaultProperty = node->isDefaultMember;
       
   588         property.type = type;
       
   589         if (type >= Object::DynamicProperty::Custom) {
       
   590             QDeclarativeScriptParser::TypeReference *typeRef =
       
   591                 _parser->findOrCreateType(memberType);
       
   592             typeRef->refObjects.append(_stateStack.top().object);
       
   593         }
       
   594         property.customType = memberType.toUtf8();
       
   595         property.name = name.toUtf8();
       
   596         property.location = location(node->firstSourceLocation(),
       
   597                                      node->lastSourceLocation());
       
   598 
       
   599         if (node->expression) { // default value
       
   600             property.defaultValue = new Property;
       
   601             property.defaultValue->parent = _stateStack.top().object;
       
   602             property.defaultValue->location =
       
   603                     location(node->expression->firstSourceLocation(),
       
   604                              node->expression->lastSourceLocation());
       
   605             Value *value = new Value;
       
   606             value->location = location(node->expression->firstSourceLocation(),
       
   607                                        node->expression->lastSourceLocation());
       
   608             value->value = getVariant(node->expression);
       
   609             property.defaultValue->values << value;
       
   610         }
       
   611 
       
   612         _stateStack.top().object->dynamicProperties << property;
       
   613 
       
   614         // process QML-like initializers (e.g. property Object o: Object {})
       
   615         accept(node->binding);
       
   616     }
       
   617 
       
   618     return false;
       
   619 }
       
   620 
       
   621 
       
   622 // UiObjectMember: UiQualifiedId UiObjectInitializer ;
       
   623 bool ProcessAST::visit(AST::UiObjectDefinition *node)
       
   624 {
       
   625     LocationSpan l = location(node->firstSourceLocation(),
       
   626                               node->lastSourceLocation());
       
   627 
       
   628     const QString objectType = asString(node->qualifiedTypeNameId);
       
   629     const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
       
   630 
       
   631     defineObjectBinding(/*propertyName = */ 0, false, objectType,
       
   632                         typeLocation, l, node->initializer);
       
   633 
       
   634     return false;
       
   635 }
       
   636 
       
   637 
       
   638 // UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
       
   639 bool ProcessAST::visit(AST::UiObjectBinding *node)
       
   640 {
       
   641     LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
       
   642                               node->initializer->rbraceToken);
       
   643 
       
   644     const QString objectType = asString(node->qualifiedTypeNameId);
       
   645     const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
       
   646 
       
   647     defineObjectBinding(node->qualifiedId, node->hasOnToken, objectType, 
       
   648                         typeLocation, l, node->initializer);
       
   649 
       
   650     return false;
       
   651 }
       
   652 
       
   653 QDeclarativeParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
       
   654 {
       
   655     if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
       
   656         return QDeclarativeParser::Variant(lit->value->asString());
       
   657     } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
       
   658         return QDeclarativeParser::Variant(true);
       
   659     } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
       
   660         return QDeclarativeParser::Variant(false);
       
   661     } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
       
   662         return QDeclarativeParser::Variant(lit->value, asString(expr));
       
   663     } else {
       
   664 
       
   665         if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
       
   666            if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
       
   667                return QDeclarativeParser::Variant(-lit->value, asString(expr));
       
   668            }
       
   669         }
       
   670 
       
   671         return  QDeclarativeParser::Variant(asString(expr), expr);
       
   672     }
       
   673 }
       
   674 
       
   675 
       
   676 // UiObjectMember: UiQualifiedId T_COLON Statement ;
       
   677 bool ProcessAST::visit(AST::UiScriptBinding *node)
       
   678 {
       
   679     int propertyCount = 0;
       
   680     AST::UiQualifiedId *propertyName = node->qualifiedId;
       
   681     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
       
   682         ++propertyCount;
       
   683         _stateStack.pushProperty(name->name->asString(),
       
   684                                  location(name));
       
   685     }
       
   686 
       
   687     Property *prop = currentProperty();
       
   688 
       
   689     if (prop->values.count()) {
       
   690         QDeclarativeError error;
       
   691         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
       
   692         error.setLine(this->location(propertyName).start.line);
       
   693         error.setColumn(this->location(propertyName).start.column);
       
   694         _parser->_errors << error;
       
   695         return 0;
       
   696     }
       
   697 
       
   698     QDeclarativeParser::Variant primitive;
       
   699 
       
   700     if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
       
   701         primitive = getVariant(stmt->expression);
       
   702     } else { // do binding
       
   703         primitive = QDeclarativeParser::Variant(asString(node->statement),
       
   704                                        node->statement);
       
   705     }
       
   706 
       
   707     prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
       
   708     prop->location.range.offset = node->qualifiedId->identifierToken.offset;
       
   709     Value *v = new Value;
       
   710     v->value = primitive;
       
   711     v->location = location(node->statement->firstSourceLocation(),
       
   712                            node->statement->lastSourceLocation());
       
   713 
       
   714     prop->addValue(v);
       
   715 
       
   716     while (propertyCount--)
       
   717         _stateStack.pop();
       
   718 
       
   719     return true;
       
   720 }
       
   721 
       
   722 static QList<int> collectCommas(AST::UiArrayMemberList *members)
       
   723 {
       
   724     QList<int> commas;
       
   725 
       
   726     if (members) {
       
   727         for (AST::UiArrayMemberList *it = members->next; it; it = it->next) {
       
   728             commas.append(it->commaToken.offset);
       
   729         }
       
   730     }
       
   731 
       
   732     return commas;
       
   733 }
       
   734 
       
   735 // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
       
   736 bool ProcessAST::visit(AST::UiArrayBinding *node)
       
   737 {
       
   738     int propertyCount = 0;
       
   739     AST::UiQualifiedId *propertyName = node->qualifiedId;
       
   740     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
       
   741         ++propertyCount;
       
   742         _stateStack.pushProperty(name->name->asString(),
       
   743                                  location(name));
       
   744     }
       
   745 
       
   746     Property* prop = currentProperty();
       
   747 
       
   748     if (prop->values.count()) {
       
   749         QDeclarativeError error;
       
   750         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
       
   751         error.setLine(this->location(propertyName).start.line);
       
   752         error.setColumn(this->location(propertyName).start.column);
       
   753         _parser->_errors << error;
       
   754         return 0;
       
   755     }
       
   756 
       
   757     accept(node->members);
       
   758 
       
   759     // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
       
   760     prop->listValueRange.offset = node->lbracketToken.offset;
       
   761     prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
       
   762 
       
   763     // Store the positions of the comma token too, again for the DOM to be able to retreive it.
       
   764     prop->listCommaPositions = collectCommas(node->members);
       
   765 
       
   766     while (propertyCount--)
       
   767         _stateStack.pop();
       
   768 
       
   769     return false;
       
   770 }
       
   771 
       
   772 bool ProcessAST::visit(AST::UiSourceElement *node)
       
   773 {
       
   774     QDeclarativeParser::Object *obj = currentObject();
       
   775 
       
   776     if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
       
   777 
       
   778         Object::DynamicSlot slot;
       
   779         slot.location = location(funDecl->firstSourceLocation(), funDecl->lastSourceLocation());
       
   780 
       
   781         AST::FormalParameterList *f = funDecl->formals;
       
   782         while (f) {
       
   783             slot.parameterNames << f->name->asString().toUtf8();
       
   784             f = f->finish();
       
   785         }
       
   786 
       
   787         QString body = textAt(funDecl->lbraceToken, funDecl->rbraceToken);
       
   788         slot.name = funDecl->name->asString().toUtf8();
       
   789         slot.body = body;
       
   790         obj->dynamicSlots << slot;
       
   791 
       
   792     } else {
       
   793         QDeclarativeError error;
       
   794         error.setDescription(QCoreApplication::translate("QDeclarativeParser","JavaScript declaration outside Script element"));
       
   795         error.setLine(node->firstSourceLocation().startLine);
       
   796         error.setColumn(node->firstSourceLocation().startColumn);
       
   797         _parser->_errors << error;
       
   798     }
       
   799     return false;
       
   800 }
       
   801 
       
   802 } // end of anonymous namespace
       
   803 
       
   804 
       
   805 QDeclarativeScriptParser::QDeclarativeScriptParser()
       
   806 : root(0), data(0)
       
   807 {
       
   808 
       
   809 }
       
   810 
       
   811 QDeclarativeScriptParser::~QDeclarativeScriptParser()
       
   812 {
       
   813     clear();
       
   814 }
       
   815 
       
   816 class QDeclarativeScriptParserJsASTData
       
   817 {
       
   818 public:
       
   819     QDeclarativeScriptParserJsASTData(const QString &filename)
       
   820         : nodePool(filename, &engine) {}
       
   821 
       
   822     Engine engine;
       
   823     NodePool nodePool;
       
   824 };
       
   825 
       
   826 bool QDeclarativeScriptParser::parse(const QByteArray &qmldata, const QUrl &url)
       
   827 {
       
   828     clear();
       
   829 
       
   830     const QString fileName = url.toString();
       
   831     _scriptFile = fileName;
       
   832 
       
   833     QTextStream stream(qmldata, QIODevice::ReadOnly);
       
   834     stream.setCodec("UTF-8");
       
   835     const QString code = stream.readAll();
       
   836 
       
   837     data = new QDeclarativeScriptParserJsASTData(fileName);
       
   838 
       
   839     Lexer lexer(&data->engine);
       
   840     lexer.setCode(code, /*line = */ 1);
       
   841 
       
   842     Parser parser(&data->engine);
       
   843 
       
   844     if (! parser.parse() || !_errors.isEmpty()) {
       
   845 
       
   846         // Extract errors from the parser
       
   847         foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
       
   848 
       
   849             if (m.isWarning())
       
   850                 continue;
       
   851 
       
   852             QDeclarativeError error;
       
   853             error.setUrl(url);
       
   854             error.setDescription(m.message);
       
   855             error.setLine(m.loc.startLine);
       
   856             error.setColumn(m.loc.startColumn);
       
   857             _errors << error;
       
   858 
       
   859         }
       
   860     }
       
   861 
       
   862     if (_errors.isEmpty()) {
       
   863         ProcessAST process(this);
       
   864         process(code, parser.ast());
       
   865 
       
   866         // Set the url for process errors
       
   867         for(int ii = 0; ii < _errors.count(); ++ii)
       
   868             _errors[ii].setUrl(url);
       
   869     }
       
   870 
       
   871     return _errors.isEmpty();
       
   872 }
       
   873 
       
   874 QList<QDeclarativeScriptParser::TypeReference*> QDeclarativeScriptParser::referencedTypes() const
       
   875 {
       
   876     return _refTypes;
       
   877 }
       
   878 
       
   879 QList<QUrl> QDeclarativeScriptParser::referencedResources() const
       
   880 {
       
   881     return _refUrls;
       
   882 }
       
   883 
       
   884 Object *QDeclarativeScriptParser::tree() const
       
   885 {
       
   886     return root;
       
   887 }
       
   888 
       
   889 QList<QDeclarativeScriptParser::Import> QDeclarativeScriptParser::imports() const
       
   890 {
       
   891     return _imports;
       
   892 }
       
   893 
       
   894 QList<QDeclarativeError> QDeclarativeScriptParser::errors() const
       
   895 {
       
   896     return _errors;
       
   897 }
       
   898 
       
   899 /*
       
   900 Searches for ".pragma <value>" declarations within \a script.  Currently supported pragmas
       
   901 are:
       
   902     library
       
   903 */
       
   904 QDeclarativeParser::Object::ScriptBlock::Pragmas QDeclarativeScriptParser::extractPragmas(QString &script)
       
   905 {
       
   906     QDeclarativeParser::Object::ScriptBlock::Pragmas rv = QDeclarativeParser::Object::ScriptBlock::None;
       
   907 
       
   908     const QChar forwardSlash(QLatin1Char('/'));
       
   909     const QChar star(QLatin1Char('*'));
       
   910     const QChar newline(QLatin1Char('\n'));
       
   911     const QChar dot(QLatin1Char('.'));
       
   912     const QChar semicolon(QLatin1Char(';'));
       
   913     const QChar space(QLatin1Char(' '));
       
   914     const QString pragma(QLatin1String(".pragma "));
       
   915 
       
   916     const QChar *pragmaData = pragma.constData();
       
   917 
       
   918     const QChar *data = script.constData();
       
   919     const int length = script.count();
       
   920     for (int ii = 0; ii < length; ++ii) {
       
   921         const QChar &c = data[ii];
       
   922 
       
   923         if (c.isSpace())
       
   924             continue;
       
   925 
       
   926         if (c == forwardSlash) {
       
   927             ++ii;
       
   928             if (ii >= length)
       
   929                 return rv;
       
   930 
       
   931             const QChar &c = data[ii];
       
   932             if (c == forwardSlash) {
       
   933                 // Find next newline
       
   934                 while (ii < length && data[++ii] != newline) {};
       
   935             } else if (c == star) {
       
   936                 // Find next star
       
   937                 while (true) {
       
   938                     while (ii < length && data[++ii] != star) {};
       
   939                     if (ii + 1 >= length)
       
   940                         return rv;
       
   941 
       
   942                     if (data[ii + 1] == forwardSlash) {
       
   943                         ++ii;
       
   944                         break;
       
   945                     }
       
   946                 }
       
   947             } else {
       
   948                 return rv;
       
   949             }
       
   950         } else if (c == dot) {
       
   951             // Could be a pragma!
       
   952             if (ii + pragma.length() >= length ||
       
   953                 0 != ::memcmp(data + ii, pragmaData, sizeof(QChar) * pragma.length()))
       
   954                 return rv;
       
   955 
       
   956             int pragmaStatementIdx = ii;
       
   957 
       
   958             ii += pragma.length();
       
   959 
       
   960             while (ii < length && data[ii].isSpace()) { ++ii; }
       
   961 
       
   962             int startIdx = ii;
       
   963 
       
   964             while (ii < length && data[ii].isLetter()) { ++ii; }
       
   965 
       
   966             int endIdx = ii;
       
   967 
       
   968             if (ii != length && data[ii] != forwardSlash && !data[ii].isSpace() && data[ii] != semicolon)
       
   969                 return rv;
       
   970 
       
   971             QString p(data + startIdx, endIdx - startIdx);
       
   972 
       
   973             if (p == QLatin1String("library"))
       
   974                 rv |= QDeclarativeParser::Object::ScriptBlock::Shared;
       
   975             else
       
   976                 return rv;
       
   977 
       
   978             for (int jj = pragmaStatementIdx; jj < endIdx; ++jj) script[jj] = space;
       
   979 
       
   980         } else {
       
   981             return rv;
       
   982         }
       
   983     }
       
   984 
       
   985     return rv;
       
   986 }
       
   987 
       
   988 void QDeclarativeScriptParser::clear()
       
   989 {
       
   990     if (root) {
       
   991         root->release();
       
   992         root = 0;
       
   993     }
       
   994     _imports.clear();
       
   995     qDeleteAll(_refTypes);
       
   996     _refTypes.clear();
       
   997     _errors.clear();
       
   998 
       
   999     if (data) {
       
  1000         delete data;
       
  1001         data = 0;
       
  1002     }
       
  1003 }
       
  1004 
       
  1005 QDeclarativeScriptParser::TypeReference *QDeclarativeScriptParser::findOrCreateType(const QString &name)
       
  1006 {
       
  1007     TypeReference *type = 0;
       
  1008     int i = 0;
       
  1009     for (; i < _refTypes.size(); ++i) {
       
  1010         if (_refTypes.at(i)->name == name) {
       
  1011             type = _refTypes.at(i);
       
  1012             break;
       
  1013         }
       
  1014     }
       
  1015     if (!type) {
       
  1016         type = new TypeReference(i, name);
       
  1017         _refTypes.append(type);
       
  1018     }
       
  1019 
       
  1020     return type;
       
  1021 }
       
  1022 
       
  1023 void QDeclarativeScriptParser::setTree(Object *tree)
       
  1024 {
       
  1025     Q_ASSERT(! root);
       
  1026 
       
  1027     root = tree;
       
  1028 }
       
  1029 
       
  1030 QT_END_NAMESPACE