qmljsbind.cpp 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "parser/qmljsast_p.h"
31
#include "qmljsbind.h"
32
#include "qmljslink.h"
33
#include "qmljscheck.h"
34
#include "qmljsmetatypesystem.h"
Roberto Raggi's avatar
Roberto Raggi committed
35
36
37

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
38
#include <QtCore/QDebug>
39
40

using namespace QmlJS;
41
42
using namespace QmlJS::AST;
using namespace QmlJS::Interpreter;
43

Roberto Raggi's avatar
Roberto Raggi committed
44
45
namespace {

Roberto Raggi's avatar
Roberto Raggi committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class ASTObjectValue: public ObjectValue
{
    UiQualifiedId *_typeName;
    UiObjectInitializer *_initializer;

public:
    ASTObjectValue(UiQualifiedId *typeName, UiObjectInitializer *initializer, Interpreter::Engine *engine)
        : ObjectValue(engine), _typeName(typeName), _initializer(initializer)
    {
    }

    virtual void processMembers(MemberProcessor *processor) const
    {
        if (_initializer) {
            for (UiObjectMemberList *it = _initializer->members; it; it = it->next) {
                UiObjectMember *member = it->member;
                if (UiPublicMember *def = cast<UiPublicMember *>(member)) {
                    if (def->name && def->memberType) {
                        const QString propName = def->name->asString();
                        const QString propType = def->memberType->asString();

                        processor->processProperty(propName, engine()->defaultValueForBuiltinType(propType));
                    }
                }
            }
        }
        ObjectValue::processMembers(processor);
    }
};

Roberto Raggi's avatar
Roberto Raggi committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class ASTFunctionValue: public FunctionValue
{
    FunctionDeclaration *_ast;
    QList<NameId *> _argumentNames;

public:
    ASTFunctionValue(FunctionDeclaration *ast, Interpreter::Engine *engine)
        : FunctionValue(engine), _ast(ast)
    {
        setPrototype(engine->functionPrototype());

        for (FormalParameterList *it = ast->formals; it; it = it->next)
            _argumentNames.append(it->name);
    }

    FunctionDeclaration *ast() const { return _ast; }

    virtual const Value *returnValue() const
    {
        return engine()->undefinedValue();
    }

    virtual int argumentCount() const
    {
        return _argumentNames.size();
    }

    virtual const Value *argument(int) const
    {
        return engine()->undefinedValue();
    }

    virtual QString argumentName(int index) const
    {
        if (index < _argumentNames.size()) {
            if (NameId *nameId = _argumentNames.at(index))
                return nameId->asString();
        }

        return FunctionValue::argumentName(index);
    }

    virtual bool isVariadic() const
    {
        return true;
    }
};

124
125
126
127
128
129
class ProcessSourceElements: protected AST::Visitor
{
    Interpreter::Engine *_interp;

public:
    ProcessSourceElements(Interpreter::Engine *interp)
130
131
        : _interp(interp),
          typeOfExpression(interp)
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    {
    }

    void operator()(AST::Node *node)
    {
        if (node)
            node->accept(this);
    }

protected:
    using AST::Visitor::visit;

    virtual bool visit(FunctionDeclaration *ast)
    {
        if (ast->name)
            _interp->globalObject()->setProperty(ast->name->asString(), new ASTFunctionValue(ast, _interp));

        return false;
    }

    virtual bool visit(VariableDeclaration *ast)
    {
154
155
156
157
158
159
160
161
        if (ast->name) {
            const Value *value = _interp->undefinedValue();

            if (ast->expression)
                value = typeOfExpression(ast->expression, _interp->globalObject());

            _interp->globalObject()->setProperty(ast->name->asString(), value);
        }
162
163
164

        return false;
    }
165
166

    Check typeOfExpression;
167
168
};

Roberto Raggi's avatar
Roberto Raggi committed
169
170
} // end of anonymous namespace

