Пример #1
1
  private IName[] findDefinitions(
      IIndex index, IASTTranslationUnit ast, NameKind kind, IBinding binding) throws CoreException {
    List<IASTName> declNames = new ArrayList<IASTName>();
    declNames.addAll(Arrays.asList(ast.getDefinitionsInAST(binding)));
    for (Iterator<IASTName> i = declNames.iterator(); i.hasNext(); ) {
      IASTName name = i.next();
      final IBinding b2 = name.resolveBinding();
      if (b2 instanceof ICPPUsingDeclaration) {
        i.remove();
      }
      if (binding != b2 && binding instanceof ICPPSpecialization) {
        // Make sure binding specializes b2 so that for instance we do not navigate from
        // one partial specialization to another.
        IBinding spec = binding;
        while (spec instanceof ICPPSpecialization) {
          spec = ((ICPPSpecialization) spec).getSpecializedBinding();
          if (spec == b2) break;
        }
        if (!(spec instanceof ICPPSpecialization)) {
          i.remove();
        }
      }
    }
    if (!declNames.isEmpty()) {
      return declNames.toArray(new IASTName[declNames.size()]);
    }

    // 2. Try definition in index.
    return index.findNames(
        binding, IIndex.FIND_DEFINITIONS | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES);
  }
  public void runWithIndex(
      IIndex parseIndex,
      IIndex searchScopeindex,
      IIndexLocationConverter converter,
      IProgressMonitor monitor)
      throws OperationCanceledException, CoreException, InterruptedException {
    fConverter = converter;

    if (fElement instanceof ICElement) {
      IBinding binding = null;
      parseIndex.acquireReadLock();
      try {
        binding = IndexQueries.elementToBinding(parseIndex, (ICElement) fElement, fPath);
        cElement = CElementForBinding(parseIndex, binding);
      } finally {
        parseIndex.releaseReadLock();
      }
      if (binding != null) {
        searchScopeindex.acquireReadLock();
        try {
          createMatches(searchScopeindex, binding);
        } finally {
          searchScopeindex.releaseReadLock();
        }
      }
    }
  }
