void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
                                                const LookupItem &lookupItem,
                                                const LookupContext &context,
                                                const Scope *scope)
{
    Symbol *declaration = lookupItem.declaration();
    if (!declaration) {
        const QString &type = Overview().prettyType(lookupItem.type(), QString());
        //  special case for bug QTCREATORBUG-4780
        if (scope && scope->isFunction()
                && lookupItem.type().match(scope->asFunction()->returnType())) {
            return;
        }
        m_element = QSharedPointer<CppElement>(new Unknown(type));
    } else {
        const FullySpecifiedType &type = declaration->type();
        if (declaration->isNamespace()) {
            m_element = QSharedPointer<CppElement>(new CppNamespace(declaration));
        } else if (declaration->isClass()
                   || declaration->isForwardClassDeclaration()
                   || (declaration->isTemplate() && declaration->asTemplate()->declaration()
                       && (declaration->asTemplate()->declaration()->isClass()
                           || declaration->asTemplate()->declaration()->isForwardClassDeclaration()))) {
            LookupContext contextToUse = context;
            if (declaration->isForwardClassDeclaration())
                if (Symbol *classDeclaration =
                        m_symbolFinder.findMatchingClassDeclaration(declaration, snapshot)) {
                    declaration = classDeclaration;
                    const QString fileName = QString::fromUtf8(declaration->fileName(),
                                                               declaration->fileNameLength());
                    const Document::Ptr declarationDocument = snapshot.document(fileName);
                    if (declarationDocument != context.thisDocument())
                        contextToUse = LookupContext(declarationDocument, snapshot);
                }

            CppClass *cppClass = new CppClass(declaration);
            if (m_lookupBaseClasses)
                cppClass->lookupBases(declaration, contextToUse);
            if (m_lookupDerivedClasses)
                cppClass->lookupDerived(declaration, snapshot);
            m_element = QSharedPointer<CppElement>(cppClass);
        } else if (Enum *enumDecl = declaration->asEnum()) {
            m_element = QSharedPointer<CppElement>(new CppEnum(enumDecl));
        } else if (EnumeratorDeclaration *enumerator = dynamic_cast<EnumeratorDeclaration *>(declaration)) {
            m_element = QSharedPointer<CppElement>(new CppEnumerator(enumerator));
        } else if (declaration->isTypedef()) {
            m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
        } else if (declaration->isFunction()
                   || (type.isValid() && type->isFunctionType())
                   || declaration->isTemplate()) {
            m_element = QSharedPointer<CppElement>(new CppFunction(declaration));
        } else if (declaration->isDeclaration() && type.isValid()) {
            m_element = QSharedPointer<CppElement>(
                new CppVariable(declaration, context, lookupItem.scope()));
        } else {
            m_element = QSharedPointer<CppElement>(new CppDeclarableElement(declaration));
        }
    }
}
bool DependencyTable::isValidFor(const Snapshot &snapshot) const
{
    const int documentCount = snapshot.size();
    if (documentCount != files.size())
        return false;

    for (Snapshot::const_iterator it = snapshot.begin(); it != snapshot.end(); ++it) {
        QHash<QString, QStringList>::const_iterator i = includesPerFile.find(it.key());
        if (i == includesPerFile.end())
            return false;

        if (i.value() != it.value()->includedFiles())
            return false;
    }

    return true;
}
Beispiel #3
0
void DB2Mon::getSnapshot(JNIEnv* env, sqlma *ma_ptr, Snapshot& snap)
{
	int		rc = 0;  // return code
	sqlca	sqlca;
	sqluint32 outputFormat;

	// Determine the size of the snapshot
	db2GetSnapshotSizeData getSnapshotSizeParam;
	sqluint32 buffer_sz;  // estimated buffer size

	getSnapshotSizeParam.piSqlmaData = ma_ptr;
	getSnapshotSizeParam.poBufferSize = &buffer_sz;
	getSnapshotSizeParam.iVersion = SQLM_CURRENT_VERSION;
	getSnapshotSizeParam.iNodeNumber = m_aggAllNodes ? SQLM_ALL_NODES : SQLM_CURRENT_NODE;
	getSnapshotSizeParam.iSnapshotClass = SQLM_CLASS_DEFAULT;

	rc = db2GetSnapshotSize(db2Version810, &getSnapshotSizeParam, &sqlca);
	APICHECK(env, sqlca);

	// Allocate memory to a buffer to hold snapshot monitor data.
	// Add about 10k to make sure we avoid the reallocation below
	buffer_sz = buffer_sz + SNAPSHOT_BUFFER_UNIT_SZ;
	MemObj	ptrBuffer(buffer_sz);
	char * buffer_ptr = ptrBuffer.get();
	sqlm_collected collected;  // returned sqlm_collected structure
	memset(&collected, '\0', sizeof(struct sqlm_collected));

	db2GetSnapshotData getSnapshotParam;
	getSnapshotParam.piSqlmaData = ma_ptr;
	getSnapshotParam.poCollectedData = &collected;
	getSnapshotParam.iBufferSize = buffer_sz;
	getSnapshotParam.poBuffer = buffer_ptr;
	getSnapshotParam.iVersion = SQLM_CURRENT_VERSION;
	getSnapshotParam.iStoreResult = 0;
	getSnapshotParam.iNodeNumber = m_aggAllNodes ? SQLM_ALL_NODES : SQLM_CURRENT_NODE;
	getSnapshotParam.poOutputFormat = &outputFormat;
	getSnapshotParam.iSnapshotClass = SQLM_CLASS_DEFAULT;

	rc = db2GetSnapshot(db2Version810, &getSnapshotParam, &sqlca);
	APICHECK(env, sqlca);

	// If buffer was too small enlarge it and repeat until succeeded
	while (sqlca.sqlcode == 1606)
	{
		buffer_sz = buffer_sz + SNAPSHOT_BUFFER_UNIT_SZ;
		ptrBuffer.resize(buffer_sz);
		buffer_ptr = ptrBuffer.get();

		getSnapshotParam.iBufferSize = buffer_sz;
		getSnapshotParam.poBuffer = buffer_ptr;

		rc = db2GetSnapshot(db2Version810, &getSnapshotParam, &sqlca);
		APICHECK(env, sqlca);
	}

	// Fill the snapshot object from the memory buffer
	snap.initialize(env, buffer_ptr);
}
void tst_FindUsages::staticVariables()
{
    const QByteArray src = "\n"
            "struct Outer\n"
            "{\n"
            "    static int Foo;\n"
            "    struct Inner\n"
            "    {\n"
            "        Outer *outer;\n"
            "        void foo();\n"
            "    };\n"
            "};\n"
            "\n"
            "int Outer::Foo = 42;\n"
            "\n"
            "void Outer::Inner::foo()\n"
            "{\n"
            "    Foo  = 7;\n"
            "    Outer::Foo = 7;\n"
            "    outer->Foo = 7;\n"
            "}\n"
            ;
    Document::Ptr doc = Document::create("staticVariables");
    doc->setUtf8Source(src);
    doc->parse();
    doc->check();

    QVERIFY(doc->diagnosticMessages().isEmpty());
    QCOMPARE(doc->globalSymbolCount(), 3U);

    Snapshot snapshot;
    snapshot.insert(doc);

    Class *c = doc->globalSymbolAt(0)->asClass();
    QVERIFY(c);
    QCOMPARE(c->name()->identifier()->chars(), "Outer");
    QCOMPARE(c->memberCount(), 2U);
    Declaration *d = c->memberAt(0)->asDeclaration();
    QVERIFY(d);
    QCOMPARE(d->name()->identifier()->chars(), "Foo");

    FindUsages findUsages(src, doc, snapshot);
    findUsages(d);
    QCOMPARE(findUsages.usages().size(), 5);
}
static Document::Ptr getParsedDocument(const QString &fileName, CppModelManagerInterface::WorkingCopy &workingCopy, Snapshot &snapshot)
{
    QString src;
    if (workingCopy.contains(fileName)) {
        src = workingCopy.source(fileName);
    } else {
        QFile file(fileName);
        if (file.open(QFile::ReadOnly))
            src = QTextStream(&file).readAll(); // ### FIXME
    }

    QByteArray source = snapshot.preprocessedCode(src, fileName);

    Document::Ptr doc = snapshot.documentFromSource(source, fileName);
    doc->check();
    snapshot.insert(doc);
    return doc;
}
static Document::Ptr getParsedDocument(const QString &fileName,
                                       CppTools::WorkingCopy &workingCopy,
                                       Snapshot &snapshot)
{
    QByteArray src;
    if (workingCopy.contains(fileName)) {
        src = workingCopy.source(fileName);
    } else {
        Utils::FileReader reader;
        if (reader.fetch(fileName)) // ### FIXME error reporting
            src = QString::fromLocal8Bit(reader.data()).toUtf8();
    }

    Document::Ptr doc = snapshot.preprocessedDocument(src, fileName);
    doc->check();
    snapshot.insert(doc);
    return doc;
}
Beispiel #7
0
void filterLocalChange()
{
	std::shared_ptr<change_xfiles> spChangeFiles(new change_xfiles());
	snapshot.filterLocalChange(spChangeFiles);

	cout << "lc: 新增文件 " << spChangeFiles->m_addXfile.size() << "新增文件夹" << spChangeFiles->m_addFolder.size();
	cout << " 更新文件" << spChangeFiles->m_updateXfile.size() << " 删除文件" << spChangeFiles->m_deleteXfile.size();
	cout << " 删除文件夹" << spChangeFiles->m_deleteFolder.size()<< endl;
}
Beispiel #8
0
Bool SignerReal::notarize( PublicKey pubkey, Signature signature, const void* data, Size size, Monitor& monitor )
{
	if (!check_interface(monitor)) return false;

	eprovider::TheKey thepubkey = creator.getCreatureCurrentTheKey(pubkey);

	Image signimage = signature.encode(monitor);
	Snapshot signblock = signimage.snapshot();

	Bool result;

	RECOVER_CALL( (iface->notarizeStart(session, signblock.get(), signblock.size(), signblock.encid(), thepubkey, error)) );
	RECOVER_CALL( (iface->notarizeProcess(session, data, size, error)) );
	RECOVER_CALL( (result = iface->notarizeStop(session, error)) );

	return result;

}
Beispiel #9
0
void QueryResultsNode::unlock(const Snapshot &snapshot)
{
    typedef QMap<QueryResultItem *, Union> Map;
    qint32 lastColumn = columnCount(QModelIndex()) - 1;
    QueryResultPropertyItem *property;
    Map map;

    for (Snapshot::const_iterator i = snapshot.begin(), end = snapshot.end(); i != end; ++i)
    {
        property = static_cast<QueryResultPropertyItem *>((*i).first->parent());
        map[property].add(property->indexOf((*i).first.data()));
        (*i).first.as<QueryResultValueItem>()->unlock();
    }

    for (Map::const_iterator i = map.constBegin(), end = map.constEnd(); i != end; ++i)
        for (Union::List::size_type q = 0, size = (*i).size(); q < size; ++q)
            emit dataChanged(createIndex((*i).at(q).top(), 0, i.key()->at((*i).at(q).top())),
                             createIndex((*i).at(q).bottom(), lastColumn, i.key()->at((*i).at(q).bottom())));
}
void QmlTaskManager::collectMessages(
        QFutureInterface<FileErrorMessages> &future,
        Snapshot snapshot, QList<ModelManagerInterface::ProjectInfo> projectInfos,
        ViewerContext vContext, bool updateSemantic)
{
    foreach (const ModelManagerInterface::ProjectInfo &info, projectInfos) {
        QHash<QString, QList<DiagnosticMessage> > linkMessages;
        ContextPtr context;
        if (updateSemantic) {
            Link link(snapshot, vContext, snapshot.libraryInfo(info.qtImportsPath));
            context = link(&linkMessages);
        }

        foreach (const QString &fileName, info.sourceFiles) {
            Document::Ptr document = snapshot.document(fileName);
            if (!document)
                continue;

            FileErrorMessages result;
            result.fileName = fileName;
            if (Document::isFullySupportedLanguage(document->language())) {
                result.tasks = convertToTasks(document->diagnosticMessages(),
                                              Utils::FileName::fromString(fileName),
                                              Core::Id(Constants::TASK_CATEGORY_QML));

                if (updateSemantic) {
                    result.tasks += convertToTasks(linkMessages.value(fileName),
                                                   Utils::FileName::fromString(fileName),
                                                   Core::Id(Constants::TASK_CATEGORY_QML_ANALYSIS));

                    Check checker(document, context);
                    result.tasks += convertToTasks(checker(),
                                                   Utils::FileName::fromString(fileName),
                                                   Core::Id(Constants::TASK_CATEGORY_QML_ANALYSIS));
                }
            }

            if (!result.tasks.isEmpty())
                future.reportResult(result);
            if (future.isCanceled())
                break;
        }
    }
void PluginDumper::onLoadBuiltinTypes(const QmlJS::ModelManagerInterface::ProjectInfo &info, bool force)
{
    if (info.qmlDumpPath.isEmpty() || info.qtImportsPath.isEmpty())
        return;

    const QString importsPath = QDir::cleanPath(info.qtImportsPath);
    if (m_runningQmldumps.values().contains(importsPath))
        return;

    LibraryInfo builtinInfo;
    if (!force) {
        const Snapshot snapshot = m_modelManager->snapshot();
        builtinInfo = snapshot.libraryInfo(info.qtImportsPath);
        if (builtinInfo.isValid())
            return;
    }
    builtinInfo = LibraryInfo(LibraryInfo::Found);
    m_modelManager->updateLibraryInfo(info.qtImportsPath, builtinInfo);

    // prefer QTDIR/imports/builtins.qmltypes if available
    const QString builtinQmltypesPath = info.qtImportsPath + QLatin1String("/builtins.qmltypes");
    if (QFile::exists(builtinQmltypesPath)) {
        loadQmltypesFile(QStringList(builtinQmltypesPath), info.qtImportsPath, builtinInfo);
        return;
    }
    // QTDIR/imports/QtQuick1/builtins.qmltypes was used in developer builds of 5.0.0, 5.0.1
    const QString builtinQmltypesPath2 = info.qtImportsPath
            + QLatin1String("/QtQuick1/builtins.qmltypes");
    if (QFile::exists(builtinQmltypesPath2)) {
        loadQmltypesFile(QStringList(builtinQmltypesPath2), info.qtImportsPath, builtinInfo);
        return;
    }

    // run qmldump
    QProcess *process = new QProcess(this);
    process->setEnvironment(info.qmlDumpEnvironment.toStringList());
    connect(process, SIGNAL(finished(int)), SLOT(qmlPluginTypeDumpDone(int)));
    connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(qmlPluginTypeDumpError(QProcess::ProcessError)));
    QStringList args(QLatin1String("--builtins"));
    process->start(info.qmlDumpPath, args);
    m_runningQmldumps.insert(process, info.qtImportsPath);
    m_qtToInfo.insert(info.qtImportsPath, info);
}
/// Currently, we return the end of fileName.cpp
/// \todo take the definitions of the surrounding declarations into account
QList<InsertionLocation> InsertionPointLocator::methodDefinition(
    Declaration *declaration) const
{
    QList<InsertionLocation> result;
    if (!declaration)
        return result;

    const QString declFileName = QString::fromUtf8(declaration->fileName(),
                                                   declaration->fileNameLength());
    QString target = declFileName;
    if (!isSourceFile(declFileName)) {
        Internal::CppToolsPlugin *cpptools = Internal::CppToolsPlugin::instance();
        QString candidate = cpptools->correspondingHeaderOrSource(declFileName);
        if (!candidate.isEmpty())
            target = candidate;
    }

    Document::Ptr doc = m_refactoringChanges->file(target).cppDocument();
    if (doc.isNull())
        return result;

    Snapshot simplified = m_refactoringChanges->snapshot().simplified(doc);
    if (Symbol *s = simplified.findMatchingDefinition(declaration)) {
        if (Function *f = s->asFunction()) {
            if (f->isConst() == declaration->type().isConst()
                    && f->isVolatile() == declaration->type().isVolatile())
                return result;
        }
    }

    TranslationUnit *xUnit = doc->translationUnit();
    unsigned tokenCount = xUnit->tokenCount();
    if (tokenCount < 2) // no tokens available
        return result;

    unsigned line = 0, column = 0;
    xUnit->getTokenEndPosition(xUnit->tokenCount() - 2, &line, &column);

    const QLatin1String prefix("\n\n");
    result.append(InsertionLocation(target, prefix, QString(), line, column));

    return result;
}
void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)
{
    QProcess *process = qobject_cast<QProcess *>(sender());
    if (!process)
        return;
    process->deleteLater();

    const QString libraryPath = m_runningQmldumps.take(process);

    Core::MessageManager *messageManager = Core::MessageManager::instance();
    const QString errorMessages = process->readAllStandardError();
    messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));

    if (!libraryPath.isEmpty()) {
        const Snapshot snapshot = m_modelManager->snapshot();
        LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
        libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
    }
}
Beispiel #14
0
//--------------------------------
int main(int argc, char **argv)
{
    init(argc, argv, "snapshot");
    
    NodeHandle nh;
    Snapshot snapshot;
    
    Publisher* mainsPub = snapshot.getPublisher();

    Subscriber sub = nh.subscribe<sensor_msgs::Image>("/camera/rgb/image_rect_color",
							                            1,
							                            &Snapshot::callback,
							                            &snapshot);

    *mainsPub = nh.advertise<sensor_msgs::Image>("/person_recognizer/rgb/image_rect_color", 1);
    
    spin();
    
    return EXIT_SUCCESS;
}
QList<CppTools::IndexItem::Ptr> CppCurrentDocumentFilter::itemsOfCurrentDocument()
{
    QMutexLocker locker(&m_mutex);

    if (m_currentFileName.isEmpty())
        return QList<CppTools::IndexItem::Ptr>();

    if (m_itemsOfCurrentDoc.isEmpty()) {
        const Snapshot snapshot = m_modelManager->snapshot();
        if (const Document::Ptr thisDocument = snapshot.document(m_currentFileName)) {
            IndexItem::Ptr rootNode = search(thisDocument);
            rootNode->visitAllChildren([&](const IndexItem::Ptr &info) -> IndexItem::VisitorResult {
                m_itemsOfCurrentDoc.append(info);
                return IndexItem::Recurse;
            });
        }
    }

    return m_itemsOfCurrentDoc;
}
void PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
{
    const QString canonicalLibraryPath = QDir::cleanPath(libraryPath);
    if (m_runningQmldumps.values().contains(canonicalLibraryPath))
        return;
    const Snapshot snapshot = m_modelManager->snapshot();
    const LibraryInfo libraryInfo = snapshot.libraryInfo(canonicalLibraryPath);
    if (libraryInfo.pluginTypeInfoStatus() != LibraryInfo::NoTypeInfo)
        return;

    // avoid inserting the same plugin twice
    int index;
    for (index = 0; index < m_plugins.size(); ++index) {
        if (m_plugins.at(index).qmldirPath == libraryPath)
            break;
    }
    if (index == m_plugins.size())
        m_plugins.append(Plugin());

    Plugin &plugin = m_plugins[index];
    plugin.qmldirPath = canonicalLibraryPath;
    plugin.importPath = importPath;
    plugin.importUri = importUri;
    plugin.importVersion = importVersion;

    // watch plugin libraries
    foreach (const QmlDirParser::Plugin &plugin, snapshot.libraryInfo(canonicalLibraryPath).plugins()) {
        const QString pluginLibrary = resolvePlugin(canonicalLibraryPath, plugin.path, plugin.name);
        pluginWatcher()->addFile(pluginLibrary, Utils::FileSystemWatcher::WatchModifiedDate);
        m_libraryToPluginIndex.insert(pluginLibrary, index);
    }

    // watch library xml file
    if (plugin.hasPredumpedQmlTypesFile()) {
        const QString &path = plugin.predumpedQmlTypesFilePath();
        pluginWatcher()->addFile(path, Utils::FileSystemWatcher::WatchModifiedDate);
        m_libraryToPluginIndex.insert(path, index);
    }

    dump(plugin);
}
void DependencyTable::build(const Snapshot &snapshot)
{
    includesPerFile.clear();
    files.clear();
    fileIndex.clear();
    includes.clear();
    includeMap.clear();

    const int documentCount = snapshot.size();
    files.resize(documentCount);
    includeMap.resize(documentCount);

    int i = 0;
    for (Snapshot::const_iterator it = snapshot.begin(); it != snapshot.end();
            ++it, ++i) {
        files[i] = it.key();
        fileIndex[it.key()] = i;
    }

    for (int i = 0; i < files.size(); ++i) {
        const QString fileName = files.at(i);
        if (Document::Ptr doc = snapshot.document(files.at(i))) {
            QBitArray bitmap(files.size());
            QList<int> directIncludes;
            const QStringList documentIncludes = doc->includedFiles();
            includesPerFile.insert(fileName, documentIncludes);

            foreach (const QString &includedFile, documentIncludes) {
                int index = fileIndex.value(includedFile);

                if (index == -1)
                    continue;
                else if (! directIncludes.contains(index))
                    directIncludes.append(index);

                bitmap.setBit(index, true);
            }

            includeMap[i] = bitmap;
            includes[i] = directIncludes;
        }
Beispiel #18
0
//-----------------------------------------------------------------------
bool OperatorManager::checkSnapshot(const Snapshot& snapshot) const
{
    GroupMap::const_iterator itGroup = mGroups.begin();
    Snapshot::const_iterator itSnapshot = snapshot.begin();
    while (itGroup != mGroups.end())
    {
        const Group* group = itGroup->second;
        if (!group->getUndoOperators().empty())
        {
            if (itSnapshot == snapshot.end())
                return false;
            if (itGroup->first != itSnapshot->first)
                return false;
            if (group->getUndoOperators().front()->getTimestamp() != itSnapshot->second)
                return false;
            ++itSnapshot;
        }
        ++itGroup;
    }
    return itSnapshot == snapshot.end();
}
Beispiel #19
0
int main ( int argc, char ** argv )
{	
	if ( argc != 3 )
	{
		printf("Usage: %s <input file> <output file>\n", *argv);
		return 1;
	}
	
	Snapshot snapshot;
	
	TaskFactory * inputTasks = snapshot.read( argv[1] );
	
	if ( inputTasks == 0 ) return 1;
	Algorithm algorithm ( inputTasks );
	Shedule result = algorithm.shedule();
	
	if ( !snapshot.write( argv[2], result, inputTasks ) ) return 1;
	
	printf("Success\n");
	return 0;
}
void PluginDumper::qmlPluginTypeDumpDone(int exitCode)
{
    QProcess *process = qobject_cast<QProcess *>(sender());
    if (!process)
        return;
    process->deleteLater();

    const QString libraryPath = m_runningQmldumps.take(process);
    const Snapshot snapshot = m_modelManager->snapshot();
    LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);

    if (exitCode != 0) {
        Core::MessageManager *messageManager = Core::MessageManager::instance();
        const QString errorMessages = process->readAllStandardError();
        messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
        libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(errorMessages));
    }

    const QByteArray output = process->readAllStandardOutput();
    QString error;
    QString warning;
    QList<FakeMetaObject::ConstPtr> objectsList = parseHelper(output, &error, &warning);
    if (exitCode == 0) {
        if (!error.isEmpty()) {
            libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, tr("Type dump of C++ plugin failed. Parse error:\n'%1'").arg(error));
        } else {
            libraryInfo.setMetaObjects(objectsList);
            // ### disabled code path for running qmldump to get Qt's builtins
            //        if (libraryPath.isEmpty())
            //            Interpreter::CppQmlTypesLoader::builtinObjects.append(objectsList);
            libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpDone);
        }

        if (!warning.isEmpty())
            printParseWarnings(libraryPath, warning);
    }

    if (!libraryPath.isEmpty())
        m_modelManager->updateLibraryInfo(libraryPath, libraryInfo);
}
void PluginDumper::onLoadBuiltinTypes(const QmlJS::ModelManagerInterface::ProjectInfo &info, bool force)
{
    const QString baseImportsPath = info.qtQmlPath.isEmpty() ? info.qtImportsPath : info.qtQmlPath;
    if (info.qmlDumpPath.isEmpty() || baseImportsPath.isEmpty())
        return;

    const QString importsPath = QDir::cleanPath(baseImportsPath);
    if (m_runningQmldumps.values().contains(importsPath))
        return;

    LibraryInfo builtinInfo;
    if (!force) {
        const Snapshot snapshot = m_modelManager->snapshot();
        builtinInfo = snapshot.libraryInfo(baseImportsPath);
        if (builtinInfo.isValid())
            return;
    }
    builtinInfo = LibraryInfo(LibraryInfo::Found);
    m_modelManager->updateLibraryInfo(baseImportsPath, builtinInfo);

    // prefer QTDIR/qml/builtins.qmltypes if available
    const QString builtinQmltypesPath = baseImportsPath + QLatin1String("/builtins.qmltypes");
    if (QFile::exists(builtinQmltypesPath)) {
        loadQmltypesFile(QStringList(builtinQmltypesPath), baseImportsPath, builtinInfo);
        return;
    }
    // QTDIR/imports/QtQuick1/builtins.qmltypes was used in developer builds of 5.0.0, 5.0.1
    const QString builtinQmltypesPath2 = info.qtImportsPath
            + QLatin1String("/QtQuick1/builtins.qmltypes");
    if (QFile::exists(builtinQmltypesPath2)) {
        loadQmltypesFile(QStringList(builtinQmltypesPath2), baseImportsPath, builtinInfo);
        return;
    }

    runQmlDump(info, QStringList(QLatin1String("--builtins")), baseImportsPath);
    m_qtToInfo.insert(baseImportsPath, info);
}
/*!
    Should insert at line 4, column 1, with "protected\n" as prefix and "\n" suffix.
 */