Roberto Raggi's avatar
Roberto Raggi committed
171
Bind::Bind(Document::Ptr doc, const Snapshot &snapshot, Interpreter::Engine *interp)
Roberto Raggi's avatar
Roberto Raggi committed
172
    : _doc(doc),
Roberto Raggi's avatar
Roberto Raggi committed
173
      _snapshot(snapshot),
Roberto Raggi's avatar
Roberto Raggi committed
174
      _interp(interp),
175
176
177
      _currentObjectValue(0),
      _typeEnvironment(0),
      _idEnvironment(0),
178
      _functionEnvironment(0),
179
      _rootObjectValue(0)
180
{
Roberto Raggi's avatar
Roberto Raggi committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    if (_doc && _doc->qmlProgram() != 0) {
        UiProgram *program = _doc->qmlProgram();

        _currentObjectValue = 0;
        _typeEnvironment = _interp->newObject(/*prototype =*/ 0);
        _idEnvironment = _interp->newObject(/*prototype =*/ 0);
        _functionEnvironment = _interp->newObject(/*prototype =*/ 0);
        _rootObjectValue = 0;

        _qmlObjectDefinitions.clear();
        _qmlObjectBindings.clear();

        accept(program);
    }
195
196
197
198
199
200
}

Bind::~Bind()
{
}

201
202
203
204
205
QStringList Bind::includedScripts() const
{
    return _includedScripts;
}

Roberto Raggi's avatar
Roberto Raggi committed
206
ObjectValue *Bind::switchObjectValue(ObjectValue *newObjectValue)
207
{
Roberto Raggi's avatar
Roberto Raggi committed
208
209
210
    ObjectValue *oldObjectValue = _currentObjectValue;
    _currentObjectValue = newObjectValue;
    return oldObjectValue;
211
}
212

213
214
215
216
217
218
219
220
221
ObjectValue *Bind::scopeChainAt(Document::Ptr currentDocument, const Snapshot &snapshot,
                                Interpreter::Engine *interp, AST::UiObjectMember *currentObject)
{
    Bind *currentBind = 0;
    QList<Bind *> binds;

    Snapshot::const_iterator end = snapshot.end();
    for (Snapshot::const_iterator iter = snapshot.begin(); iter != end; ++iter) {
        Document::Ptr doc = *iter;
Roberto Raggi's avatar
Roberto Raggi committed
222
        Bind *newBind = new Bind(doc, snapshot, interp);
223
224
225
        binds += newBind;
        if (doc == currentDocument)
            currentBind = newBind;
226
227
    }

Roberto Raggi's avatar
Roberto Raggi committed
228
229
230
    LinkImports linkImports;
    Link link;

231
    // link the import directives
Roberto Raggi's avatar
Roberto Raggi committed
232
    linkImports(binds);
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

    // link the scripts
    QStringList includedScriptFiles;
    foreach (Bind *bind, binds)
        includedScriptFiles += bind->includedScripts();

    includedScriptFiles.removeDuplicates();

    ProcessSourceElements processSourceElements(interp);

    foreach (const QString &scriptFile, includedScriptFiles) {
        if (Document::Ptr scriptDoc = snapshot.document(scriptFile)) {
            if (AST::Program *program = scriptDoc->jsProgram()) {
                processSourceElements(program);
            }
        }
    }

251
252
    ObjectValue *scope = interp->globalObject();
    if (currentBind)
Roberto Raggi's avatar
Roberto Raggi committed
253
        scope = link(binds, currentBind, currentObject);
254

255
256
257
    qDeleteAll(binds);

    return scope;
258
259
}

Roberto Raggi's avatar
Roberto Raggi committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
QString Bind::toString(UiQualifiedId *qualifiedId, QChar delimiter)
{
    QString result;

    for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) {
        if (iter != qualifiedId)
            result += delimiter;

        if (iter->name)
            result += iter->name->asString();
    }

    return result;
}

Roberto Raggi's avatar
Roberto Raggi committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
ExpressionNode *Bind::expression(UiScriptBinding *ast) const
{
    if (ExpressionStatement *statement = cast<ExpressionStatement *>(ast->statement))
        return statement->expression;

    return 0;
}