Пример #3
0
  IStatus performNavigation(IProgressMonitor monitor) throws CoreException {
    fAction.clearStatusLine();

    assert fIndex == null;
    if (fIndex != null) return Status.CANCEL_STATUS;

    fMonitor = monitor;
    fIndex =
        CCorePlugin.getIndexManager()
            .getIndex(
                fTranslationUnit.getCProject(),
                IIndexManager.ADD_DEPENDENCIES | IIndexManager.ADD_DEPENDENT);

    try {
      fIndex.acquireReadLock();
    } catch (InterruptedException e) {
      return Status.CANCEL_STATUS;
    }

    try {
      return ASTProvider.getASTProvider()
          .runOnAST(fTranslationUnit, ASTProvider.WAIT_ACTIVE_ONLY, monitor, this);
    } finally {
      fIndex.releaseReadLock();
    }
  }
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 2);

      if (testData.length < 2) return;
      IFile file =
          TestSourceReader.createFile(
              cproject.getProject(), new Path("header.h"), testData[0].toString());
      CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Project PDOM: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject);

      index.acquireReadLock();
      IFile cppfile =
          TestSourceReader.createFile(
              cproject.getProject(),
              new Path("references.c" + (cpp ? "pp" : "")),
              testData[1].toString());
      ast = TestSourceReader.createIndexBasedAST(index, cproject, cppfile);
    }
  @Override
  protected void setUp() throws Exception {
    cproject =
        cpp
            ? CProjectHelper.createCCProject(
                getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
            : CProjectHelper.createCProject(
                getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
    testData = testSourceReader.getContentsForTest(getName());

    if (testData.length > 0) {
      for (int i = 0; i < testData.length - 1; i++) {
        String filename = String.format("header%d.h", i + 1);
        IFile file =
            TestSourceReader.createFile(
                cproject.getProject(), new Path(filename), testData[i].toString());
        CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      }
    }

    IFile cppfile =
        TestSourceReader.createFile(
            cproject.getProject(), new Path("source.c" + (cpp ? "pp" : "")), getAstSource());
    waitForIndexer(cproject);

    if (DEBUG) {
      System.out.println("Project PDOM: " + getName());
      ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
    }

    index = CCorePlugin.getIndexManager().getIndex(cproject);

    index.acquireReadLock();
    ast = TestSourceReader.createIndexBasedAST(index, cproject, cppfile);
  }
Пример #6
0
 @Override
 protected void processTranslationUnitUnlocked(ITranslationUnit tu) {
   try {
     index = CCorePlugin.getIndexManager().getIndex(tu.getCProject());
     // lock the index for read access
     index.acquireReadLock();
     try {
       // traverse the translation unit using the visitor pattern.
       this.file = tu.getFile();
       processUnit(tu);
     } finally {
       this.file = null;
       index.releaseReadLock();
     }
   } catch (CoreException e) {
     CodanCorePlugin.log(e);
   } catch (InterruptedException e) {
     // ignore
   }
 }
 @Override
 protected void tearDown() throws Exception {
   if (index != null) {
     index.releaseReadLock();
   }
   if (cproject != null) {
     cproject
         .getProject()
         .delete(
             IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT, new NullProgressMonitor());
   }
 }
Пример #8
0
 private IName[] findDeclarations(IIndex index, IASTTranslationUnit ast, IBinding binding)
     throws CoreException {
   IName[] declNames = ast.getDeclarationsInAST(binding);
   for (int i = 0; i < declNames.length; i++) {
     IName name = declNames[i];
     if (name.isDefinition()) declNames[i] = null;
   }
   declNames = (IName[]) ArrayUtil.removeNulls(IName.class, declNames);
   if (declNames.length == 0) {
     declNames =
         index.findNames(
             binding, IIndex.FIND_DECLARATIONS | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES);
   }
   return declNames;
 }
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  getName() + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 0);

      List<IFile> astFiles = new ArrayList<IFile>();
      for (int i = 0; i < testData.length; i++) {
        StringBuilder contents = testData[i];
        int endOfLine = contents.indexOf("\n");
        if (endOfLine >= 0) endOfLine++;
        else endOfLine = contents.length();
        String filename = contents.substring(0, endOfLine).trim();
        contents.delete(0, endOfLine); // Remove first line from the file contents
        boolean astRequested = filename.endsWith("*");
        if (astRequested) {
          filename = filename.substring(0, filename.length() - 1).trim();
        }
        IFile file =
            TestSourceReader.createFile(
                cproject.getProject(), new Path(filename), contents.toString());
        if (astRequested || (i == testData.length - 1 && astFiles.isEmpty())) {
          astSources.add(contents);
          astFiles.add(file);
        }
      }
      CCorePlugin.getIndexManager().setIndexerId(cproject, IPDOMManager.ID_FAST_INDEXER);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Project PDOM: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject);

      index.acquireReadLock();
      for (IFile file : astFiles) {
        asts.add(TestSourceReader.createIndexBasedAST(index, cproject, file));
      }
    }
    @Override
    public void setUp() throws Exception {
      cproject =
          cpp
              ? CProjectHelper.createCCProject(
                  "OnlineContent" + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER)
              : CProjectHelper.createCProject(
                  "OnlineContent" + System.currentTimeMillis(), "bin", IPDOMManager.ID_NO_INDEXER);
      Bundle b = CTestPlugin.getDefault().getBundle();
      testData =
          TestSourceReader.getContentsForTest(
              b, "parser", IndexBindingResolutionTestBase.this.getClass(), getName(), 2);
      referenced = createReferencedContent();

      TestScannerProvider.sIncludes =
          new String[] {referenced.getProject().getLocation().toOSString()};
      IFile references =
          TestSourceReader.createFile(
              cproject.getProject(),
              new Path("refs.c" + (cpp ? "pp" : "")),
              testData[1].toString());

      IProject[] refs = new IProject[] {referenced.getProject()};
      IProjectDescription pd = cproject.getProject().getDescription();
      pd.setReferencedProjects(refs);
      cproject.getProject().setDescription(pd, new NullProgressMonitor());

      IndexerPreferences.set(
          cproject.getProject(), IndexerPreferences.KEY_INDEXER_ID, IPDOMManager.ID_FAST_INDEXER);
      CCorePlugin.getIndexManager().reindex(cproject);
      waitForIndexer(cproject);

      if (DEBUG) {
        System.out.println("Online: " + getName());
        ((PDOM) CCoreInternals.getPDOMManager().getPDOM(cproject)).accept(new PDOMPrettyPrinter());
      }

      index = CCorePlugin.getIndexManager().getIndex(cproject, IIndexManager.ADD_DEPENDENCIES);
      index.acquireReadLock();
      ast = TestSourceReader.createIndexBasedAST(index, cproject, references);
    }
