Asynchronous component instantiation
[profile/ivi/qtdeclarative.git] / src / declarative / qml / qdeclarativescript.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 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 ** 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.
17 **
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.
21 **
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.
29 **
30 ** Other Usage
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.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "private/qdeclarativescript_p.h"
43
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"
51
52 #include <QStack>
53 #include <QCoreApplication>
54 #include <QtDebug>
55
56 QT_BEGIN_NAMESPACE
57
58 using namespace QDeclarativeJS;
59 using namespace QDeclarativeScript;
60
61 // 
62 // Parser IR classes
63 //
64 QDeclarativeScript::Object::Object()
65 : type(-1), idIndex(-1), metatype(0), synthCache(0), defaultProperty(0), parserStatusCast(-1),
66   componentCompileState(0), nextAliasingObject(0), nextIdObject(0)
67 {
68 }
69
70 QDeclarativeScript::Object::~Object() 
71
72     if (synthCache) synthCache->release();
73 }
74
75 void Object::setBindingBit(int b)
76 {
77     while (bindingBitmask.size() < 4 * (1 + b / 32))
78         bindingBitmask.append(char(0));
79
80     quint32 *bits = (quint32 *)bindingBitmask.data();
81     bits[b / 32] |= (1 << (b % 32));
82 }
83
84 const QMetaObject *Object::metaObject() const
85 {
86     if (!metadata.isEmpty() && metatype)
87         return &extObject;
88     else
89         return metatype;
90 }
91
92 QDeclarativeScript::Property *Object::getDefaultProperty()
93 {
94     if (!defaultProperty) {
95         defaultProperty = pool()->New<Property>();
96         defaultProperty->parent = this;
97     }
98     return defaultProperty;
99 }
100
101 void QDeclarativeScript::Object::addValueProperty(Property *p)
102 {
103     valueProperties.append(p);
104 }
105
106 void QDeclarativeScript::Object::addSignalProperty(Property *p)
107 {
108     signalProperties.append(p);
109 }
110
111 void QDeclarativeScript::Object::addAttachedProperty(Property *p)
112 {
113     attachedProperties.append(p);
114 }
115
116 void QDeclarativeScript::Object::addGroupedProperty(Property *p)
117 {
118     groupedProperties.append(p);
119 }
120
121 void QDeclarativeScript::Object::addValueTypeProperty(Property *p)
122 {
123     valueTypeProperties.append(p);
124 }
125
126 void QDeclarativeScript::Object::addScriptStringProperty(Property *p)
127 {
128     scriptStringProperties.append(p);
129 }
130
131 // This lookup is optimized for missing, and having to create a new property.
132 Property *QDeclarativeScript::Object::getProperty(const QHashedStringRef &name, bool create)
133 {
134     if (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)
139                     return p;
140             }
141         }
142
143         Property *property = pool()->New<Property>();
144         property->parent = this;
145         property->_name = name;
146         property->isDefault = false;
147         properties.prepend(property);
148         return property;
149     } else {
150         for (Property *p = properties.first(); p; p = properties.next(p)) {
151             if (p->name() == name)
152                 return p;
153         }
154     }
155
156     return 0;
157 }
158
159 Property *QDeclarativeScript::Object::getProperty(const QStringRef &name, bool create)
160 {
161     return getProperty(QHashedStringRef(name), create);
162 }
163
164 Property *QDeclarativeScript::Object::getProperty(const QString &name, bool create)
165 {
166     for (Property *p = properties.first(); p; p = properties.next(p)) {
167         if (p->name() == name)
168             return p;
169     }
170
171     if (create) {
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);
178         return property;
179     } else {
180         return 0;
181     }
182 }
183
184 QDeclarativeScript::Object::DynamicProperty::DynamicProperty()
185 : isDefaultProperty(false), type(Variant), defaultValue(0), nextProperty(0), 
186   resolvedCustomTypeName(0)
187 {
188 }
189
190 QDeclarativeScript::Object::DynamicSignal::DynamicSignal()
191 : nextSignal(0)
192 {
193 }
194
195 // Returns length in utf8 bytes
196 int QDeclarativeScript::Object::DynamicSignal::parameterTypesLength() const
197 {
198     int rv = 0;
199     for (int ii = 0; ii < parameterTypes.count(); ++ii)
200         rv += parameterTypes.at(ii).length();
201     return rv;
202 }
203
204 // Returns length in utf8 bytes
205 int QDeclarativeScript::Object::DynamicSignal::parameterNamesLength() const
206 {
207     int rv = 0;
208     for (int ii = 0; ii < parameterNames.count(); ++ii)
209         rv += parameterNames.at(ii).utf8length();
210     return rv;
211 }
212
213 QDeclarativeScript::Object::DynamicSlot::DynamicSlot()
214 : nextSlot(0)
215 {
216 }
217
218 int QDeclarativeScript::Object::DynamicSlot::parameterNamesLength() const
219 {
220     int rv = 0;
221     for (int ii = 0; ii < parameterNames.count(); ++ii)
222         rv += parameterNames.at(ii).length();
223     return rv;
224 }
225
226 QDeclarativeScript::Property::Property()
227 : parent(0), type(0), index(-1), value(0), isDefault(true), isDeferred(false), 
228   isValueTypeSubProperty(false), isAlias(false), scriptStringScope(-1), 
229   nextMainProperty(0), nextProperty(0)
230 {
231 }
232
233 QDeclarativeScript::Object *QDeclarativeScript::Property::getValue(const LocationSpan &l)
234 {
235     if (!value) { value = pool()->New<Object>(); value->location = l; }
236     return value;
237 }
238
239 void QDeclarativeScript::Property::addValue(Value *v)
240 {
241     values.append(v);
242 }
243
244 void QDeclarativeScript::Property::addOnValue(Value *v)
245 {
246     onValues.append(v);
247 }
248
249 bool QDeclarativeScript::Property::isEmpty() const
250 {
251     return !value && values.isEmpty() && onValues.isEmpty();
252 }
253
254 QDeclarativeScript::Value::Value()
255 : type(Unknown), object(0), bindingReference(0), signalExpressionContextStack(0), nextValue(0)
256 {
257 }
258
259 QDeclarativeScript::Variant::Variant()
260 : t(Invalid)
261 {
262 }
263
264 QDeclarativeScript::Variant::Variant(const Variant &o)
265 : t(o.t), d(o.d), asWritten(o.asWritten)
266 {
267 }
268
269 QDeclarativeScript::Variant::Variant(bool v)
270 : t(Boolean), b(v)
271 {
272 }
273
274 QDeclarativeScript::Variant::Variant(double v, const QStringRef &asWritten)
275 : t(Number), d(v), asWritten(asWritten)
276 {
277 }
278
279 QDeclarativeScript::Variant::Variant(QDeclarativeJS::AST::StringLiteral *v)
280 : t(String), l(v)
281 {
282 }
283
284 QDeclarativeScript::Variant::Variant(const QStringRef &asWritten, QDeclarativeJS::AST::Node *n)
285 : t(Script), n(n), asWritten(asWritten)
286 {
287 }
288
289 QDeclarativeScript::Variant &QDeclarativeScript::Variant::operator=(const Variant &o)
290 {
291     t = o.t;
292     d = o.d;
293     asWritten = o.asWritten;
294     return *this;
295 }
296
297 QDeclarativeScript::Variant::Type QDeclarativeScript::Variant::type() const
298 {
299     return t;
300 }
301
302 bool QDeclarativeScript::Variant::asBoolean() const
303 {
304     return b;
305 }
306
307 QString QDeclarativeScript::Variant::asString() const
308 {
309     if (t == String) {
310         return l->value.toString();
311     } else {
312         return asWritten.toString();
313     }
314 }
315
316 double QDeclarativeScript::Variant::asNumber() const
317 {
318     return d;
319 }
320
321 //reverse of Lexer::singleEscape()
322 QString escapedString(const QString &string)
323 {
324     QString tmp = QLatin1String("\"");
325     for (int i = 0; i < string.length(); ++i) {
326         const QChar &c = string.at(i);
327         switch(c.unicode()) {
328         case 0x08:
329             tmp += QLatin1String("\\b");
330             break;
331         case 0x09:
332             tmp += QLatin1String("\\t");
333             break;
334         case 0x0A:
335             tmp += QLatin1String("\\n");
336             break;
337         case 0x0B:
338             tmp += QLatin1String("\\v");
339             break;
340         case 0x0C:
341             tmp += QLatin1String("\\f");
342             break;
343         case 0x0D:
344             tmp += QLatin1String("\\r");
345             break;
346         case 0x22:
347             tmp += QLatin1String("\\\"");
348             break;
349         case 0x27:
350             tmp += QLatin1String("\\\'");
351             break;
352         case 0x5C:
353             tmp += QLatin1String("\\\\");
354             break;
355         default:
356             tmp += c;
357             break;
358         }
359     }
360     tmp += QLatin1Char('\"');
361     return tmp;
362 }
363
364 QString QDeclarativeScript::Variant::asScript() const
365 {
366     switch(type()) { 
367     default:
368     case Invalid:
369         return QString();
370     case Boolean:
371         return b?QLatin1String("true"):QLatin1String("false");
372     case Number:
373         if (asWritten.isEmpty())
374             return QString::number(d);
375         else 
376             return asWritten.toString();
377     case String:
378         return escapedString(asString());
379     case Script:
380         if (AST::IdentifierExpression *i = AST::cast<AST::IdentifierExpression *>(n)) {
381             return i->name.toString();
382         } else
383             return asWritten.toString();
384     }
385 }
386
387 QDeclarativeJS::AST::Node *QDeclarativeScript::Variant::asAST() const
388 {
389     if (type() == Script)
390         return n;
391     else
392         return 0;
393 }
394
395 bool QDeclarativeScript::Variant::isStringList() const
396 {
397     if (isString())
398         return true;
399
400     if (type() != Script || !n)
401         return false;
402
403     AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
404     if (!array)
405         return false;
406
407     AST::ElementList *elements = array->elements;
408
409     while (elements) {
410
411         if (!AST::cast<AST::StringLiteral *>(elements->expression))
412             return false;
413
414         elements = elements->next;
415     }
416
417     return true;
418 }
419
420 QStringList QDeclarativeScript::Variant::asStringList() const
421 {
422     QStringList rv;
423     if (isString()) {
424         rv << asString();
425         return rv;
426     }
427
428     AST::ArrayLiteral *array = AST::cast<AST::ArrayLiteral *>(n);
429     if (!array)
430         return rv;
431
432     AST::ElementList *elements = array->elements;
433     while (elements) {
434
435         AST::StringLiteral *string = AST::cast<AST::StringLiteral *>(elements->expression);
436         if (!string)
437             return QStringList();
438         rv.append(string->value.toString());
439
440         elements = elements->next;
441     }
442
443     return  rv;
444 }
445
446 //
447 // Actual parser classes
448 //
449 void QDeclarativeScript::Import::extractVersion(int *maj, int *min) const
450 {
451     *maj = -1; *min = -1;
452
453     if (!version.isEmpty()) {
454         int dot = version.indexOf(QLatin1Char('.'));
455         if (dot < 0) {
456             *maj = version.toInt();
457             *min = 0;
458         } else {
459             *maj = version.left(dot).toInt();
460             *min = version.mid(dot+1).toInt();
461         }
462     }
463 }
464
465 namespace {
466
467 class ProcessAST: protected AST::Visitor
468 {
469     struct State {
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) {}
473
474         QDeclarativeScript::Object *object;
475         Property *property;
476     };
477
478     struct StateStack : public QStack<State>
479     {
480         void pushObject(QDeclarativeScript::Object *obj)
481         {
482             push(State(obj));
483         }
484
485         void pushProperty(const QString &name, const LocationSpan &location)
486         {
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;
492                 push(s);
493             } else {
494                 State s(state.object, state.object->getProperty(name));
495
496                 s.property->location = location;
497                 push(s);
498             }
499         }
500
501         void pushProperty(const QStringRef &name, const LocationSpan &location)
502         {
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;
508                 push(s);
509             } else {
510                 State s(state.object, state.object->getProperty(name));
511
512                 s.property->location = location;
513                 push(s);
514             }
515         }
516     };
517
518 public:
519     ProcessAST(QDeclarativeScript::Parser *parser);
520     virtual ~ProcessAST();
521
522     void operator()(const QString &code, AST::Node *node);
523
524 protected:
525
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);
531
532     QDeclarativeScript::Variant getVariant(AST::Statement *stmt);
533     QDeclarativeScript::Variant getVariant(AST::ExpressionNode *expr);
534
535     LocationSpan location(AST::SourceLocation start, AST::SourceLocation end);
536     LocationSpan location(AST::UiQualifiedId *);
537
538     using AST::Visitor::visit;
539     using AST::Visitor::endVisit;
540
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);
546
547     virtual bool visit(AST::UiScriptBinding *node);
548     virtual bool visit(AST::UiArrayBinding *node);
549     virtual bool visit(AST::UiSourceElement *node);
550
551     void accept(AST::Node *node);
552
553     QString asString(AST::UiQualifiedId *node) const;
554
555     const State state() const;
556     QDeclarativeScript::Object *currentObject() const;
557     Property *currentProperty() const;
558
559     QString qualifiedNameId() const;
560
561     QString textAt(const AST::SourceLocation &loc) const
562     { return _contents->mid(loc.offset, loc.length); }
563
564     QStringRef textRefAt(const AST::SourceLocation &loc) const
565     { return QStringRef(_contents, loc.offset, loc.length); }
566
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); }
570
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); }
574
575     QString asString(AST::ExpressionNode *expr)
576     {
577         if (! expr)
578             return QString();
579
580         return textAt(expr->firstSourceLocation(), expr->lastSourceLocation());
581     }
582
583     QStringRef asStringRef(AST::ExpressionNode *expr)
584     {
585         if (! expr)
586             return QStringRef();
587
588         return textRefAt(expr->firstSourceLocation(), expr->lastSourceLocation());
589     }
590
591     QString asString(AST::Statement *stmt)
592     {
593         if (! stmt)
594             return QString();
595
596         QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
597         s += QLatin1Char('\n');
598         return s;
599     }
600
601     QStringRef asStringRef(AST::Statement *stmt)
602     {
603         if (! stmt)
604             return QStringRef();
605
606         return textRefAt(stmt->firstSourceLocation(), stmt->lastSourceLocation());
607     }
608
609 private:
610     QDeclarativeScript::Parser *_parser;
611     StateStack _stateStack;
612     QStringList _scope;
613     const QString *_contents;
614 };
615
616 ProcessAST::ProcessAST(QDeclarativeScript::Parser *parser)
617     : _parser(parser)
618 {
619 }
620
621 ProcessAST::~ProcessAST()
622 {
623 }
624
625 void ProcessAST::operator()(const QString &code, AST::Node *node)
626 {
627     _contents = &code;
628     accept(node);
629 }
630
631 void ProcessAST::accept(AST::Node *node)
632 {
633     AST::Node::acceptChild(node, this);
634 }
635
636 const ProcessAST::State ProcessAST::state() const
637 {
638     if (_stateStack.isEmpty())
639         return State();
640
641     return _stateStack.back();
642 }
643
644 QDeclarativeScript::Object *ProcessAST::currentObject() const
645 {
646     return state().object;
647 }
648
649 Property *ProcessAST::currentProperty() const
650 {
651     return state().property;
652 }
653
654 QString ProcessAST::qualifiedNameId() const
655 {
656     return _scope.join(QLatin1String("/"));
657 }
658
659 QString ProcessAST::asString(AST::UiQualifiedId *node) const
660 {
661     QString s;
662
663     for (AST::UiQualifiedId *it = node; it; it = it->next) {
664         s.append(it->name.toString());
665
666         if (it->next)
667             s.append(QLatin1Char('.'));
668     }
669
670     return s;
671 }
672
673 QDeclarativeScript::Object *
674 ProcessAST::defineObjectBinding(AST::UiQualifiedId *propertyName,
675                                 bool onAssignment,
676                                 const QString &objectType,
677                                 AST::SourceLocation typeLocation,
678                                 LocationSpan location,
679                                 AST::UiObjectInitializer *initializer)
680 {
681     int lastTypeDot = objectType.lastIndexOf(QLatin1Char('.'));
682     bool isType = !objectType.isEmpty() &&
683                     (objectType.at(0).isUpper() ||
684                         (lastTypeDot >= 0 && objectType.at(lastTypeDot+1).isUpper()));
685
686     int propertyCount = 0;
687     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
688         ++propertyCount;
689         _stateStack.pushProperty(name->name,
690                                  this->location(name));
691     }
692
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;
699         return 0;
700     }
701
702     if (!isType) {
703
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;
710             return 0;
711         }
712
713         LocationSpan loc = ProcessAST::location(typeLocation, typeLocation);
714         if (propertyName)
715             loc = ProcessAST::location(propertyName);
716
717         _stateStack.pushProperty(objectType, loc);
718        accept(initializer);
719         _stateStack.pop();
720
721         return 0;
722
723     } else {
724         // Class
725
726         QString resolvableObjectType = objectType;
727         if (lastTypeDot >= 0)
728             resolvableObjectType.replace(QLatin1Char('.'),QLatin1Char('/'));
729
730         QDeclarativeScript::Object *obj = _parser->_pool.New<QDeclarativeScript::Object>();
731
732         QDeclarativeScript::TypeReference *typeRef = _parser->findOrCreateType(resolvableObjectType);
733         obj->type = typeRef->id;
734
735         typeRef->refObjects.append(obj);
736
737         // XXX this doesn't do anything (_scope never builds up)
738         _scope.append(resolvableObjectType);
739         obj->typeName = qualifiedNameId().toUtf8();
740         _scope.removeLast();
741
742         obj->location = location;
743
744         if (propertyCount) {
745             Property *prop = currentProperty();
746             QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
747             v->object = obj;
748             v->location = obj->location;
749             if (onAssignment)
750                 prop->addOnValue(v);
751             else
752                 prop->addValue(v);
753
754             while (propertyCount--)
755                 _stateStack.pop();
756
757         } else {
758
759             if (! _parser->tree()) {
760                 _parser->setTree(obj);
761             } else {
762                 const State state = _stateStack.top();
763                 QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
764                 v->object = obj;
765                 v->location = obj->location;
766                 if (state.property) {
767                     state.property->addValue(v);
768                 } else {
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;
774                     }
775                     defaultProp->addValue(v);
776                 }
777             }
778         }
779
780         _stateStack.pushObject(obj);
781         accept(initializer);
782         _stateStack.pop();
783
784         return obj;
785     }
786 }
787
788 LocationSpan ProcessAST::location(AST::UiQualifiedId *id)
789 {
790     return location(id->identifierToken, id->identifierToken);
791 }
792
793 LocationSpan ProcessAST::location(AST::SourceLocation start, AST::SourceLocation end)
794 {
795     LocationSpan rv;
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;
802     return rv;
803 }
804
805 // UiProgram: UiImportListOpt UiObjectMemberList ;
806 bool ProcessAST::visit(AST::UiProgram *node)
807 {
808     accept(node->imports);
809     accept(node->members->member);
810     return false;
811 }
812
813 // UiImport: T_IMPORT T_STRING_LITERAL ;
814 bool ProcessAST::visit(AST::UiImport *node)
815 {
816     QString uri;
817     QDeclarativeScript::Import import;
818
819     if (!node->fileName.isNull()) {
820         uri = node->fileName.toString();
821
822         if (uri.endsWith(QLatin1String(".js"))) {
823             import.type = QDeclarativeScript::Import::Script;
824         } else {
825             import.type = QDeclarativeScript::Import::File;
826         }
827     } else {
828         import.type = QDeclarativeScript::Import::Library;
829         uri = asString(node->importUri);
830     }
831
832     AST::SourceLocation startLoc = node->importToken;
833     AST::SourceLocation endLoc = node->semicolonToken;
834
835     // Qualifier
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;
844             return false;
845         }
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;
852             return false;
853         }
854
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;
860
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;
867                 return false;
868             }
869         }
870
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;
877         return false;
878     }
879
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;
888         return false;
889     }
890
891
892     import.location = location(startLoc, endLoc);
893     import.uri = uri;
894
895     _parser->_imports << import;
896
897     return false;
898 }
899
900 bool ProcessAST::visit(AST::UiPublicMember *node)
901 {
902     static const struct TypeNameToType {
903         const char *name;
904         int nameLength;
905         Object::DynamicProperty::Type type;
906         const char *qtName;
907         int qtNameLength;
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     };
925     static const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) /
926                                                 sizeof(propTypeNameToTypes[0]);
927
928     if(node->type == AST::UiPublicMember::Signal) {
929         Object::DynamicSignal *signal = _parser->_pool.New<Object::DynamicSignal>();
930         signal->name = node->name;
931
932         AST::UiParameterList *p = node->parameters;
933         int paramLength = 0;
934         while (p) { paramLength++; p = p->next; }
935         p = node->parameters;
936
937         if (paramLength) {
938             signal->parameterTypes = _parser->_pool.NewRawList<QHashedCStringRef>(paramLength);
939             signal->parameterNames = _parser->_pool.NewRawList<QHashedStringRef>(paramLength);
940         }
941
942         int index = 0;
943         while (p) {
944             const QStringRef &memberType = p->type;
945
946             const TypeNameToType *type = 0;
947             for(int typeIndex = 0; typeIndex < propTypeNameToTypesCount; ++typeIndex) {
948                 const TypeNameToType *t = propTypeNameToTypes + typeIndex;
949                 if (t->nameLength == memberType.length() && 
950                     QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
951                     type = t;
952                     break;
953                 }
954             }
955
956             if (!type) {
957                 QDeclarativeError error;
958                 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected parameter type"));
959                 error.setLine(node->typeToken.startLine);
960                 error.setColumn(node->typeToken.startColumn);
961                 _parser->_errors << error;
962                 return false;
963             }
964             
965             signal->parameterTypes[index] = QHashedCStringRef(type->qtName, type->qtNameLength);
966             signal->parameterNames[index] = QHashedStringRef(p->name);
967             p = p->next;
968             index++;
969         }
970
971         signal->location = location(node->typeToken, node->semicolonToken);
972         _stateStack.top().object->dynamicSignals.append(signal);
973     } else {
974         const QStringRef &memberType = node->memberType;
975         const QStringRef &name = node->name;
976
977         bool typeFound = false;
978         Object::DynamicProperty::Type type;
979
980         if ((unsigned)memberType.length() == strlen("alias") && 
981             QHashedString::compare(memberType.constData(), "alias", strlen("alias"))) {
982             type = Object::DynamicProperty::Alias;
983             typeFound = true;
984         } 
985
986         for(int ii = 0; !typeFound && ii < propTypeNameToTypesCount; ++ii) {
987             const TypeNameToType *t = propTypeNameToTypes + ii;
988             if (t->nameLength == memberType.length() && 
989                 QHashedString::compare(memberType.constData(), t->name, t->nameLength)) {
990                 type = t->type;
991                 typeFound = true;
992             }
993         }
994
995         if (!typeFound && memberType.at(0).isUpper()) {
996             const QStringRef &typeModifier = node->typeModifier;
997
998             if (typeModifier.isEmpty()) {
999                 type = Object::DynamicProperty::Custom;
1000             } else if((unsigned)typeModifier.length() == strlen("list") && 
1001                       QHashedString::compare(typeModifier.constData(), "list", strlen("list"))) {
1002                 type = Object::DynamicProperty::CustomList;
1003             } else {
1004                 QDeclarativeError error;
1005                 error.setDescription(QCoreApplication::translate("QDeclarativeParser","Invalid property type modifier"));
1006                 error.setLine(node->typeModifierToken.startLine);
1007                 error.setColumn(node->typeModifierToken.startColumn);
1008                 _parser->_errors << error;
1009                 return false;
1010             }
1011             typeFound = true;
1012         } else if (!node->typeModifier.isNull()) {
1013             QDeclarativeError error;
1014             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Unexpected property type modifier"));
1015             error.setLine(node->typeModifierToken.startLine);
1016             error.setColumn(node->typeModifierToken.startColumn);
1017             _parser->_errors << error;
1018             return false;
1019         }
1020
1021         if(!typeFound) {
1022             QDeclarativeError error;
1023             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Expected property type"));
1024             error.setLine(node->typeToken.startLine);
1025             error.setColumn(node->typeToken.startColumn);
1026             _parser->_errors << error;
1027             return false;
1028         }
1029
1030         if (node->isReadonlyMember) {
1031             QDeclarativeError error;
1032             error.setDescription(QCoreApplication::translate("QDeclarativeParser","Readonly not yet supported"));
1033             error.setLine(node->readonlyToken.startLine);
1034             error.setColumn(node->readonlyToken.startColumn);
1035             _parser->_errors << error;
1036             return false;
1037
1038         }
1039
1040         Object::DynamicProperty *property = _parser->_pool.New<Object::DynamicProperty>();
1041         property->isDefaultProperty = node->isDefaultMember;
1042         property->type = type;
1043         if (type >= Object::DynamicProperty::Custom) {
1044             QDeclarativeScript::TypeReference *typeRef =
1045                 _parser->findOrCreateType(memberType.toString());
1046             typeRef->refObjects.append(_stateStack.top().object);
1047             property->customType = memberType;
1048         }
1049
1050         property->name = QHashedStringRef(name);
1051         property->location = location(node->firstSourceLocation(),
1052                                       node->lastSourceLocation());
1053
1054         if (node->statement) { // default value
1055             property->defaultValue = _parser->_pool.New<Property>();
1056             property->defaultValue->parent = _stateStack.top().object;
1057             property->defaultValue->location =
1058                     location(node->statement->firstSourceLocation(),
1059                              node->statement->lastSourceLocation());
1060             QDeclarativeScript::Value *value = _parser->_pool.New<QDeclarativeScript::Value>();
1061             value->location = location(node->statement->firstSourceLocation(),
1062                                        node->statement->lastSourceLocation());
1063             value->value = getVariant(node->statement);
1064             property->defaultValue->values.append(value);
1065         }
1066
1067         _stateStack.top().object->dynamicProperties.append(property);
1068
1069         // process QML-like initializers (e.g. property Object o: Object {})
1070         accept(node->binding);
1071     }
1072
1073     return false;
1074 }
1075
1076
1077 // UiObjectMember: UiQualifiedId UiObjectInitializer ;
1078 bool ProcessAST::visit(AST::UiObjectDefinition *node)
1079 {
1080     LocationSpan l = location(node->firstSourceLocation(),
1081                               node->lastSourceLocation());
1082
1083     const QString objectType = asString(node->qualifiedTypeNameId);
1084     const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1085
1086     defineObjectBinding(/*propertyName = */ 0, false, objectType,
1087                         typeLocation, l, node->initializer);
1088
1089     return false;
1090 }
1091
1092
1093 // UiObjectMember: UiQualifiedId T_COLON UiQualifiedId UiObjectInitializer ;
1094 bool ProcessAST::visit(AST::UiObjectBinding *node)
1095 {
1096     LocationSpan l = location(node->qualifiedTypeNameId->identifierToken,
1097                               node->initializer->rbraceToken);
1098
1099     const QString objectType = asString(node->qualifiedTypeNameId);
1100     const AST::SourceLocation typeLocation = node->qualifiedTypeNameId->identifierToken;
1101
1102     defineObjectBinding(node->qualifiedId, node->hasOnToken, objectType, 
1103                         typeLocation, l, node->initializer);
1104
1105     return false;
1106 }
1107
1108 QDeclarativeScript::Variant ProcessAST::getVariant(AST::Statement *stmt)
1109 {
1110     if (stmt) {
1111         if (AST::ExpressionStatement *exprStmt = AST::cast<AST::ExpressionStatement *>(stmt))
1112             return getVariant(exprStmt->expression);
1113
1114         return QDeclarativeScript::Variant(asStringRef(stmt), stmt);
1115     }
1116
1117     return QDeclarativeScript::Variant();
1118 }
1119
1120 QDeclarativeScript::Variant ProcessAST::getVariant(AST::ExpressionNode *expr)
1121 {
1122     if (AST::StringLiteral *lit = AST::cast<AST::StringLiteral *>(expr)) {
1123         return QDeclarativeScript::Variant(lit);
1124     } else if (expr->kind == AST::Node::Kind_TrueLiteral) {
1125         return QDeclarativeScript::Variant(true);
1126     } else if (expr->kind == AST::Node::Kind_FalseLiteral) {
1127         return QDeclarativeScript::Variant(false);
1128     } else if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(expr)) {
1129         return QDeclarativeScript::Variant(lit->value, asStringRef(expr));
1130     } else {
1131
1132         if (AST::UnaryMinusExpression *unaryMinus = AST::cast<AST::UnaryMinusExpression *>(expr)) {
1133            if (AST::NumericLiteral *lit = AST::cast<AST::NumericLiteral *>(unaryMinus->expression)) {
1134                return QDeclarativeScript::Variant(-lit->value, asStringRef(expr));
1135            }
1136         }
1137
1138         return  QDeclarativeScript::Variant(asStringRef(expr), expr);
1139     }
1140 }
1141
1142
1143 // UiObjectMember: UiQualifiedId T_COLON Statement ;
1144 bool ProcessAST::visit(AST::UiScriptBinding *node)
1145 {
1146     int propertyCount = 0;
1147     AST::UiQualifiedId *propertyName = node->qualifiedId;
1148     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1149         ++propertyCount;
1150         _stateStack.pushProperty(name->name,
1151                                  location(name));
1152     }
1153
1154     Property *prop = currentProperty();
1155
1156     if (!prop->values.isEmpty()) {
1157         QDeclarativeError error;
1158         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
1159         error.setLine(this->location(propertyName).start.line);
1160         error.setColumn(this->location(propertyName).start.column);
1161         _parser->_errors << error;
1162         return 0;
1163     }
1164
1165     QDeclarativeScript::Variant primitive;
1166
1167     if (AST::ExpressionStatement *stmt = AST::cast<AST::ExpressionStatement *>(node->statement)) {
1168         primitive = getVariant(stmt->expression);
1169     } else { // do binding
1170         primitive = QDeclarativeScript::Variant(asStringRef(node->statement), node->statement);
1171     }
1172
1173     prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset;
1174     prop->location.range.offset = node->qualifiedId->identifierToken.offset;
1175     QDeclarativeScript::Value *v = _parser->_pool.New<QDeclarativeScript::Value>();
1176     v->value = primitive;
1177     v->location = location(node->statement->firstSourceLocation(),
1178                            node->statement->lastSourceLocation());
1179
1180     prop->addValue(v);
1181
1182     while (propertyCount--)
1183         _stateStack.pop();
1184
1185     return false;
1186 }
1187
1188 // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ;
1189 bool ProcessAST::visit(AST::UiArrayBinding *node)
1190 {
1191     int propertyCount = 0;
1192     AST::UiQualifiedId *propertyName = node->qualifiedId;
1193     for (AST::UiQualifiedId *name = propertyName; name; name = name->next){
1194         ++propertyCount;
1195         _stateStack.pushProperty(name->name,
1196                                  location(name));
1197     }
1198
1199     Property* prop = currentProperty();
1200
1201     if (!prop->values.isEmpty()) {
1202         QDeclarativeError error;
1203         error.setDescription(QCoreApplication::translate("QDeclarativeParser","Property value set multiple times"));
1204         error.setLine(this->location(propertyName).start.line);
1205         error.setColumn(this->location(propertyName).start.column);
1206         _parser->_errors << error;
1207         return false;
1208     }
1209
1210     accept(node->members);
1211
1212     // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range:
1213     prop->listValueRange.offset = node->lbracketToken.offset;
1214     prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset;
1215
1216     while (propertyCount--)
1217         _stateStack.pop();
1218
1219     return false;
1220 }
1221
1222 bool ProcessAST::visit(AST::UiSourceElement *node)
1223 {
1224     QDeclarativeScript::Object *obj = currentObject();
1225
1226     if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) {
1227
1228         Object::DynamicSlot *slot = _parser->_pool.New<Object::DynamicSlot>();
1229         slot->location = location(funDecl->firstSourceLocation(), funDecl->lastSourceLocation());
1230
1231         AST::FormalParameterList *f = funDecl->formals;
1232         while (f) {
1233             slot->parameterNames << f->name.toUtf8();
1234             f = f->next;
1235         }
1236
1237         AST::SourceLocation loc = funDecl->rparenToken;
1238         loc.offset = loc.end();
1239         loc.startColumn += 1;
1240         QString body = textAt(loc, funDecl->rbraceToken);
1241         slot->name = funDecl->name;
1242         slot->body = body;
1243         obj->dynamicSlots.append(slot);
1244
1245     } else {
1246         QDeclarativeError error;
1247         error.setDescription(QCoreApplication::translate("QDeclarativeParser","JavaScript declaration outside Script element"));
1248         error.setLine(node->firstSourceLocation().startLine);
1249         error.setColumn(node->firstSourceLocation().startColumn);
1250         _parser->_errors << error;
1251     }
1252     return false;
1253 }
1254
1255 } // end of anonymous namespace
1256
1257
1258 QDeclarativeScript::Parser::Parser()
1259 : root(0), data(0)
1260 {
1261
1262 }
1263
1264 QDeclarativeScript::Parser::~Parser()
1265 {
1266     clear();
1267 }
1268
1269 namespace QDeclarativeScript {
1270 class ParserJsASTData
1271 {
1272 public:
1273     ParserJsASTData(const QString &filename)
1274     : filename(filename) {}
1275
1276     QString filename;
1277     Engine engine;
1278 };
1279 }
1280
1281 bool QDeclarativeScript::Parser::parse(const QByteArray &qmldata, const QUrl &url)
1282 {
1283     clear();
1284
1285     const QString fileName = url.toString();
1286     _scriptFile = fileName;
1287
1288     QTextStream stream(qmldata, QIODevice::ReadOnly);
1289 #ifndef QT_NO_TEXTCODEC
1290     stream.setCodec("UTF-8");
1291 #endif
1292     QString *code = _pool.NewString(stream.readAll());
1293
1294     data = new QDeclarativeScript::ParserJsASTData(fileName);
1295
1296     Lexer lexer(&data->engine);
1297     lexer.setCode(*code, /*line = */ 1);
1298
1299     QDeclarativeJS::Parser parser(&data->engine);
1300
1301     if (! parser.parse() || !_errors.isEmpty()) {
1302
1303         // Extract errors from the parser
1304         foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
1305
1306             if (m.isWarning())
1307                 continue;
1308
1309             QDeclarativeError error;
1310             error.setUrl(url);
1311             error.setDescription(m.message);
1312             error.setLine(m.loc.startLine);
1313             error.setColumn(m.loc.startColumn);
1314             _errors << error;
1315
1316         }
1317     }
1318
1319     if (_errors.isEmpty()) {
1320         ProcessAST process(this);
1321         process(*code, parser.ast());
1322
1323         // Set the url for process errors
1324         for(int ii = 0; ii < _errors.count(); ++ii)
1325             _errors[ii].setUrl(url);
1326     }
1327
1328     return _errors.isEmpty();
1329 }
1330
1331 QList<QDeclarativeScript::TypeReference*> QDeclarativeScript::Parser::referencedTypes() const
1332 {
1333     return _refTypes;
1334 }
1335
1336 QDeclarativeScript::Object *QDeclarativeScript::Parser::tree() const
1337 {
1338     return root;
1339 }
1340
1341 QList<QDeclarativeScript::Import> QDeclarativeScript::Parser::imports() const
1342 {
1343     return _imports;
1344 }
1345
1346 QList<QDeclarativeError> QDeclarativeScript::Parser::errors() const
1347 {
1348     return _errors;
1349 }
1350
1351 static void replaceWithSpace(QString &str, int idx, int n) 
1352 {
1353     QChar *data = str.data() + idx;
1354     const QChar space(QLatin1Char(' '));
1355     for (int ii = 0; ii < n; ++ii)
1356         *data++ = space;
1357 }
1358
1359 static QDeclarativeScript::LocationSpan
1360 locationFromLexer(const QDeclarativeJS::Lexer &lex, int startLine, int startColumn, int startOffset)
1361 {
1362     QDeclarativeScript::LocationSpan l;
1363
1364     l.start.line = startLine; l.start.column = startColumn;
1365     l.end.line = lex.tokenEndLine(); l.end.column = lex.tokenEndColumn();
1366     l.range.offset = startOffset;
1367     l.range.length = lex.tokenOffset() + lex.tokenLength() - startOffset;
1368
1369     return l;
1370 }
1371
1372 /*
1373 Searches for ".pragma <value>" declarations within \a script.  Currently supported pragmas
1374 are:
1375     library
1376 */
1377 QDeclarativeScript::Object::ScriptBlock::Pragmas QDeclarativeScript::Parser::extractPragmas(QString &script)
1378 {
1379     QDeclarativeScript::Object::ScriptBlock::Pragmas rv = QDeclarativeScript::Object::ScriptBlock::None;
1380
1381     const QString pragma(QLatin1String("pragma"));
1382     const QString library(QLatin1String("library"));
1383
1384     QDeclarativeJS::Lexer l(0);
1385     l.setCode(script, 0);
1386
1387     int token = l.lex();
1388
1389     while (true) {
1390         if (token != QDeclarativeJSGrammar::T_DOT)
1391             return rv;
1392
1393         int startOffset = l.tokenOffset();
1394         int startLine = l.tokenStartLine();
1395
1396         token = l.lex();
1397
1398         if (token != QDeclarativeJSGrammar::T_IDENTIFIER ||
1399             l.tokenStartLine() != startLine ||
1400             script.mid(l.tokenOffset(), l.tokenLength()) != pragma)
1401             return rv;
1402
1403         token = l.lex();
1404
1405         if (token != QDeclarativeJSGrammar::T_IDENTIFIER ||
1406             l.tokenStartLine() != startLine)
1407             return rv;
1408
1409         QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1410         int endOffset = l.tokenLength() + l.tokenOffset();
1411
1412         token = l.lex();
1413         if (l.tokenStartLine() == startLine)
1414             return rv;
1415
1416         if (pragmaValue == library) {
1417             rv |= QDeclarativeScript::Object::ScriptBlock::Shared;
1418             replaceWithSpace(script, startOffset, endOffset - startOffset);
1419         } else {
1420             return rv;
1421         }
1422     }
1423     return rv;
1424 }
1425
1426 #define CHECK_LINE if (l.tokenStartLine() != startLine) return rv;
1427 #define CHECK_TOKEN(t) if (token != QDeclarativeJSGrammar:: t) return rv;
1428
1429 static const int uriTokens[] = {
1430     QDeclarativeJSGrammar::T_IDENTIFIER, 
1431     QDeclarativeJSGrammar::T_PROPERTY, 
1432     QDeclarativeJSGrammar::T_SIGNAL, 
1433     QDeclarativeJSGrammar::T_READONLY, 
1434     QDeclarativeJSGrammar::T_ON, 
1435     QDeclarativeJSGrammar::T_BREAK, 
1436     QDeclarativeJSGrammar::T_CASE, 
1437     QDeclarativeJSGrammar::T_CATCH, 
1438     QDeclarativeJSGrammar::T_CONTINUE, 
1439     QDeclarativeJSGrammar::T_DEFAULT, 
1440     QDeclarativeJSGrammar::T_DELETE, 
1441     QDeclarativeJSGrammar::T_DO, 
1442     QDeclarativeJSGrammar::T_ELSE, 
1443     QDeclarativeJSGrammar::T_FALSE, 
1444     QDeclarativeJSGrammar::T_FINALLY, 
1445     QDeclarativeJSGrammar::T_FOR, 
1446     QDeclarativeJSGrammar::T_FUNCTION, 
1447     QDeclarativeJSGrammar::T_IF, 
1448     QDeclarativeJSGrammar::T_IN, 
1449     QDeclarativeJSGrammar::T_INSTANCEOF, 
1450     QDeclarativeJSGrammar::T_NEW, 
1451     QDeclarativeJSGrammar::T_NULL, 
1452     QDeclarativeJSGrammar::T_RETURN, 
1453     QDeclarativeJSGrammar::T_SWITCH, 
1454     QDeclarativeJSGrammar::T_THIS, 
1455     QDeclarativeJSGrammar::T_THROW, 
1456     QDeclarativeJSGrammar::T_TRUE, 
1457     QDeclarativeJSGrammar::T_TRY, 
1458     QDeclarativeJSGrammar::T_TYPEOF, 
1459     QDeclarativeJSGrammar::T_VAR, 
1460     QDeclarativeJSGrammar::T_VOID, 
1461     QDeclarativeJSGrammar::T_WHILE, 
1462     QDeclarativeJSGrammar::T_CONST, 
1463     QDeclarativeJSGrammar::T_DEBUGGER, 
1464     QDeclarativeJSGrammar::T_RESERVED_WORD, 
1465     QDeclarativeJSGrammar::T_WITH, 
1466
1467     QDeclarativeJSGrammar::EOF_SYMBOL
1468 };
1469 static inline bool isUriToken(int token)
1470 {
1471     const int *current = uriTokens;
1472     while (*current != QDeclarativeJSGrammar::EOF_SYMBOL) {
1473         if (*current == token)
1474             return true;
1475         ++current;
1476     }
1477     return false;
1478 }
1479
1480 QDeclarativeScript::Parser::JavaScriptMetaData QDeclarativeScript::Parser::extractMetaData(QString &script)
1481 {
1482     JavaScriptMetaData rv;
1483
1484     QDeclarativeScript::Object::ScriptBlock::Pragmas &pragmas = rv.pragmas;
1485
1486     const QString pragma(QLatin1String("pragma"));
1487     const QString js(QLatin1String(".js"));
1488     const QString library(QLatin1String("library"));
1489
1490     QDeclarativeJS::Lexer l(0);
1491     l.setCode(script, 0);
1492
1493     int token = l.lex();
1494
1495     while (true) {
1496         if (token != QDeclarativeJSGrammar::T_DOT)
1497             return rv;
1498
1499         int startOffset = l.tokenOffset();
1500         int startLine = l.tokenStartLine();
1501         int startColumn = l.tokenStartColumn();
1502
1503         token = l.lex();
1504
1505         CHECK_LINE;
1506
1507         if (token == QDeclarativeJSGrammar::T_IMPORT) {
1508
1509             // .import <URI> <Version> as <Identifier>
1510             // .import <file.js> as <Identifier>
1511
1512             token = l.lex();
1513
1514             CHECK_LINE;
1515
1516             if (token == QDeclarativeJSGrammar::T_STRING_LITERAL) {
1517
1518                 QString file = l.tokenText();
1519
1520                 if (!file.endsWith(js))
1521                     return rv;
1522
1523                 token = l.lex();
1524
1525                 CHECK_TOKEN(T_AS);
1526                 CHECK_LINE;
1527
1528                 token = l.lex();
1529
1530                 CHECK_TOKEN(T_IDENTIFIER);
1531                 CHECK_LINE;
1532
1533                 int endOffset = l.tokenLength() + l.tokenOffset();
1534
1535                 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1536
1537                 if (!importId.at(0).isUpper())
1538                     return rv;
1539
1540                 QDeclarativeScript::LocationSpan location =
1541                     locationFromLexer(l, startLine, startColumn, startOffset);
1542
1543                 token = l.lex();
1544                 if (l.tokenStartLine() == startLine)
1545                     return rv;
1546
1547                 replaceWithSpace(script, startOffset, endOffset - startOffset);
1548
1549                 Import import;
1550                 import.type = Import::Script;
1551                 import.uri = file;
1552                 import.qualifier = importId;
1553                 import.location = location;
1554
1555                 rv.imports << import;
1556             } else {
1557                 // URI
1558                 QString uri;
1559                 QString version;
1560
1561                 while (true) {
1562                     if (!isUriToken(token))
1563                         return rv;
1564
1565                     uri.append(l.tokenText());
1566
1567                     token = l.lex();
1568                     CHECK_LINE;
1569                     if (token != QDeclarativeJSGrammar::T_DOT)
1570                         break;
1571
1572                     uri.append(QLatin1Char('.'));
1573
1574                     token = l.lex();
1575                     CHECK_LINE;
1576                 }
1577
1578                 CHECK_TOKEN(T_NUMERIC_LITERAL);
1579                 version = script.mid(l.tokenOffset(), l.tokenLength());
1580
1581                 token = l.lex();
1582
1583                 CHECK_TOKEN(T_AS);
1584                 CHECK_LINE;
1585
1586                 token = l.lex();
1587
1588                 CHECK_TOKEN(T_IDENTIFIER);
1589                 CHECK_LINE;
1590
1591                 int endOffset = l.tokenLength() + l.tokenOffset();
1592
1593                 QString importId = script.mid(l.tokenOffset(), l.tokenLength());
1594
1595                 if (!importId.at(0).isUpper())
1596                     return rv;
1597
1598                 QDeclarativeScript::LocationSpan location =
1599                     locationFromLexer(l, startLine, startColumn, startOffset);
1600
1601                 token = l.lex();
1602                 if (l.tokenStartLine() == startLine)
1603                     return rv;
1604
1605                 replaceWithSpace(script, startOffset, endOffset - startOffset);
1606
1607                 Import import;
1608                 import.type = Import::Library;
1609                 import.uri = uri;
1610                 import.version = version;
1611                 import.qualifier = importId;
1612                 import.location = location;
1613
1614                 rv.imports << import;
1615             }
1616
1617         } else if (token == QDeclarativeJSGrammar::T_IDENTIFIER &&
1618                    script.mid(l.tokenOffset(), l.tokenLength()) == pragma) {
1619
1620             token = l.lex();
1621
1622             CHECK_TOKEN(T_IDENTIFIER);
1623             CHECK_LINE;
1624
1625             QString pragmaValue = script.mid(l.tokenOffset(), l.tokenLength());
1626             int endOffset = l.tokenLength() + l.tokenOffset();
1627
1628             if (pragmaValue == library) {
1629                 pragmas |= QDeclarativeScript::Object::ScriptBlock::Shared;
1630                 replaceWithSpace(script, startOffset, endOffset - startOffset);
1631             } else {
1632                 return rv;
1633             }
1634
1635             token = l.lex();
1636             if (l.tokenStartLine() == startLine)
1637                 return rv;
1638
1639         } else {
1640             return rv;
1641         }
1642     }
1643     return rv;
1644 }
1645
1646 void QDeclarativeScript::Parser::clear()
1647 {
1648     _imports.clear();
1649     qDeleteAll(_refTypes);
1650     _refTypes.clear();
1651     _errors.clear();
1652
1653     if (data) {
1654         delete data;
1655         data = 0;
1656     }
1657
1658     _pool.clear();
1659 }
1660
1661 QDeclarativeScript::TypeReference *QDeclarativeScript::Parser::findOrCreateType(const QString &name)
1662 {
1663     TypeReference *type = 0;
1664     int i = 0;
1665     for (; i < _refTypes.size(); ++i) {
1666         if (_refTypes.at(i)->name == name) {
1667             type = _refTypes.at(i);
1668             break;
1669         }
1670     }
1671     if (!type) {
1672         type = new TypeReference(i, name);
1673         _refTypes.append(type);
1674     }
1675
1676     return type;
1677 }
1678
1679 void QDeclarativeScript::Parser::setTree(QDeclarativeScript::Object *tree)
1680 {
1681     Q_ASSERT(! root);
1682
1683     root = tree;
1684 }
1685
1686 QT_END_NAMESPACE