Ejemplo n.º 1
0
/* 
   testGetInstance of the OS provider. 
*/
void OSTestClient::testGetInstance (CIMClient &client,
                                    Boolean verboseTest)
{
  CIMObjectPath  getTestRef;    //  will need an instance for Get
  
  try
    {
      Boolean deepInheritance = true;
      Boolean localOnly = true;
   
      testLog("OS Provider Test GetInstance");
     
      // first do an EnumerateInstanceNames - select one to play with 
      // doesn't hurt to keep testing enumerate :-)
 
      Array<CIMObjectPath> cimReferences = 
	    client.enumerateInstanceNames(NAMESPACE, CLASSNAME);
 
      Uint32 numberInstances = cimReferences.size();
      if (verboseTest)
	cout << numberInstances << " instances of PG_OperatingSystem" <<endl;

      for (Uint32 i = 0; i < cimReferences.size(); i++)
      {
         CIMName className = cimReferences[i].getClassName();
         if (!className.equal (CLASSNAME))
         {
	    errorExit("EnumInstanceNames failed - wrong class");
	 }
         // add in some content checks on the keys returned

         _validateKeys(cimReferences[i], verboseTest);

         // let's just take the first instance found
         getTestRef = cimReferences[i];

    }   // end for looping through instances
    
    if (verboseTest)
       cout<<"EnumerateInstanceNames for Get Instance completed"<<endl; 
   
    // now call GetInstance with the appropriate references
    CIMInstance getTestInstance = client.getInstance(NAMESPACE,
                                                     getTestRef);

    // now validate the properties returned
    _validateProperties(getTestInstance, verboseTest);

    testLog("OS Provider Test Get Instance passed ");
    }  // end try 
   
    catch(Exception& e)
    {
      errorExit(e.getMessage());
    }
}
Ejemplo n.º 2
0
int main()
{
    // Create a sink for output
    std::shared_ptr<smlog::Sink> sink =
            std::make_shared<SinkToStdOut>();

    // Create the log
    smlog::Logger log;
    log.AddSink(sink);

    // Add some prefix tokens for each log message
    std::unique_ptr<smlog::FBCustomStr> fb0(
            new smlog::FBCustomStr("TRACE: LIBNAME: " ));

    std::unique_ptr<smlog::FBCustomStr> fb1(
            new smlog::FBCustomStr("DEBUG: LIBNAME: " ));

    std::unique_ptr<smlog::FBCustomStr> fb2(
            new smlog::FBCustomStr("INFO:  LIBNAME: " ));

    std::unique_ptr<smlog::FBCustomStr> fb3(
            new smlog::FBCustomStr("WARN:  LIBNAME: " ));

    std::unique_ptr<smlog::FBCustomStr> fb4(
            new smlog::FBCustomStr("ERROR: LIBNAME: " ));

    std::unique_ptr<smlog::FBCustomStr> fb5(
            new smlog::FBCustomStr("FATAL: LIBNAME: " ));

    log.AddFormatBlock(std::move(fb0),smlog::Logger::Level::TRACE);
    log.AddFormatBlock(std::move(fb1),smlog::Logger::Level::DEBUG);
    log.AddFormatBlock(std::move(fb2),smlog::Logger::Level::INFO);
    log.AddFormatBlock(std::move(fb3),smlog::Logger::Level::WARN);
    log.AddFormatBlock(std::move(fb4),smlog::Logger::Level::ERROR);
    log.AddFormatBlock(std::move(fb5),smlog::Logger::Level::FATAL);

    testLog(log);

    // Test setting / unsetting log levels. All levels
    // are initially enabled by default
    log.UnsetLevel(smlog::Logger::Level::TRACE);
    log.UnsetLevel(smlog::Logger::Level::DEBUG);
    log.UnsetLevel(smlog::Logger::Level::WARN);

    std::cout << std::endl;
    testLog(log);

    log.SetLevel(smlog::Logger::Level::DEBUG);
    std::cout << std::endl;
    testLog(log);

    return 0;
}
Ejemplo n.º 3
0
/*
   testEnumerateInstances of the NIS provider.
*/
void NISTestClient::testEnumerateInstances(
    CIMClient &client,
    Boolean verboseTest)
{
    try
    {
        Boolean deepInheritance = true;
        Boolean localOnly = true;
        Boolean includeQualifiers = false;
        Boolean includeClassOrigin = false;
        Uint32 numberInstances;

        testLog("NIS Provider Test EnumerateInstances");

        Array<CIMInstance> cimNInstances = client.enumerateInstances(
            NAMESPACE,
            CLASS_NAME,
            deepInheritance,
            localOnly,
            includeQualifiers,
            includeClassOrigin);

        numberInstances = cimNInstances.size();
        if (verboseTest)
            cout << numberInstances << " instances of PG_NISServerService" <<
                endl;

        for (Uint32 i = 0; i < cimNInstances.size(); i++)
        {
            CIMObjectPath instanceRef = cimNInstances[i].getPath ();
            if (verboseTest)
                cout << "Instance ClassName is " <<
                    instanceRef.getClassName().getString() << endl;
            if(!instanceRef.getClassName().equal(CLASS_NAME))
            {
                errorExit("EnumInstances failed");
            }

            // now validate the properties
            _validateProperties(cimNInstances[i], verboseTest);
        }       // end for looping through instances

        testLog("NIS Provider Test EnumInstances Passed");
    }
    catch(Exception& e)
    {
        errorExit(e.getMessage());
    }
}
Ejemplo n.º 4
0
bool IndexerJob::visit(int build)
{
    if (!mUnits.at(build).second) {
        abort();
        return false;
    }
    clang_getInclusions(mUnits.at(build).second, IndexerJob::inclusionVisitor, this);
    if (isAborted())
        return false;

    clang_visitChildren(clang_getTranslationUnitCursor(mUnits.at(build).second),
                        IndexerJob::indexVisitor, this);
    if (isAborted())
        return false;
    if (testLog(VerboseDebug)) {
        VerboseVisitorUserData u = { 0, "<VerboseVisitor " + mClangLines.at(build) + ">\n", this };
        clang_visitChildren(clang_getTranslationUnitCursor(mUnits.at(build).second),
                            IndexerJob::verboseVisitor, &u);
        u.out += "</VerboseVisitor " + mClangLines.at(build) + ">";
        if (getenv("RTAGS_INDEXERJOB_DUMP_TO_FILE")) {
            char buf[1024];
            snprintf(buf, sizeof(buf), "/tmp/%s.log", mSourceInformation.sourceFile.fileName());
            FILE *f = fopen(buf, "w");
            assert(f);
            fwrite(u.out.constData(), 1, u.out.size(), f);
            fclose(f);
        } else {
            logDirect(VerboseDebug, u.out);
        }
    }
    return !isAborted();
}
Ejemplo n.º 5
0
/*
   testEnumerateInstanceNames of the NIS provider.
*/
void NISTestClient::testEnumerateInstanceNames(
    CIMClient &client,
    Boolean verboseTest)
{
    try
    {
        Uint32  numberInstances;

        testLog("NIS Provider Test Start EnumerateInstanceNames");

        Array<CIMObjectPath> cimReferences =
            client.enumerateInstanceNames(NAMESPACE, CLASS_NAME);

        numberInstances = cimReferences.size();
        if (verboseTest)
            cout << numberInstances << " instances of " <<
                CLASS_NAME.getString() <<endl;

        for (Uint32 i = 0; i < cimReferences.size(); i++)
        {
            CIMName className = cimReferences[i].getClassName();
            if (!className.equal(CLASS_NAME))
            {
                errorExit("EnumInstanceNames failed - wrong class");
            }

            _validateKeys(cimReferences[i], verboseTest);

        }   // end for looping through instances

        testLog("NIS Provider Test EnumInstanceNames Passed");
    }
    catch(Exception& e)
    {
        errorExit(e.getMessage());
    }
}
Ejemplo n.º 6
0
int main( int argc, char ** argv )
{
	if ( argc == 2 )
		dataPath = argv[1];

	std::cout << "System uses " << ( IS_BIG_ENDIAN ? " B I G " : "little" );
	std::cout << " endian byte order." << std::endl;

	// Test-load each binary config file.
	testGps( dataPath );
	testLog( dataPath );
	testSys( dataPath );

	return 0;
}
static inline void eatAutoTools(List<ByteArray> &args)
{
    List<ByteArray> copy = args;
    for (int i=0; i<args.size(); ++i) {
        if (args.at(i).contains("gcc") || args.at(i).contains("g++") || args.at(i) == "cd" || args.at(i) == "c++") {
            if (i) {
                args.erase(args.begin(), args.begin() + i);
                if (testLog(Debug)) {
                    debug() << "ate something " << copy;
                    debug() << "now we have " << args;
                }
            }
            break;
        }
    }
}
Ejemplo n.º 8
0
void Project::onJobFinished(const shared_ptr<IndexerJob> &job)
{
    PendingJob pending;
    bool startPending = false;
    {
        MutexLocker lock(&mMutex);

        const uint32_t fileId = job->fileId();
        if (job->isAborted()) {
            mVisitedFiles -= job->visitedFiles();
            --mJobCounter;
            pending = mPendingJobs.take(fileId, &startPending);
            if (mJobs.value(fileId) == job)
                mJobs.remove(fileId);
        } else {
            assert(mJobs.value(fileId) == job);
            mJobs.remove(fileId);

            shared_ptr<IndexData> data = job->data();
            mPendingData[fileId] = data;

            const int idx = mJobCounter - mJobs.size();

            mSources[fileId].parsed = job->parseTime();
            if (testLog(RTags::CompilationErrorXml))
                log(RTags::CompilationErrorXml, "<?xml version=\"1.0\" encoding=\"utf-8\"?><progress index=\"%d\" total=\"%d\"></progress>",
                    idx, mJobCounter);

            error("[%3d%%] %d/%d %s %s.",
                  static_cast<int>(round((double(idx) / double(mJobCounter)) * 100.0)), idx, mJobCounter,
                  String::formatTime(time(0), String::Time).constData(),
                  data->message.constData());

            if (mJobs.isEmpty()) {
                mSyncTimer.start(shared_from_this(), job->type() == IndexerJob::Dirty ? 0 : SyncTimeout,
                                 SingleShot, Sync);
            }
        }
    }
    if (startPending)
        index(pending.source, pending.type);
}
Ejemplo n.º 9
0
int main(int argc, char * argv[])
{
//	getopt_main(argc, argv);
//	test_ChangeTHEX2CPTR();
//	test_string_convert();
//	testRandMN();
//	testSetBitVecC();
//	testGetString();
 	testLog();
// 	testBinSearch();
// 	testRandNumber();
// 	testShift();
//	testSetArray();
// 	testSetList();
// 	testSetBST();
// 	testSetBitVec();
//	WordSort1();
//	testWordSort2();
//	testTime();
	return 0;
}
void CompletionJob::processDiagnostics(CXCodeCompleteResults* results)
{
    if (!testLog(CompilationError))
        return;

    const unsigned int numDiags = clang_codeCompleteGetNumDiagnostics(results);
    for (unsigned int curDiag = 0; curDiag < numDiags; ++curDiag) {
        CXDiagnostic diagnostic = clang_codeCompleteGetDiagnostic(results, curDiag);
        const unsigned diagnosticOptions = (CXDiagnostic_DisplaySourceLocation|
                                            CXDiagnostic_DisplayColumn|
                                            CXDiagnostic_DisplaySourceRanges|
                                            CXDiagnostic_DisplayOption|
                                            CXDiagnostic_DisplayCategoryId|
                                            CXDiagnostic_DisplayCategoryName);
        const ByteArray text = RTags::eatString(clang_formatDiagnostic(diagnostic, diagnosticOptions));
        log(CompilationError, "%s", text.constData());

        clang_disposeDiagnostic(diagnostic);
    }
    log(CompilationError, "$");
}
Ejemplo n.º 11
0
Archivo: Log.cpp Proyecto: jmataraz/rct
static void log(int level, const char *format, va_list v)
{
    if (!testLog(level))
        return;

    va_list v2;
    va_copy(v2, v);
    enum { Size = 16384 };
    char buf[Size];
    char *msg = buf;
    int n = vsnprintf(msg, Size, format, v);
    if (n == -1) {
        va_end(v2);
        return;
    }

    if (n >= Size) {
        msg = new char[n + 2];
        n = vsnprintf(msg, n + 1, format, v2);
    }

    std::lock_guard<std::mutex> lock(sOutputsMutex);
    if (sOutputs.isEmpty()) {
        printf("%s\n", msg);
    } else {
        for (Set<LogOutput*>::const_iterator it = sOutputs.begin(); it != sOutputs.end(); ++it) {
            LogOutput *output = *it;
            if (output->testLog(level)) {
                output->log(msg, n);
            }
        }
    }

    if (msg != buf)
        delete []msg;
    va_end(v2);
}
Ejemplo n.º 12
0
Archivo: Log.cpp Proyecto: emdeesee/rct
static void log(LogLevel level, const char *format, va_list v)
{
    if (!testLog(level))
        return;

    va_list v2;
    va_copy(v2, v);
    enum { Size = 16384 };

    StackBuffer<Size> buf(Size);
    int n = vsnprintf(buf, Size, format, v);
    if (n == -1) {
        va_end(v2);
        return;
    }

    if (n >= Size) {
        buf.resize(n + 2);
        n = vsnprintf(buf, n + 1, format, v2);
    }

    logDirect(level, buf, n);
    va_end(v2);
}
Ejemplo n.º 13
0
bool ClangIndexer::visit()
{
    if (!mClangUnit || !mSource.fileId) {
        return false;
    }

    StopWatch watch;

    clang_visitChildren(clang_getTranslationUnitCursor(mClangUnit),
                        ClangIndexer::indexVisitor, this);

    for (Hash<uint32_t, bool>::const_iterator it = mData->visited.begin(); it != mData->visited.end(); ++it) {
        mData->dependencies[it->first].insert(mSource.fileId);
        addFileSymbol(it->first);
    }

    mVisitDuration = watch.elapsed();

    if (testLog(VerboseDebug)) {
        VerboseVisitorUserData u = { 0, "<VerboseVisitor " + mClangLine + ">\n", this };
        clang_visitChildren(clang_getTranslationUnitCursor(mClangUnit),
                            ClangIndexer::verboseVisitor, &u);
        u.out += "</VerboseVisitor " + mClangLine + ">";
        if (getenv("RTAGS_INDEXERJOB_DUMP_TO_FILE")) {
            char buf[1024];
            snprintf(buf, sizeof(buf), "/tmp/%s.log", Location::path(mSource.fileId).fileName());
            FILE *f = fopen(buf, "w");
            assert(f);
            fwrite(u.out.constData(), 1, u.out.size(), f);
            fclose(f);
        } else {
            logDirect(VerboseDebug, u.out);
        }
    }
    return true;
}
Ejemplo n.º 14
0
void CompletionThread::process(Request *request)
{
    // if (!request->unsaved.isEmpty()) {
    //     int line = request->location.line();
    //     int pos = 0;
    //     while (line > 1) {
    //         int p = request->unsaved.indexOf('\n', pos);
    //         if (p == -1) {
    //             pos = -1;
    //             break;
    //         }
    //         pos = p + 1;
    //         --line;
    //     }
    //     if (pos != -1) {
    //         int end = request->unsaved.indexOf('\n', pos);
    //         if (end == -1)
    //             end = request->unsaved.size();
    //         error("Completing at %s:%d:%d line: [%s]\n",
    //               request->location.path().constData(),
    //               request->location.line(),
    //               request->location.column(),
    //               request->unsaved.mid(pos, end - pos).constData());
    //     }
    // }

    StopWatch sw;
    int parseTime = 0;
    int reparseTime = 0;
    int completeTime = 0;
    int processTime = 0;
    SourceFile *&cache = mCacheMap[request->source.fileId];
    if (cache && cache->source != request->source) {
        delete cache;
        cache = 0;
    }
    if (!cache) {
        cache = new SourceFile;
        mCacheList.append(cache);
        while (mCacheMap.size() > mCacheSize) {
            SourceFile *c = mCacheList.removeFirst();
            mCacheMap.remove(c->source.fileId);
            delete c;
        }
    } else {
        mCacheList.moveToEnd(cache);
    }
    const bool sendDebug = testLog(LogLevel::Debug);

    if (cache->translationUnit && cache->source != request->source) {
        clang_disposeTranslationUnit(cache->translationUnit);
        cache->translationUnit = 0;
        cache->source = request->source;
    } else if (!cache->translationUnit) {
        cache->source = request->source;
    }

    const Path sourceFile = request->source.sourceFile();
    CXUnsavedFile unsaved = {
        sourceFile.constData(),
        request->unsaved.constData(),
        static_cast<unsigned long>(request->unsaved.size())
    };

    size_t hash = 0;
    uint64_t lastModified = 0;
    if (request->unsaved.size()) {
        std::hash<String> h;
        hash = h(request->unsaved);
    } else {
        lastModified = sourceFile.lastModifiedMs();
    }

    const auto &options = Server::instance()->options();
    if (!cache->translationUnit) {
        cache->completionsMap.clear();
        cache->completionsList.deleteAll();
        sw.restart();
        Flags<CXTranslationUnit_Flags> flags = static_cast<CXTranslationUnit_Flags>(clang_defaultEditingTranslationUnitOptions());
        flags |= CXTranslationUnit_PrecompiledPreamble;
        flags |= CXTranslationUnit_CacheCompletionResults;
        flags |= CXTranslationUnit_SkipFunctionBodies;

        for (const auto &inc : options.includePaths) {
            request->source.includePaths << inc;
        }
        request->source.defines << options.defines;

        String clangLine;
        RTags::parseTranslationUnit(sourceFile, request->source.toCommandLine(Source::Default|Source::ExcludeDefaultArguments),
                                    cache->translationUnit, mIndex,
                                    &unsaved, request->unsaved.size() ? 1 : 0, flags, &clangLine);
        // error() << "PARSING" << clangLine;
        parseTime = sw.restart();
        if (cache->translationUnit) {
            RTags::reparseTranslationUnit(cache->translationUnit, &unsaved, request->unsaved.size() ? 1 : 0);
        }
        reparseTime = sw.elapsed();
        if (!cache->translationUnit)
            return;
        cache->unsavedHash = hash;
        cache->lastModified = lastModified;
    } else if (cache->unsavedHash != hash || cache->lastModified != lastModified) {
        cache->completionsMap.clear();
        cache->completionsList.deleteAll();
        cache->unsavedHash = hash;
        cache->lastModified = lastModified;
    } else if (!(request->flags & Refresh)) {
        const auto it = cache->completionsMap.find(request->location);
        if (it != cache->completionsMap.end()) {
            cache->completionsList.moveToEnd(it->second);
            error("Found completions (%d) in cache %s:%d:%d",
                  it->second->candidates.size(), sourceFile.constData(),
                  request->location.line(), request->location.column());
            printCompletions(it->second->candidates, request);
            return;
        }
    }

    sw.restart();
    const unsigned int completionFlags = (CXCodeComplete_IncludeMacros|CXCodeComplete_IncludeCodePatterns);

    CXCodeCompleteResults *results = clang_codeCompleteAt(cache->translationUnit, sourceFile.constData(),
                                                          request->location.line(), request->location.column(),
                                                          &unsaved, unsaved.Length ? 1 : 0, completionFlags);
    completeTime = sw.restart();
    if (results) {
        std::vector<Completions::Candidate> nodes;
        nodes.reserve(results->NumResults);

        int nodeCount = 0;
        Map<Token, int> tokens;
        if (!request->unsaved.isEmpty()) {
            tokens = Token::tokenize(request->unsaved.constData(), request->unsaved.size());
            // for (Map<Token, int>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) {
            //     error() << String(it->first.data, it->first.length) << it->second;
            // }
        }
        for (unsigned int i = 0; i < results->NumResults; ++i) {
            const CXCursorKind kind = results->Results[i].CursorKind;
            if (!(options.options & Server::CompletionsNoFilter) && kind == CXCursor_Destructor)
                continue;

            const CXCompletionString &string = results->Results[i].CompletionString;

            const CXAvailabilityKind availabilityKind = clang_getCompletionAvailability(string);
            if (!(options.options & Server::CompletionsNoFilter) && availabilityKind != CXAvailability_Available)
                continue;

            const int priority = clang_getCompletionPriority(string);

            if (size_t(nodeCount) == nodes.size())
                nodes.emplace_back();

            Completions::Candidate &node = nodes.back();
            node.cursorKind = kind;
            node.priority = priority;
            node.signature.reserve(256);
            const int chunkCount = clang_getNumCompletionChunks(string);
            bool ok = true;
            for (int j=0; j<chunkCount; ++j) {
                const CXCompletionChunkKind chunkKind = clang_getCompletionChunkKind(string, j);
                if (chunkKind == CXCompletionChunk_TypedText) {
                    node.completion = RTags::eatString(clang_getCompletionChunkText(string, j));
                    if (node.completion.size() > 8 && node.completion.startsWith("operator") && !isPartOfSymbol(node.completion.at(8))) {
                        ok = false;
                        break;
                    }
                    node.signature.append(node.completion);
                } else {
                    node.signature.append(RTags::eatString(clang_getCompletionChunkText(string, j)));
                    if (chunkKind == CXCompletionChunk_ResultType)
                        node.signature.append(' ');
                }
            }
            if (ok) {
                int ws = node.completion.size() - 1;
                while (ws >= 0 && isspace(node.completion.at(ws)))
                    --ws;
                if (ws >= 0) {
                    node.completion.truncate(ws + 1);
                    node.signature.replace("\n", "");
                    node.distance = tokens.value(Token(node.completion.constData(), node.completion.size()), -1);
                    if (sendDebug)
                        debug() << node.signature << node.priority << kind
                                << node.distance << clang_getCompletionAvailability(string);

                    ++nodeCount;
                    continue;
                }
            }
            node.completion.clear();
            node.signature.clear();
        }
        if (nodeCount) {
            // Sort pointers instead of shuffling candidates around
            std::vector<Completions::Candidate*> nodesPtr;
            nodesPtr.reserve(nodeCount);
            for (auto& n : nodes) nodesPtr.push_back(&n);

            std::sort(nodesPtr.begin(), nodesPtr.end(), compareCompletionCandidates);

            Completions *&c = cache->completionsMap[request->location];
            if (c) {
                cache->completionsList.moveToEnd(c);
            } else {
                enum { MaxCompletionCache = 10 }; // ### configurable?
                c = new Completions(request->location);
                cache->completionsList.append(c);
                while (cache->completionsMap.size() > MaxCompletionCache) {
                    Completions *cc = cache->completionsList.takeFirst();
                    cache->completionsMap.remove(cc->location);
                    delete cc;
                }
            }
            c->candidates.resize(nodeCount);
            for (int i=0; i<nodeCount; ++i)
                c->candidates[i] = std::move(*nodesPtr[i]);
            printCompletions(c->candidates, request);
            processTime = sw.elapsed();
            warning("Processed %s, parse %d/%d, complete %d, process %d => %d completions (unsaved %d)",
                    sourceFile.constData(), parseTime, reparseTime, completeTime, processTime, nodeCount, request->unsaved.size());
        } else {
            printCompletions(List<Completions::Candidate>(), request);
            error() << "No completion results available" << request->location << results->NumResults;
        }
        clang_disposeCodeCompleteResults(results);
    }
}
Ejemplo n.º 15
0
int main() {

    return testLog() ;
}
Ejemplo n.º 16
0
bool IndexerJob::diagnose(int build, int *errorCount)
{
    if (errorCount)
        *errorCount = 0;
    if (!mUnits.at(build).second) {
        abort();
        return false;
    }

    List<String> compilationErrors;
    const unsigned diagnosticCount = clang_getNumDiagnostics(mUnits.at(build).second);
    const unsigned options = Server::instance()->options().options;

    for (unsigned i=0; i<diagnosticCount; ++i) {
        CXDiagnostic diagnostic = clang_getDiagnostic(mUnits.at(build).second, i);
        int logLevel = INT_MAX;
        const CXDiagnosticSeverity severity = clang_getDiagnosticSeverity(diagnostic);
        switch (severity) {
        case CXDiagnostic_Fatal:
        case CXDiagnostic_Error:
            if (errorCount)
                ++*errorCount;
            logLevel = Error;
            break;
        case CXDiagnostic_Warning:
            logLevel = Warning;
            break;
        case CXDiagnostic_Note:
            logLevel = Debug;
            break;
        case CXDiagnostic_Ignored:
            break;
        }

        const unsigned diagnosticOptions = (CXDiagnostic_DisplaySourceLocation|
                                            CXDiagnostic_DisplayColumn|
                                            CXDiagnostic_DisplaySourceRanges|
                                            CXDiagnostic_DisplayOption|
                                            CXDiagnostic_DisplayCategoryId|
                                            CXDiagnostic_DisplayCategoryName);
        const uint32_t fileId = createLocation(clang_getDiagnosticLocation(diagnostic), 0).fileId();
        if (mVisitedFiles.contains(fileId)) {
            const String text = RTags::eatString(clang_formatDiagnostic(diagnostic, diagnosticOptions));
            if (testLog(logLevel) || testLog(CompilationError)) {
                log(logLevel, "%s: %s => %s", mSourceInformation.sourceFile.constData(), mClangLines.at(build).constData(), text.constData());
                compilationErrors.append(text);
            }

            const unsigned fixItCount = clang_getDiagnosticNumFixIts(diagnostic);
            RegExp rx;
            if (options & Server::IgnorePrintfFixits) {
                rx = "^%[A-Za-z0-9]\\+$";
            }
            for (unsigned f=0; f<fixItCount; ++f) {
                CXSourceRange range;
                const String string = RTags::eatString(clang_getDiagnosticFixIt(diagnostic, f, &range));
                unsigned startOffset;
                CXFile file;
                clang_getSpellingLocation(clang_getRangeStart(range), &file, 0, 0, &startOffset);
                unsigned endOffset;
                clang_getSpellingLocation(clang_getRangeEnd(range), 0, 0, 0, &endOffset);
                const Location loc(file, startOffset);
                if (options & Server::IgnorePrintfFixits && rx.indexIn(string) == 0) {
                    error("Ignored fixit for %s: Replace %d-%d with [%s]", loc.path().constData(),
                          startOffset, endOffset, string.constData());
                } else {
                    error("Fixit for %s: Replace %d-%d with [%s]", loc.path().constData(),
                          startOffset, endOffset, string.constData());
                    compilationErrors.append(String::format<128>("Fixit for %s: Replace %d-%d with [%s]", loc.path().constData(),
                                                                 startOffset, endOffset, string.constData()));
                    mData->fixIts[loc.fileId()].insert(FixIt(startOffset, endOffset, string));
                }
            }
        }

        clang_disposeDiagnostic(diagnostic);
    }
    if (testLog(CompilationError))
        sendDiagnostics(compilationErrors);
    return !isAborted();
}
Ejemplo n.º 17
0
CXChildVisitResult IndexerJob::indexVisitor(CXCursor cursor, CXCursor parent, CXClientData data)
{
    IndexerJob *job = static_cast<IndexerJob*>(data);
    {
        MutexLocker lock(&job->mMutex);
        if (job->mAborted)
            return CXChildVisit_Break;
    }

    const LastCursorUpdater updater(job->mLastCursor, cursor);

    const CXCursorKind kind = clang_getCursorKind(cursor);
    const RTags::CursorType type = RTags::cursorType(kind);
    if (type == RTags::Other)
        return CXChildVisit_Recurse;

    bool blocked = false;
    Location loc = job->createLocation(cursor, &blocked);
    if (blocked) {
        return CXChildVisit_Continue;
    } else if (loc.isNull()) {
        return CXChildVisit_Recurse;
    }

    if (testLog(VerboseDebug)) {
        Log log(VerboseDebug);
        log << cursor;
        CXCursor ref = clang_getCursorReferenced(cursor);
        if (!clang_isInvalid(clang_getCursorKind(ref)) && !clang_equalCursors(ref, cursor)) {
            log << "refs" << ref;
        }
    }
    switch (type) {
    case RTags::Cursor:
        job->handleCursor(cursor, kind, loc);
        break;
    case RTags::Include:
        job->handleInclude(cursor, kind, loc);
        break;
    case RTags::Reference:
        switch (kind) {
        case CXCursor_OverloadedDeclRef: {
            const int count = clang_getNumOverloadedDecls(cursor);
            for (int i=0; i<count; ++i) {
                const CXCursor ref = clang_getOverloadedDecl(cursor, i);
                job->handleReference(cursor, kind, loc, ref, parent);
            }
            break; }
        case CXCursor_CXXDeleteExpr:
            job->handleReference(cursor, kind, loc, findDestructorForDelete(cursor), parent);
            break;
        default:
            job->handleReference(cursor, kind, loc, clang_getCursorReferenced(cursor), parent);
            break;
        }
        break;
    case RTags::Other:
        assert(0);
        break;
    }
    return CXChildVisit_Recurse;
}
Ejemplo n.º 18
0
Archivo: Log.cpp Proyecto: jmataraz/rct
Log::Log(int level)
{
    if (testLog(level))
        mData.reset(new Data(level));
}
Ejemplo n.º 19
0
Archivo: Log.cpp Proyecto: emdeesee/rct
Log::Log(LogLevel level, Flags<LogOutput::LogFlag> flags)
{
    if (testLog(level))
        mData.reset(new Data(level, flags));
}
Ejemplo n.º 20
0
CXChildVisitResult ClangIndexer::indexVisitor(CXCursor cursor, CXCursor parent, CXClientData data)
{
    ClangIndexer *indexer = static_cast<ClangIndexer*>(data);
    // error() << "indexVisitor" << cursor;
    // FILE *f = fopen("/tmp/clangindex.log", "a");
    // String str;
    // Log(&str) << cursor;
    // fwrite(str.constData(), 1, str.size(), f);
    // fwrite("\n", 1, 1, f);
    // fclose(f);
    const LastCursorUpdater updater(indexer->mLastCursor, cursor);

    const CXCursorKind kind = clang_getCursorKind(cursor);
    const RTags::CursorType type = RTags::cursorType(kind);
    if (type == RTags::Other)
        return CXChildVisit_Recurse;

    bool blocked = false;

    Location loc = indexer->createLocation(cursor, &blocked);
    if (blocked) {
        // error() << "blocked" << cursor;
        ++indexer->mBlocked;
        return CXChildVisit_Continue;
    } else if (loc.isNull()) {
        // error() << "Got null" << cursor;
        return CXChildVisit_Recurse;
    }
    ++indexer->mAllowed;
    if (indexer->mLogFile) {
        String out;
        Log(&out) << cursor;
        fwrite(out.constData(), 1, out.size(), indexer->mLogFile);
        fwrite("\n", 1, 1, indexer->mLogFile);
    }

    if (testLog(VerboseDebug)) {
        Log log(VerboseDebug);
        log << cursor;
        CXCursor ref = clang_getCursorReferenced(cursor);
        if (!clang_isInvalid(clang_getCursorKind(ref)) && !clang_equalCursors(ref, cursor)) {
            log << "refs" << ref;
        }
    }
    switch (type) {
    case RTags::Cursor:
        indexer->handleCursor(cursor, kind, loc);
        break;
    case RTags::Include:
        indexer->handleInclude(cursor, kind, loc);
        break;
    case RTags::Reference:
        switch (kind) {
        case CXCursor_OverloadedDeclRef: {
            const int count = clang_getNumOverloadedDecls(cursor);
            for (int i=0; i<count; ++i) {
                const CXCursor ref = clang_getOverloadedDecl(cursor, i);
                indexer->handleReference(cursor, kind, loc, ref, parent);
            }
            break; }
        case CXCursor_CXXDeleteExpr:
            indexer->handleReference(cursor, kind, loc, findDestructorForDelete(cursor), parent);
            break;
        case CXCursor_CallExpr: {
            // uglehack, see rtags/tests/nestedClassConstructorCallUgleHack/
            const CXCursor ref = clang_getCursorReferenced(cursor);
            if (clang_getCursorKind(ref) == CXCursor_Constructor
                && clang_getCursorKind(indexer->mLastCursor) == CXCursor_TypeRef
                && clang_getCursorKind(parent) != CXCursor_VarDecl) {
                loc = indexer->createLocation(indexer->mLastCursor);
                indexer->handleReference(indexer->mLastCursor, kind, loc, ref, parent);
            } else {
                indexer->handleReference(cursor, kind, loc, ref, parent);
            }
            break; }
        default:
            indexer->handleReference(cursor, kind, loc, clang_getCursorReferenced(cursor), parent);
            break;
        }
        break;
    case RTags::Other:
        assert(0);
        break;
    }
    return CXChildVisit_Recurse;
}