Пример #11
0
  private boolean navigationFallBack(IASTTranslationUnit ast, IASTName sourceName, NameKind kind) {
    // Bug 102643, as a fall-back we look up the selected word in the index.
    if (fSelectedText != null && fSelectedText.length() > 0) {
      try {
        final ICProject project = fTranslationUnit.getCProject();
        final char[] name = fSelectedText.toCharArray();
        List<ICElement> elems = new ArrayList<ICElement>();

        // Bug 252549, search for names in the AST first.
        Set<IBinding> primaryBindings = new HashSet<IBinding>();
        ASTNameCollector nc = new ASTNameCollector(fSelectedText);
        ast.accept(nc);
        IASTName[] candidates = nc.getNames();
        for (IASTName astName : candidates) {
          try {
            IBinding b = astName.resolveBinding();
            if (b != null && !(b instanceof IProblemBinding)) {
              primaryBindings.add(b);
            }
          } catch (RuntimeException e) {
            CUIPlugin.log(e);
          }
        }

        // Search the index, also.
        final IndexFilter filter =
            IndexFilter.getDeclaredBindingFilter(ast.getLinkage().getLinkageID(), false);
        final IIndexBinding[] idxBindings = fIndex.findBindings(name, false, filter, fMonitor);
        for (IIndexBinding idxBinding : idxBindings) {
          primaryBindings.add(idxBinding);
        }

        // Search for a macro in the index.
        IIndexMacro[] macros = fIndex.findMacros(name, filter, fMonitor);
        for (IIndexMacro macro : macros) {
          ICElement elem = IndexUI.getCElementForMacro(project, fIndex, macro);
          if (elem != null) {
            elems.add(elem);
          }
        }

        Collection<IBinding> secondaryBindings;
        if (ast instanceof ICPPASTTranslationUnit) {
          secondaryBindings = cppRemoveSecondaryBindings(primaryBindings, sourceName);
        } else {
          secondaryBindings = defaultRemoveSecondaryBindings(primaryBindings, sourceName);
        }

        // Convert bindings to CElements.
        Collection<IBinding> bs = primaryBindings;
        for (int k = 0; k < 2; k++) {
          for (IBinding binding : bs) {
            IName[] names = findNames(fIndex, ast, kind, binding);
            // Exclude names of the same kind.
            for (int i = 0; i < names.length; i++) {
              if (getNameKind(names[i]) == kind) {
                names[i] = null;
              }
            }
            names = (IName[]) ArrayUtil.removeNulls(IName.class, names);
            convertToCElements(project, fIndex, names, elems);
          }
          // In case we did not find anything, consider the secondary bindings.
          if (!elems.isEmpty()) break;
          bs = secondaryBindings;
        }
        if (navigateCElements(elems)) {
          return true;
        }
        if (sourceName != null && sourceName.isDeclaration()) {
          // Select the name at the current location as the last resort.
          return navigateToName(sourceName);
        }
      } catch (CoreException e) {
        CUIPlugin.log(e);
      }
    }
    return false;
  }
Пример #12
0
 @Override
 public void modifyAST(IIndex index, IMarker marker) {
   CompositeChange c = new CompositeChange(Messages.QuickFixCreateParameter_0);
   try {
     ITranslationUnit baseTU = getTranslationUnitViaEditor(marker);
     IASTTranslationUnit baseAST = baseTU.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
     IASTName astName = getASTNameFromMarker(marker, baseAST);
     if (astName == null) {
       return;
     }
     IASTDeclaration declaration =
         CxxAstUtils.createDeclaration(astName, baseAST.getASTNodeFactory(), index);
     // We'll need a FunctionParameterDeclaration later
     final IASTDeclSpecifier finalDeclSpec = (IASTDeclSpecifier) declaration.getChildren()[0];
     final IASTDeclarator finalDeclarator = (IASTDeclarator) declaration.getChildren()[1];
     IASTFunctionDefinition function = CxxAstUtils.getEnclosingFunction(astName);
     if (function == null) {
       return;
     }
     // Find the function declarations
     NameFinderVisitor nameFinderVisitor = new NameFinderVisitor();
     function.accept(nameFinderVisitor);
     IASTName funcName = nameFinderVisitor.name;
     IBinding binding = funcName.resolveBinding();
     IIndexName[] declarations = index.findNames(binding, IIndex.FIND_DECLARATIONS_DEFINITIONS);
     if (declarations.length == 0) {
       return;
     }
     HashMap<ITranslationUnit, IASTTranslationUnit> cachedASTs =
         new HashMap<ITranslationUnit, IASTTranslationUnit>();
     HashMap<ITranslationUnit, ASTRewrite> cachedRewrites =
         new HashMap<ITranslationUnit, ASTRewrite>();
     for (IIndexName iname : declarations) {
       ITranslationUnit declTU = CxxAstUtils.getTranslationUnitFromIndexName(iname);
       if (declTU == null) {
         continue;
       }
       ASTRewrite rewrite;
       IASTTranslationUnit declAST;
       if (!cachedASTs.containsKey(declTU)) {
         declAST = declTU.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
         rewrite = ASTRewrite.create(declAST);
         cachedASTs.put(declTU, declAST);
         cachedRewrites.put(declTU, rewrite);
       } else {
         declAST = cachedASTs.get(declTU);
         rewrite = cachedRewrites.get(declTU);
       }
       IASTFileLocation fileLocation = iname.getFileLocation();
       IASTName declName =
           declAST
               .getNodeSelector(null)
               .findEnclosingName(fileLocation.getNodeOffset(), fileLocation.getNodeLength());
       if (declName == null) {
         continue;
       }
       INodeFactory factory = declAST.getASTNodeFactory();
       IASTFunctionDeclarator functionDecl;
       {
         IASTNode n = declName;
         while (n instanceof IASTName) {
           n = n.getParent();
         }
         functionDecl = (IASTFunctionDeclarator) n;
       }
       IASTParameterDeclaration newParam =
           factory.newParameterDeclaration(finalDeclSpec, finalDeclarator);
       rewrite.insertBefore(functionDecl, null, newParam, null);
     }
     for (ASTRewrite rewrite : cachedRewrites.values()) {
       c.add(rewrite.rewriteAST());
     }
     c.perform(new NullProgressMonitor());
   } catch (CoreException e) {
     CheckersUiActivator.log(e);
   }
 }