Ejemplo n.º 1
0
translation_unit& index::create_translation_unit(const std::string& filename, const std::vector<std::string>& args, const std::vector<unsaved_file>& unsaved)
{
    auto argv = convert_args(args);
    auto unsaved_files = convert_unsaved_files(unsaved);
    auto tu = clang_createTranslationUnitFromSourceFile(idx, filename.c_str(), argv.size(), argv.data(), unsaved_files.size(), unsaved_files.data());
    if(!tu)
        throw error("unable to parse tu");
    
    tus.emplace_back(tu);
    return tus.back();
}
Ejemplo n.º 2
0
void ReflectionParser::Parse(void)
{
    m_index = clang_createIndex( true, m_options.displayDiagnostics );

    std::vector<const char *> arguments;

#if defined(SYSTEM_INCLUDE_DIRECTORY)

    arguments.emplace_back( "-I" SYSTEM_INCLUDE_DIRECTORY );

#endif

    for (auto &argument : m_options.arguments)
        arguments.emplace_back( argument.c_str( ) );

    if (m_options.displayDiagnostics)
    {
        for (auto *argument : arguments)
            std::cout << argument << std::endl;
    }

    m_translationUnit = clang_createTranslationUnitFromSourceFile(
        m_index,
        m_options.inputSourceFile.c_str( ),
        static_cast<int>( arguments.size( ) ),
        arguments.data( ),
        0,
        nullptr
    );

    auto cursor = clang_getTranslationUnitCursor( m_translationUnit );

    Namespace tempNamespace;

    buildClasses( cursor, tempNamespace );

    tempNamespace.clear( );

    buildGlobals( cursor, tempNamespace );

    tempNamespace.clear( );

    buildGlobalFunctions( cursor, tempNamespace );

    tempNamespace.clear( );

    buildEnums( cursor, tempNamespace );
}
Ejemplo n.º 3
0
int perform_test_load_source(int argc, const char **argv,
                             const char *filter, CXCursorVisitor Visitor,
                             PostVisitTU PV) {
  const char *UseExternalASTs =
    getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION");
  CXIndex Idx;
  CXTranslationUnit TU;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  int result;
  
  Idx = clang_createIndex(/* excludeDeclsFromPCH */
                          !strcmp(filter, "local") ? 1 : 0,
                          /* displayDiagnosics=*/1);

  if (UseExternalASTs && strlen(UseExternalASTs))
    clang_setUseExternalASTGeneration(Idx, 1);

  if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
    clang_disposeIndex(Idx);
    return -1;
  }

  TU = clang_createTranslationUnitFromSourceFile(Idx, 0,
                                                 argc - num_unsaved_files,
                                                 argv + num_unsaved_files,
                                                 num_unsaved_files,
                                                 unsaved_files);
  if (!TU) {
    fprintf(stderr, "Unable to load translation unit!\n");
    free_remapped_files(unsaved_files, num_unsaved_files);
    clang_disposeIndex(Idx);
    return 1;
  }

  result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
  free_remapped_files(unsaved_files, num_unsaved_files);
  clang_disposeIndex(Idx);
  return result;
}
Ejemplo n.º 4
0
int main(int argc, char ** argv)
{
    CXTranslationUnit tu;
    CXIndex idx;
    CXCursor cur;
    char * filename;

    if(argc != 2)
    {
        printf("Usage: %s source_filename.c\n", argv[0]);
        return EXIT_FAILURE;
    }

    filename = argv[1];
    idx = clang_createIndex(1, 1);
    // TODO: fixme, obvious
    const char * args[] = {"-I/opt/local/include"};
    tu = clang_createTranslationUnitFromSourceFile(idx, filename, 1, args, 0, NULL);
    cur = clang_getTranslationUnitCursor(tu);

    clang_visitChildren(cur, foundChild, strdup(filename));

    return EXIT_SUCCESS;
}
TranslationUnit::TranslationUnit(
    CXIndex index                                           ///< Clang-C index instance to use
  , const KUrl& filename_url                                ///< File (document) URI
  , clang::compiler_options&& options                       ///< Compiler options to use
  )
  : m_filename(filename_url.toLocalFile().toUtf8())
{
    kDebug(DEBUG_AREA) << "Creating a translation unit: " << filename_url.toLocalFile();
    kDebug(DEBUG_AREA) << "w/ the following compiler options:" << options;
    auto clang_options = options.get();
    // Ok, ready to go
    m_unit = clang_createTranslationUnitFromSourceFile(
        index
      , m_filename.constData()
      , options.size()
      , options.data()
      , 0
      , 0
      );
    if (!m_unit)
        throw Exception::ParseFailure(
            i18nc("@item:intext", "Failure to parse C++ code").toAscii().constData()
          );
}
Ejemplo n.º 6
0
bool ReflectionParser::ProcessFile(std::string const & fileName, bool InProcessModule)
{
  if (!InProcessModule && !m_sourceCache->RequestGenerate(fileName))
    return true;

  Clear();

  m_currentFile = fileName;
  m_index = clang_createIndex(true, false);

  std::vector<const char *> arguments;

  for (auto &argument : m_options.arguments)
  {
    // unescape flags
    boost::algorithm::replace_all(argument, "\\-", "-");

    arguments.emplace_back(argument.c_str());
  }

  m_translationUnit = clang_createTranslationUnitFromSourceFile(
        m_index,
        fileName.c_str(),
        static_cast<int>(arguments.size()),
        arguments.data(),
        0,
        nullptr
        );

  auto cursor = clang_getTranslationUnitCursor(m_translationUnit);

  try
  {
    Namespace tempNamespace;
    buildClasses(cursor, tempNamespace);
    tempNamespace.clear();

    if (ContainsModule() && !InProcessModule)
    {
      if (m_classes.size() > 1)
      {
        EMIT_ERROR("You can't implement any other classes in one file with module class");
      }
      return false;
    }

    if (RequestGenerate())
    {
      std::string fileId = GetFileID(fileName);
      std::stringstream outCode;

      // includes
      outCode << "#include <memory>\n\n";
      outCode << "#include \"sc-memory/cpp/sc_memory.hpp\"\n\n\n";
      outCode << "#include \"sc-memory/cpp/sc_event.hpp\"\n\n\n";

      for (auto it = m_classes.begin(); it != m_classes.end(); ++it)
      {
        Class const * klass = *it;
        if (klass->ShouldGenerate())
        {
          klass->GenerateCode(fileId, outCode, this);
        }
      }

      /// write ScFileID definition
      outCode << "\n\n#undef ScFileID\n";
      outCode << "#define ScFileID " << fileId;

      // generate output file
      boost::filesystem::path outputPath(m_options.outputPath);
      outputPath /= boost::filesystem::path(GetOutputFileName(fileName));
      std::ofstream outputFile(outputPath.string());
      outputFile << outCode.str();
      outputFile << std::endl << std::endl;
      outputFile.close();
    }

    clang_disposeIndex(m_index);
    clang_disposeTranslationUnit(m_translationUnit);

  } catch (Exception e)
  {
    clang_disposeIndex(m_index);
    clang_disposeTranslationUnit(m_translationUnit);

    EMIT_ERROR(e.GetDescription());
  }


  return true;
}
Ejemplo n.º 7
0
int perform_token_annotation(int argc, const char **argv) {
  const char *input = argv[1];
  char *filename = 0;
  unsigned line, second_line;
  unsigned column, second_column;
  CXIndex CIdx;
  CXTranslationUnit TU = 0;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  CXToken *tokens;
  unsigned num_tokens;
  CXSourceRange range;
  CXSourceLocation startLoc, endLoc;
  CXFile file = 0;
  CXCursor *cursors = 0;
  unsigned i;

  input += strlen("-test-annotate-tokens=");
  if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
                                          &second_line, &second_column)))
    return errorCode;

  if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
    return -1;

  CIdx = clang_createIndex(0, 1);
  TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
                                                 argc - num_unsaved_files - 3,
                                                 argv + num_unsaved_files + 2,
                                                 num_unsaved_files,
                                                 unsaved_files);
  if (!TU) {
    fprintf(stderr, "unable to parse input\n");
    clang_disposeIndex(CIdx);
    free(filename);
    free_remapped_files(unsaved_files, num_unsaved_files);
    return -1;
  }
  errorCode = 0;

  file = clang_getFile(TU, filename);
  if (!file) {
    fprintf(stderr, "file %s is not in this translation unit\n", filename);
    errorCode = -1;
    goto teardown;
  }

  startLoc = clang_getLocation(TU, file, line, column);
  if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
    fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
            column);
    errorCode = -1;
    goto teardown;
  }

  endLoc = clang_getLocation(TU, file, second_line, second_column);
  if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
    fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
            second_line, second_column);
    errorCode = -1;
    goto teardown;
  }

  range = clang_getRange(startLoc, endLoc);
  clang_tokenize(TU, range, &tokens, &num_tokens);
  cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
  clang_annotateTokens(TU, tokens, num_tokens, cursors);
  for (i = 0; i != num_tokens; ++i) {
    const char *kind = "<unknown>";
    CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
    CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
    unsigned start_line, start_column, end_line, end_column;

    switch (clang_getTokenKind(tokens[i])) {
    case CXToken_Punctuation: kind = "Punctuation"; break;
    case CXToken_Keyword: kind = "Keyword"; break;
    case CXToken_Identifier: kind = "Identifier"; break;
    case CXToken_Literal: kind = "Literal"; break;
    case CXToken_Comment: kind = "Comment"; break;
    }
    clang_getInstantiationLocation(clang_getRangeStart(extent),
                                   0, &start_line, &start_column, 0);
    clang_getInstantiationLocation(clang_getRangeEnd(extent),
                                   0, &end_line, &end_column, 0);
    printf("%s: \"%s\" ", kind, clang_getCString(spelling));
    PrintExtent(stdout, start_line, start_column, end_line, end_column);
    if (!clang_isInvalid(cursors[i].kind)) {
      printf(" ");
      PrintCursor(cursors[i]);
    }
    printf("\n");
  }
  free(cursors);

 teardown:
  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(filename);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return errorCode;
}
Ejemplo n.º 8
0
int inspect_cursor_at(int argc, const char **argv) {
  CXIndex CIdx;
  int errorCode;
  struct CXUnsavedFile *unsaved_files = 0;
  int num_unsaved_files = 0;
  CXTranslationUnit TU;
  CXCursor Cursor;
  CursorSourceLocation *Locations = 0;
  unsigned NumLocations = 0, Loc;

  /* Count the number of locations. */
  while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
    ++NumLocations;

  /* Parse the locations. */
  assert(NumLocations > 0 && "Unable to count locations?");
  Locations = (CursorSourceLocation *)malloc(
                                  NumLocations * sizeof(CursorSourceLocation));
  for (Loc = 0; Loc < NumLocations; ++Loc) {
    const char *input = argv[Loc + 1] + strlen("-cursor-at=");
    if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
                                            &Locations[Loc].line,
                                            &Locations[Loc].column, 0, 0)))
      return errorCode;
  }

  if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
                           &num_unsaved_files))
    return -1;

  CIdx = clang_createIndex(0, 1);
  TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1],
                                  argc - num_unsaved_files - 2 - NumLocations,
                                   argv + num_unsaved_files + 1 + NumLocations,
                                                 num_unsaved_files,
                                                 unsaved_files);
  if (!TU) {
    fprintf(stderr, "unable to parse input\n");
    return -1;
  }

  for (Loc = 0; Loc < NumLocations; ++Loc) {
    CXFile file = clang_getFile(TU, Locations[Loc].filename);
    if (!file)
      continue;

    Cursor = clang_getCursor(TU,
                             clang_getLocation(TU, file, Locations[Loc].line,
                                               Locations[Loc].column));
    PrintCursor(Cursor);
    printf("\n");
    free(Locations[Loc].filename);
  }

  PrintDiagnostics(TU);
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(CIdx);
  free(Locations);
  free_remapped_files(unsaved_files, num_unsaved_files);
  return 0;
}