void Bind::processScript(AST::UiQualifiedId *qualifiedId, AST::UiObjectInitializer *initializer)
{
    Q_UNUSED(qualifiedId);

    if (! initializer)
        return;

    for (UiObjectMemberList *it = initializer->members; it; it = it->next) {
        if (UiScriptBinding *binding = cast<UiScriptBinding *>(it->member)) {
            const QString bindingName = toString(binding->qualifiedId);
            if (bindingName == QLatin1String("source")) {
                if (StringLiteral *literal = cast<StringLiteral *>(expression(binding))) {
                    QFileInfo fileInfo(QDir(_doc->path()), literal->value->asString());
296
297
                    const QString scriptPath = fileInfo.absoluteFilePath();
                    _includedScripts.append(scriptPath);
Roberto Raggi's avatar
Roberto Raggi committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
                }
            }
        } else if (UiSourceElement *binding = cast<UiSourceElement *>(it->member)) {
            if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(binding->sourceElement)) {
                accept(decl); // process the function declaration
            } else {
                // ### unexpected source element
            }
        } else {
            // ### unexpected binding.
        }
    }
}

Roberto Raggi's avatar
Roberto Raggi committed
312
ObjectValue *Bind::bindObject(UiQualifiedId *qualifiedTypeNameId, UiObjectInitializer *initializer)
313
{
Roberto Raggi's avatar
Roberto Raggi committed
314
315
    ObjectValue *parentObjectValue = 0;
    const QString typeName = toString(qualifiedTypeNameId);
316

Roberto Raggi's avatar
Roberto Raggi committed
317
    if (typeName == QLatin1String("Script")) {
Roberto Raggi's avatar
Roberto Raggi committed
318
319
        // Script blocks all contribute to the same scope
        parentObjectValue = switchObjectValue(_functionEnvironment);
Roberto Raggi's avatar
Roberto Raggi committed
320
321
        processScript(qualifiedTypeNameId, initializer);
        return switchObjectValue(parentObjectValue);
Roberto Raggi's avatar
Roberto Raggi committed
322
323
    }

Roberto Raggi's avatar
Roberto Raggi committed
324
325
326
327
328
329
330
331
332
    // normal component instance
    ASTObjectValue *objectValue = new ASTObjectValue(qualifiedTypeNameId, initializer, _interp);
    parentObjectValue = switchObjectValue(objectValue);

    if (parentObjectValue)
        objectValue->setProperty(QLatin1String("parent"), parentObjectValue);
    else
        _rootObjectValue = objectValue;

Roberto Raggi's avatar
Roberto Raggi committed
333
334
335
    accept(initializer);

    return switchObjectValue(parentObjectValue);
336
337
}

Roberto Raggi's avatar
Roberto Raggi committed
338
void Bind::accept(Node *node)
339
{
Roberto Raggi's avatar
Roberto Raggi committed
340
    Node::accept(node, this);
341
342
}

343
344
345
346
347
348
349
350
351
352
353
354
/*
  import Qt 4.6
  import Qt 4.6 as Xxx
  (import com.nokia.qt is the same as the ones above)

  import "content"
  import "content" as Xxx
  import "content" 4.6
  import "content" 4.6 as Xxx

  import "http://www.ovi.com/" as Ovi
 */