void CppToolsPlugin::test_codegen_protected_between_public_and_private()
{
    const QByteArray src = "\n"
            "class Foo\n" // line 1
            "{\n"
            "public:\n"   // line 3
            "private:\n"  // line 4
            "};\n"        // line 5
            "\n";

    Document::Ptr doc = Document::create(QLatin1String("protected_betwee_public_and_private"));
    doc->setUtf8Source(src);
    doc->parse();
    doc->check();

    QCOMPARE(doc->diagnosticMessages().size(), 0);
    QCOMPARE(doc->globalSymbolCount(), 1U);

    Class *foo = doc->globalSymbolAt(0)->asClass();
    QVERIFY(foo);
    QCOMPARE(foo->line(), 1U);
    QCOMPARE(foo->column(), 7U);

    Snapshot snapshot;
    snapshot.insert(doc);
    CppRefactoringChanges changes(snapshot);
    InsertionPointLocator find(changes);
    InsertionLocation loc = find.methodDeclarationInClass(
                doc->fileName(),
                foo,
                InsertionPointLocator::Protected);
    QVERIFY(loc.isValid());
    QCOMPARE(loc.prefix(), QLatin1String("protected:\n"));
    QCOMPARE(loc.suffix(), QLatin1String("\n"));
    QCOMPARE(loc.column(), 1U);
    QCOMPARE(loc.line(), 4U);
}
Beispiel #23
0
bool ModelManager::loadSnapshot(const Snapshot& ss1, const Snapshot& ss2, double c1, double c2){
	Snapshot::const_iterator it1 = ss1.begin();
	Snapshot::const_iterator it2 = ss2.begin();
	
	while(ss1.end() != it1 && ss2.end() != it2){
		
		const std::string& id1 = it1->first;
		const std::string& id2 = it2->first;

		int cmp = id1.compare(id2);
		
		if(0 == cmp){		// ids match, attempt interpolation
			
			NamedModels::const_iterator itState = mState.find(id1);
			if(mState.end() != itState){	// found model with this id, lock and load!
				const Data& data1 = it1->second;
				const Data& data2 = it2->second;
				
				Data temp = data1;
				temp.clone();
				temp.mix(data1, data2, c1, c2);
				itState->second->setData(temp);
			}
			
			++it1;
			++it2;
		}
		else if(cmp < 0){	// first id less than second id
			++it1;			// let first iterator catch up with second
		}
		else{				// first id greater than second id
			++it2;			// let second iterator catch up with first
		}
	}
	return true;
}
Beispiel #24
0
Signature SignerReal::sign( PrivateKey privkey, const void* data, Size size, Monitor& monitor )
{
	if (!check_interface(monitor)) return Signature();
	if (!hasher)
	{
		// TODO: find default hasher for this sign algid
	}

	if (hasher)
	{
		Digest digest = hasher.hash(data,size,monitor);
		return sign(privkey,data,size,monitor);
	} else {
		eprovider::TheKey thekey = creator.getCreatureCurrentTheKey(privkey);

		eprovider::Block binsign;
		RECOVER_CALL( (iface->signStart(session, thekey, error)) );
		RECOVER_CALL( (iface->signProcess(session, data, size, error)) );
		RECOVER_CALL( (binsign = iface->signStop(session, error)) );

		Snapshot snapshot = creator.createSnapshot(binsign.get(), binsign.size(), binsign.encid(), iface->getKeyId(kcSignature));
		return snapshot.reviveSignature(monitor);
	}
}
Beispiel #25
0
Snapshot Image::snapshot()
{
	Data img = image();
	Snapshot res = creator->createSnapshot(img.get(), img.size(), getEncodingId());
	res.setEncodingExtType(getEncodingExtType());
	res.setEncodingZipType(getEncodingZipType());
	res.setEncodingByteOrder(getEncodingByteOrder());
	res.setProvider(getProvider());
	res.setKeyId(getKeyId());
	return res;
}
Beispiel #26
0
void TypeOfExpression::processEnvironment(Snapshot documents,
                                          Document::Ptr doc, Environment *env,
                                          QSet<QString> *processed) const
{
    if (! doc)
        return;
    if (processed->contains(doc->fileName()))
        return;
    processed->insert(doc->fileName());
    foreach (const Document::Include &incl, doc->includes()) {
        processEnvironment(documents,
                           documents.value(incl.fileName()),
                           env, processed);
    }
    foreach (const Macro &macro, doc->definedMacros())
        env->bind(macro);
}
void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
                                                const LookupItem &lookupItem,
                                                const LookupContext &context)
{
    Symbol *declaration = lookupItem.declaration();
    if (!declaration) {
        const QString &type = Overview().prettyType(lookupItem.type(), QString());
        m_element = QSharedPointer<CppElement>(new Unknown(type));
    } else {
        const FullySpecifiedType &type = declaration->type();
        if (declaration->isNamespace()) {
            m_element = QSharedPointer<CppElement>(new CppNamespace(declaration));
        } else if (declaration->isClass()
                   || declaration->isForwardClassDeclaration()
                   || (declaration->isTemplate() && declaration->asTemplate()->declaration()
                       && (declaration->asTemplate()->declaration()->isClass()
                           || declaration->asTemplate()->declaration()->isForwardClassDeclaration()))) {
            if (declaration->isForwardClassDeclaration())
                if (Symbol *classDeclaration = snapshot.findMatchingClassDeclaration(declaration))
                    declaration = classDeclaration;
            CppClass *cppClass = new CppClass(declaration);
            if (m_lookupBaseClasses)
                cppClass->lookupBases(declaration, context);
            if (m_lookupDerivedClasses)
                cppClass->lookupDerived(declaration, snapshot);
            m_element = QSharedPointer<CppElement>(cppClass);
        } else if (Enum *enumDecl = declaration->asEnum()) {
            m_element = QSharedPointer<CppElement>(new CppEnum(enumDecl));
        } else if (EnumeratorDeclaration *enumerator = dynamic_cast<EnumeratorDeclaration *>(declaration)) {
            m_element = QSharedPointer<CppElement>(new CppEnumerator(enumerator));
        } else if (declaration->isTypedef()) {
            m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
        } else if (declaration->isFunction()
                   || (type.isValid() && type->isFunctionType())
                   || declaration->isTemplate()) {
            m_element = QSharedPointer<CppElement>(new CppFunction(declaration));
        } else if (declaration->isDeclaration() && type.isValid()) {
            m_element = QSharedPointer<CppElement>(
                new CppVariable(declaration, context, lookupItem.scope()));
        } else {
            m_element = QSharedPointer<CppElement>(new CppDeclarableElement(declaration));
        }
    }
}
Beispiel #28
0
void tst_Lookup::iface_impl_scoping()
{
    const QByteArray source = "\n"
                              "@interface Scooping{}-(int)method1:(int)arg;-(void)method2;@end\n"
                              "@implementation Scooping-(int)method1:(int)arg{return arg;}@end\n";

    Document::Ptr doc = Document::create("class_with_protocol_with_protocol");
    doc->setUtf8Source(source);
    doc->parse();
    doc->check();

    QVERIFY(doc->diagnosticMessages().isEmpty());
    QCOMPARE(doc->globalSymbolCount(), 2U);

    Snapshot snapshot;
    snapshot.insert(doc);

    ObjCClass *iface = doc->globalSymbolAt(0)->asObjCClass();
    QVERIFY(iface);
    QVERIFY(iface->isInterface());
    ObjCClass *impl = doc->globalSymbolAt(1)->asObjCClass();
    QVERIFY(impl);
    QVERIFY(!impl->isInterface());

    QCOMPARE(iface->memberCount(), 2U);
    QCOMPARE(impl->memberCount(), 1U);

    ObjCMethod *method1Impl = impl->memberAt(0)->asObjCMethod();
    QVERIFY(method1Impl);
    QCOMPARE(method1Impl->identifier()->chars(), "method1");

    // get the body of method1
    QCOMPARE(method1Impl->memberCount(), 2U);
    Argument *method1Arg = method1Impl->memberAt(0)->asArgument();
    QVERIFY(method1Arg);
    QCOMPARE(method1Arg->identifier()->chars(), "arg");
    QVERIFY(method1Arg->type()->isIntegerType());

    Block *method1Body = method1Impl->memberAt(1)->asBlock();
    QVERIFY(method1Body);

    const LookupContext context(doc, snapshot);

    { // verify if we can resolve "arg" in the body
        QCOMPARE(method1Impl->argumentCount(), 1U);
        Argument *arg = method1Impl->argumentAt(0)->asArgument();
        QVERIFY(arg);
        QVERIFY(arg->name());
        QVERIFY(arg->name()->identifier());
        QCOMPARE(arg->name()->identifier()->chars(), "arg");
        QVERIFY(arg->type()->isIntegerType());

        const QList<LookupItem> candidates = context.lookup(arg->name(), method1Body->enclosingScope());
        QCOMPARE(candidates.size(), 1);
        QVERIFY(candidates.at(0).declaration()->type()->asIntegerType());
    }

    Declaration *method2 = iface->memberAt(1)->asDeclaration();
    QVERIFY(method2);
    QCOMPARE(method2->identifier()->chars(), "method2");

    { // verify if we can resolve "method2" in the body
        const QList<LookupItem> candidates = context.lookup(method2->name(), method1Body->enclosingScope());
        QCOMPARE(candidates.size(), 1);
        QCOMPARE(candidates.at(0).declaration(), method2);
    }
}
Beispiel #29
0
void tst_Lookup::simple_class_1()
{
    const QByteArray source = "\n"
        "@interface Zoo {} +(id)alloc; -(id)init; @end\n"
        "@implementation Zoo +(id)alloc{} -(id)init{} -(void)dealloc{} @end\n";

    Document::Ptr doc = Document::create("simple_class_1");
    doc->setUtf8Source(source);
    doc->parse();
    doc->check();

    QVERIFY(doc->diagnosticMessages().isEmpty());
    QCOMPARE(doc->globalSymbolCount(), 2U);

    Snapshot snapshot;
    snapshot.insert(doc);

    ObjCClass *iface = doc->globalSymbolAt(0)->asObjCClass();
    QVERIFY(iface);
    QVERIFY(iface->isInterface());
    QCOMPARE(iface->memberCount(), 2U);

    ObjCClass *impl = doc->globalSymbolAt(1)->asObjCClass();
    QVERIFY(impl);
    QVERIFY(!impl->isInterface());
    QCOMPARE(impl->memberCount(), 3U);

    Declaration *allocMethodIface = iface->memberAt(0)->asDeclaration();
    QVERIFY(allocMethodIface);
    QVERIFY(allocMethodIface->name() && allocMethodIface->name()->identifier());
    QCOMPARE(QLatin1String(allocMethodIface->name()->identifier()->chars()), QLatin1String("alloc"));

    ObjCMethod *allocMethodImpl = impl->memberAt(0)->asObjCMethod();
    QVERIFY(allocMethodImpl);
    QVERIFY(allocMethodImpl->name() && allocMethodImpl->name()->identifier());
    QCOMPARE(QLatin1String(allocMethodImpl->name()->identifier()->chars()), QLatin1String("alloc"));

    ObjCMethod *deallocMethod = impl->memberAt(2)->asObjCMethod();
    QVERIFY(deallocMethod);
    QVERIFY(deallocMethod->name() && deallocMethod->name()->identifier());
    QCOMPARE(QLatin1String(deallocMethod->name()->identifier()->chars()), QLatin1String("dealloc"));

    const LookupContext context(doc, snapshot);

    // check class resolving:
    LookupScope *klass = context.lookupType(impl->name(), impl->enclosingScope());
    QVERIFY(klass != 0);
    QCOMPARE(klass->symbols().size(), 2);
    QVERIFY(klass->symbols().contains(iface));
    QVERIFY(klass->symbols().contains(impl));

    // check method resolving:
    QList<LookupItem> results = context.lookup(allocMethodImpl->name(), impl);
    QCOMPARE(results.size(), 2);
    QCOMPARE(results.at(0).declaration(), allocMethodIface);
    QCOMPARE(results.at(1).declaration(), allocMethodImpl);

    results = context.lookup(deallocMethod->name(), impl);
    QCOMPARE(results.size(), 1);
    QCOMPARE(results.at(0).declaration(), deallocMethod);
}
void CppToolsPlugin::test_codegen_definition_member_specific_file()
{
    const QByteArray srcText = "\n"
            "class Foo\n"  // line 1
            "{\n"
            "void foo();\n" // line 3
            "void bar();\n" // line 4
            "void baz();\n" // line 5
            "};\n"
            "\n"
            "void Foo::bar()\n"
            "{\n"
            "\n"
            "}\n";

    const QByteArray dstText = QString::fromLatin1(
                "\n"
                "#include \"%1/file.h\"\n" // line 1
                "int x;\n"
                "\n"
                "void Foo::foo()\n" // line 4
                "{\n"
                "\n"
                "}\n" // line 7
                "\n"
                "int y;\n").arg(QDir::tempPath()).toLatin1();

    Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
    Utils::FileSaver srcSaver(src->fileName());
    srcSaver.write(srcText);
    srcSaver.finalize();
    src->setUtf8Source(srcText);
    src->parse();
    src->check();
    QCOMPARE(src->diagnosticMessages().size(), 0);
    QCOMPARE(src->globalSymbolCount(), 2U);

    Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
    dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
                                          Client::IncludeLocal));
    Utils::FileSaver dstSaver(dst->fileName());
    dstSaver.write(dstText);
    dstSaver.finalize();
    dst->setUtf8Source(dstText);
    dst->parse();
    dst->check();
    QCOMPARE(dst->diagnosticMessages().size(), 0);
    QCOMPARE(dst->globalSymbolCount(), 3U);

    Snapshot snapshot;
    snapshot.insert(src);
    snapshot.insert(dst);

    Class *foo = src->globalSymbolAt(0)->asClass();
    QVERIFY(foo);
    QCOMPARE(foo->line(), 1U);
    QCOMPARE(foo->column(), 7U);
    QCOMPARE(foo->memberCount(), 3U);
    Declaration *decl = foo->memberAt(2)->asDeclaration();
    QVERIFY(decl);
    QCOMPARE(decl->line(), 5U);
    QCOMPARE(decl->column(), 6U);

    CppRefactoringChanges changes(snapshot);
    InsertionPointLocator find(changes);
    QList<InsertionLocation> locList = find.methodDefinition(decl, true, dst->fileName());
    QVERIFY(locList.size() == 1);
    InsertionLocation loc = locList.first();
    QCOMPARE(loc.fileName(), dst->fileName());
    QCOMPARE(loc.line(), 7U);
    QCOMPARE(loc.column(), 2U);
    QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
    QCOMPARE(loc.suffix(), QString());
}