355
// ### TODO: Move to LinkImports
356
bool Bind::visit(UiImport *ast)
357
{
358
359
360
361
    if (! (ast->importUri || ast->fileName))
        return false; // nothing to do.

    ObjectValue *namespaceObject = 0;
362
363
364
365

    if (ast->asToken.isValid()) { // with namespace we insert an object in the type env. to hold the imported types
        if (!ast->importId)
            return false; // this should never happen, but better be safe than sorry
Roberto Raggi's avatar
Roberto Raggi committed
366

367
368
        namespaceObject = _interp->newObject(/*prototype */ 0);

369
        _typeEnvironment->setProperty(ast->importId->asString(), namespaceObject);
Roberto Raggi's avatar
Roberto Raggi committed
370

371
372
373
374
375
376
377
    } else { // without namespace we insert all types directly into the type env.
        namespaceObject = _typeEnvironment;
    }

    // look at files first

    // else try the metaobject system
378
    if (ast->importUri) {
Roberto Raggi's avatar
Roberto Raggi committed
379
        const QString package = toString(ast->importUri, '/');
380
381
382
383
384
385
386
387
388
389
390
391
392
393
        int majorVersion = -1; // ### TODO: Check these magic version numbers
        int minorVersion = -1; // ### TODO: Check these magic version numbers

        if (ast->versionToken.isValid()) {
            const QString versionString = _doc->source().mid(ast->versionToken.offset, ast->versionToken.length);
            const int dotIdx = versionString.indexOf(QLatin1Char('.'));
            if (dotIdx == -1) {
                // only major (which is probably invalid, but let's handle it anyway)
                majorVersion = versionString.toInt();
                minorVersion = 0; // ### TODO: Check with magic version numbers above
            } else {
                majorVersion = versionString.left(dotIdx).toInt();
                minorVersion = versionString.mid(dotIdx + 1).toInt();
            }
394
395
        }
#ifndef NO_DECLARATIVE_BACKEND
396
397
398
        foreach (QmlObjectValue *object, _interp->metaTypeSystem().staticTypesForImport(package, majorVersion, minorVersion)) {
            namespaceObject->setProperty(object->qmlTypeName(), object);
        }
399
#endif // NO_DECLARATIVE_BACKEND
400
    }
401
402

    return false;
403
404
}

Roberto Raggi's avatar
Roberto Raggi committed
405
bool Bind::visit(UiPublicMember *)
406
{
Roberto Raggi's avatar
Roberto Raggi committed
407
    // nothing to do.
408
    return false;
409
410
}

411
412
413
bool Bind::visit(UiObjectDefinition *ast)
{
    ObjectValue *value = bindObject(ast->qualifiedTypeNameId, ast->initializer);
414
    _qmlObjectDefinitions.insert(ast, value);
415
416

    return false;
417
418
}

419
420
421
422
bool Bind::visit(UiObjectBinding *ast)
{
//    const QString name = serialize(ast->qualifiedId);
    ObjectValue *value = bindObject(ast->qualifiedTypeNameId, ast->initializer);
423
    _qmlObjectBindings.insert(ast, value);
424
425
426
427
428
429
430
431
    // ### FIXME: we don't handle dot-properties correctly (i.e. font.size)
//    _currentObjectValue->setProperty(name, value);

    return false;
}

bool Bind::visit(UiScriptBinding *ast)
{
Roberto Raggi's avatar
Roberto Raggi committed
432
    if (toString(ast->qualifiedId) == QLatin1String("id")) {
433
434
435
436
        if (ExpressionStatement *e = cast<ExpressionStatement*>(ast->statement))
            if (IdentifierExpression *i = cast<IdentifierExpression*>(e->expression))
                if (i->name)
                    _idEnvironment->setProperty(i->name->asString(), _currentObjectValue);
Roberto Raggi's avatar
Roberto Raggi committed
437
    }
438
439
440
441
442

    return false;
}

bool Bind::visit(UiArrayBinding *)
443
{
444
445
    // ### FIXME: do we need to store the members into the property? Or, maybe the property type is an JS Array?

446
447
448
    return true;
}

449
bool Bind::visit(FunctionDeclaration *ast)
450
{
451
452
453
454
455
456
    if (!ast->name)
        return false;
    // the first declaration counts
    if (_currentObjectValue->property(ast->name->asString()))
        return false;

Roberto Raggi's avatar
Roberto Raggi committed
457
    ASTFunctionValue *function = new ASTFunctionValue(ast, _interp);
458
459
    _currentObjectValue->setProperty(ast->name->asString(), function);
    return false; // ### eventually want to visit function bodies
460
}