1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-07-23 17:05:26 +02:00

Testing the scalability of the Commit Files dialog. No really, I've removed the old indexer, search and type cache and have fixed all the compile errors that doing so caused. A number of features are disabled to be re-enabled later.

This commit is contained in:
Doug Schaefer 2006-04-12 17:11:14 +00:00
parent 160774ed3d
commit c394f40e48
466 changed files with 1277 additions and 73129 deletions

View file

@ -35,7 +35,6 @@ import org.eclipse.cdt.managedbuilder.core.tests.ResourceBuildCoreTests;
*/
public class AllManagedBuildTests {
public static void main(String[] args) {
CCorePlugin.getDefault().getCoreModel().getIndexManager().reset();
junit.textui.TestRunner.run(AllManagedBuildTests.suite());
}
public static Test suite() {

View file

@ -10,22 +10,10 @@
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.makegen.internal;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.core.search.PathCollector;
import org.eclipse.cdt.internal.core.search.PatternSearchJob;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.matching.CSearchPattern;
import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
/**
* @since 2.0
@ -36,37 +24,39 @@ public class DefaultIndexerDependencyCalculator implements IManagedDependencyGen
* @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderDependencyCalculator#findDependencies(org.eclipse.core.resources.IResource)
*/
public IResource[] findDependencies(IResource resource, IProject project) {
PathCollector pathCollector = new PathCollector();
ICSearchScope scope = SearchEngine.createWorkspaceScope();
CSearchPattern pattern = CSearchPattern.createPattern(resource.getLocation().toOSString(), ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES, ICSearchConstants.EXACT_MATCH, true);
IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
indexManager.performConcurrentJob(
new PatternSearchJob(
(CSearchPattern) pattern,
scope,
pathCollector,
indexManager),
ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
null, null);
// We will get back an array of resource names relative to the workspace
String[] deps = pathCollector.getPaths();
// Convert them to something useful
List depList = new ArrayList();
IResource res = null;
IWorkspaceRoot root = null;
if (project != null) {
root = project.getWorkspace().getRoot();
}
for (int index = 0; index < deps.length; ++index) {
res = root.findMember(deps[index]);
if (res != null) {
depList.add(res);
}
}
return (IResource[]) depList.toArray(new IResource[depList.size()]);
// PathCollector pathCollector = new PathCollector();
// ICSearchScope scope = SearchEngine.createWorkspaceScope();
// CSearchPattern pattern = CSearchPattern.createPattern(resource.getLocation().toOSString(), ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES, ICSearchConstants.EXACT_MATCH, true);
// IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
// indexManager.performConcurrentJob(
// new PatternSearchJob(
// (CSearchPattern) pattern,
// scope,
// pathCollector,
// indexManager),
// ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
// null, null);
//
// // We will get back an array of resource names relative to the workspace
// String[] deps = pathCollector.getPaths();
//
// // Convert them to something useful
// List depList = new ArrayList();
// IResource res = null;
// IWorkspaceRoot root = null;
// if (project != null) {
// root = project.getWorkspace().getRoot();
// }
// for (int index = 0; index < deps.length; ++index) {
// res = root.findMember(deps[index]);
// if (res != null) {
// depList.add(res);
// }
// }
//
// return (IResource[]) depList.toArray(new IResource[depList.size()]);
// TODO this needs to be redone to fit on the PDOM
return new IResource[0];
}
/* (non-Javadoc)

View file

@ -10,20 +10,17 @@
*******************************************************************************/
package org.eclipse.cdt.managedbuilder.ui.tests.suite;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.managedbuilder.ui.tests.TestCProjectPlatformPage;
import org.eclipse.cdt.managedbuilder.ui.tests.TestCustomPageManager;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.cdt.managedbuilder.ui.tests.TestCProjectPlatformPage;
import org.eclipse.cdt.managedbuilder.ui.tests.TestCustomPageManager;
/**
*
*/
public class AllManagedBuildUITests {
public static void main(String[] args) {
CCorePlugin.getDefault().getCoreModel().getIndexManager().reset();
junit.textui.TestRunner.run(AllManagedBuildUITests.suite());
}
public static Test suite() {

View file

@ -5,8 +5,6 @@
<classpathentry kind="src" path="model"/>
<classpathentry kind="src" path="parser"/>
<classpathentry kind="src" path="suite"/>
<classpathentry kind="src" path="indexer"/>
<classpathentry kind="src" path="search"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="regression"/>

View file

@ -7,7 +7,6 @@ Bundle-ClassPath: cdtcoretests.jar
Bundle-Activator: org.eclipse.cdt.core.testplugin.CTestPlugin
Bundle-Localization: plugin
Export-Package: org.eclipse.cdt.core.cdescriptor.tests,
org.eclipse.cdt.core.indexer.tests,
org.eclipse.cdt.core.internal.errorparsers.tests,
org.eclipse.cdt.core.model.failedTests,
org.eclipse.cdt.core.model.tests,
@ -16,7 +15,6 @@ Export-Package: org.eclipse.cdt.core.cdescriptor.tests,
org.eclipse.cdt.core.parser.tests.ast2,
org.eclipse.cdt.core.parser.tests.prefix,
org.eclipse.cdt.core.parser.tests.scanner2,
org.eclipse.cdt.core.search.tests,
org.eclipse.cdt.core.suite,
org.eclipse.cdt.core.testplugin,
org.eclipse.cdt.core.testplugin.util,

View file

@ -1,244 +0,0 @@
/**********************************************************************
* Copyright (c) 2002, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on Jun 19, 2003
*/
package org.eclipse.cdt.core.indexer.tests;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorOperation;
import org.eclipse.cdt.core.index.IIndexChangeListener;
import org.eclipse.cdt.core.index.IIndexDelta;
import org.eclipse.cdt.core.index.IndexChangeEvent;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author bgheorgh
*/
public class DOMSourceIndexerPerfTests extends TestCase {
IProject testProject;
DOMSourceIndexer sourceIndexer;
IndexManager indexManager;
static long timeC = 0;
static long timeCPP = 0;
static int countC = 0;
static int countCPP = 0;
static final int MAXCOUNT = 10;
/**
* @param name
*/
public DOMSourceIndexerPerfTests(String name) {
super(name);
}
public void resetIndexer(final String indexerId){
if ( testProject != null) {
ICDescriptorOperation op = new ICDescriptorOperation() {
public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException {
descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID);
descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId);
}
};
try {
CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor());
CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject);
} catch (CoreException e) {}
}
}
public static void main(String[] args) {}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
testProject = CProjectHelper.createCCProject("IndexerTestProject", "bin").getProject(); //$NON-NLS-1$
assertNotNull("Unable to create project", testProject); //$NON-NLS-1$
resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID);
indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(testProject);
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() {
try {
super.tearDown();
} catch (Exception e1) {}
//Delete project
if (testProject.exists()) {
try {
System.gc();
System.runFinalization();
testProject.delete(true, null);
} catch (CoreException e) {
fail(getMessage(e.getStatus()));
}
}
}
/**
* Makes error message from multistatus
*
* @param status
* @return
*/
private String getMessage(IStatus status) {
StringBuffer message = new StringBuffer("["); //$NON-NLS-1$
message.append(status.getMessage());
if (status.isMultiStatus()) {
IStatus children[] = status.getChildren();
for (int i = 0; i < children.length; i++) {
message.append(getMessage(children[i]));
}
}
message.append("]"); //$NON-NLS-1$
return message.toString();
}
public static Test suite() {
timeC = 0;
timeCPP = 0;
countC = 0;
countCPP = 0;
TestSuite suite = new TestSuite(DOMSourceIndexerPerfTests.class.getName());
Test t1 = new DOMSourceIndexerPerfTests("testC"); //$NON-NLS-1$
Test t2 = new DOMSourceIndexerPerfTests("testCPP"); //$NON-NLS-1$
for (int i = 0; i < MAXCOUNT; i++) {
suite.addTest(t1);
suite.addTest(t2);
}
return suite;
}
/**
* Unpack archive contents to project directory
*
* @param name - name of archive file w/o extension
* @param mask - pattern to check file extensions
* @return - list of files which fit to pattern
*/
private ArrayList unzip(String name, String mask) {
ArrayList lst = new ArrayList(20);
byte[] buffer = new byte[512];
String archname = "resources/zips/" + name + ".zip";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(CTestPlugin.getDefault().getFileInPlugin(new Path(archname)));
IPath projPath = testProject.getLocation();
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if (!entry.isDirectory()) {
IPath entryPath = projPath.append(entry.getName());
InputStream in = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(entryPath.toFile());
for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);
in.close();
out.close();
if (entryPath.lastSegment().endsWith(mask)) {
lst.add(entryPath.lastSegment());
}
}
}
zipFile.close();
} catch (IOException e) {
fail("Unzip error with " + archname + " : " + e.getLocalizedMessage());
}
return lst;
}
/**
* Adds files from list to index and counts indexing time
*
* @param lst - list of file names to be added
* @return - time (in ms) spent for indexing
*/
private long indexFiles(ArrayList lst) {
// wait for finish of other indexing processes, if any
while(indexManager.awaitingJobsCount()>0) {
try { Thread.sleep(20);
} catch (InterruptedException e) {}
}
System.gc();
long t0 = System.currentTimeMillis();
for (int i=0; i<lst.size(); i++) {
IFile f = testProject.getProject().getFile((String)(lst.get(i)));
sourceIndexer.addResource(testProject, f);
}
while(indexManager.awaitingJobsCount()>0) {
try { Thread.sleep(20);
} catch (InterruptedException e) {}
}
return (System.currentTimeMillis() - t0);
}
/**
* Test C source indexation
* @throws Exception
*/
public void testC() throws Exception {
long t0 = indexFiles(unzip("perf1", ".c"));
timeC += t0; countC++;
System.out.println("Index performance: " + t0 + " ms on C source[" + countC + "]");
if (countC == MAXCOUNT) {
System.out.println("Average performance on " + MAXCOUNT + " C passes: " + (timeC/MAXCOUNT));
}
}
/**
* Test C++ source indexation
* @throws Exception
*/
public void testCPP() throws Exception {
long t0 = indexFiles(unzip("perf2", ".cpp"));
timeCPP += t0; countCPP++;
System.out.println("Index performance: " + t0 + " ms on C++ source[" + countCPP + "]");
if (countCPP == MAXCOUNT) {
System.out.println("Average performance on " + MAXCOUNT + " C++ passes: " + (timeCPP/MAXCOUNT));
}
}
}

View file

@ -1,876 +0,0 @@
/**********************************************************************
* Copyright (c) 2002, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on Jun 19, 2003
*/
package org.eclipse.cdt.core.indexer.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorOperation;
import org.eclipse.cdt.core.index.IIndexChangeListener;
import org.eclipse.cdt.core.index.IIndexDelta;
import org.eclipse.cdt.core.index.IndexChangeEvent;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.core.tests.FailingTest;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.IQueryResult;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexerRunner;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author bgheorgh
*/
public class DOMSourceIndexerTests extends TestCase implements IIndexChangeListener {
IFile file;
IProject testProject;
NullProgressMonitor monitor;
IndexManager indexManager;
DOMSourceIndexer sourceIndexer;
boolean fileIndexed;
static final String sourceIndexerID = "org.eclipse.cdt.core.originalsourceindexer"; //$NON-NLS-1$
public static final int TIMEOUT = 50;
/**
* Constructor for IndexManagerTest.
* @param name
*/
public DOMSourceIndexerTests(String name) {
super(name);
}
public void resetIndexState() {
fileIndexed = false;
}
public void resetIndexer(final String indexerId){
if ( testProject != null) {
ICDescriptorOperation op = new ICDescriptorOperation() {
public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException {
descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID);
descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId);
}
};
try {
CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor());
CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject);
} catch (CoreException e) {}
}
}
public void waitForIndex(int maxSec) throws Exception {
int delay = 0;
while (fileIndexed != true && delay < (maxSec * 1000))
{
Thread.sleep(TIMEOUT);
delay += TIMEOUT;
}
}
public static void main(String[] args) {
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
monitor = new NullProgressMonitor();
//Create temp project
testProject = createProject("IndexerTestProject"); //$NON-NLS-1$
IPath pathLoc = CCorePlugin.getDefault().getStateLocation();
File indexFile = new File(pathLoc.append("3915980774.index").toOSString()); //$NON-NLS-1$
if (indexFile.exists())
indexFile.delete();
if (testProject==null)
fail("Unable to create project"); //$NON-NLS-1$
resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID);
//The DOM Source Indexer checks to see if a file has any scanner info
//set prior to indexing it in order to increase efficiency. We need to let it know
//that it is running in test mode in order to allow for this scanner info test to be skipped
DOMSourceIndexerRunner.setSkipScannerInfoTest(true);
indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
//indexManager.reset();
//Get the indexer used for the test project
sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(testProject);
sourceIndexer.addIndexChangeListener(this);
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() {
try {
super.tearDown();
sourceIndexer.removeIndexChangeListener(this);
} catch (Exception e1) {
}
//Delete project
if (testProject.exists()) {
try {
System.gc();
System.runFinalization();
testProject.delete(true, monitor);
} catch (CoreException e) {
fail(getMessage(e.getStatus()));
}
}
}
private String getMessage(IStatus status) {
StringBuffer message = new StringBuffer("["); //$NON-NLS-1$
message.append(status.getMessage());
if (status.isMultiStatus()) {
IStatus children[] = status.getChildren();
for (int i = 0; i < children.length; i++) {
message.append(getMessage(children[i]));
}
}
message.append("]"); //$NON-NLS-1$
return message.toString();
}
public static Test suite() {
TestSuite suite = new TestSuite(DOMSourceIndexerTests.class.getName());
suite.addTest(new DOMSourceIndexerTests("testAddNewFileToIndex")); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testForwardDeclarations")); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testIndexAll")); //$NON-NLS-1$
suite.addTest(new FailingTest(new DOMSourceIndexerTests("testIndexContents"))); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testMacros")); //$NON-NLS-1$
suite.addTest(new FailingTest(new DOMSourceIndexerTests("testRefs"))); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testExactDeclarations")); //$NON-NLS-1$
suite.addTest(new FailingTest(new DOMSourceIndexerTests("testRemoveFileFromIndex"))); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testRemoveProjectFromIndex")); //$NON-NLS-1$
suite.addTest(new DOMSourceIndexerTests("testIndexShutdown")); //$NON-NLS-1$
return suite;
}
/*
* Utils
*/
private IProject createProject(String projectName) throws CoreException {
ICProject cPrj = CProjectHelper.createCCProject(projectName, "bin"); //$NON-NLS-1$
return cPrj.getProject();
}
private IFile importFile(String fileName, String resourceLocation)throws Exception {
resetIndexState();
//Obtain file handle
file = testProject.getProject().getFile(fileName);
//Create file input stream
monitor = new NullProgressMonitor();
if (!file.exists()) {
file.create(new FileInputStream(
CTestPlugin.getDefault().getFileInPlugin(new Path(resourceLocation))),
false, monitor);
}
waitForIndex(20); // only wait 20 seconds max.
return file;
}
/*
* Start of tests
*/
public void testIndexAll() throws Exception {
//Add a file to the project
importFile("mail.cpp","resources/indexer/mail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
IIndex ind = sourceIndexer.getIndex(testProject.getFullPath(),true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
IQueryResult[] qresults = ind.getPrefix(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION);
IEntryResult[] eresults = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION);
IEntryResult[] eresultsDecls = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION);
assertTrue("Query Results exist", qresults != null); //$NON-NLS-1$
assertTrue("Entry Results exist", eresults != null); //$NON-NLS-1$
String [] queryResultModel = {"IndexedFile(1: /IndexerTestProject/mail.cpp)"}; //$NON-NLS-1$
String [] entryResultModel ={"EntryResult: word=typeDefn/C/Mail, refs={ 1 }, offsets={ [ 294] }", //$NON-NLS-1$
"EntryResult: word=typeDefn/C/Unknown, refs={ 1 }, offsets={ [ 2738] }", //$NON-NLS-1$
"EntryResult: word=typeDefn/C/container, refs={ 1 }, offsets={ [ 21084] }", //$NON-NLS-1$
"EntryResult: word=typeDefn/C/first_class, refs={ 1 }, offsets={ [ 2506] }", //$NON-NLS-1$
"EntryResult: word=typeDefn/C/postcard, refs={ 1 }, offsets={ [ 2298] }", //$NON-NLS-1$
};
String [] entryResultDeclsModel = {
"EntryResult: word=typeDecl/D/Mail, refs={ 1 }, offsets={ [ 294] }", //$NON-NLS-1$
"EntryResult: word=typeDecl/D/first_class, refs={ 1 }, offsets={ [ 2506] }", //$NON-NLS-1$
"EntryResult: word=typeDecl/D/postcard, refs={ 1 }, offsets={ [ 2298] }", //$NON-NLS-1$
};
String[] entryResultNameModel = {"Mail","Unknown","container","first_class","postcard"};
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultTypeModel = {IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS};
int[] entryResultRefModel = {IIndex.DEFINITION};
if (qresults.length != queryResultModel.length)
fail("Query Result length different from model"); //$NON-NLS-1$
if (eresults.length != entryResultModel.length)
fail("Entry Result length different from model"); //$NON-NLS-1$
if (eresultsDecls.length != entryResultDeclsModel.length)
fail("Entry Result length different from model"); //$NON-NLS-1$
for (int i=0; i<qresults.length;i++)
{
assertEquals(queryResultModel[i],qresults[i].toString());
}
for (int i=0;i<eresults.length; i++)
{
assertEquals(entryResultNameModel[i],eresults[i].getName());
assertEquals(entryResultMetaModel[0],eresults[i].getMetaKind());
assertEquals(entryResultTypeModel[i],eresults[i].getKind());
assertEquals(entryResultRefModel[0],eresults[i].getRefKind());
}
}
public void testAddNewFileToIndex() throws Exception{
//Add a file to the project
importFile("mail.cpp","resources/indexer/mail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
//Add a new file to the project, give it some time to index
importFile("DocumentManager.h","resources/indexer/DocumentManager.h"); //$NON-NLS-1$ //$NON-NLS-2$
importFile("DocumentManager.cpp","resources/indexer/DocumentManager.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
ind = sourceIndexer.getIndex(testProjectPath,true,true);
String name = "CDocumentManager"; //$NON-NLS-1$
String[] entryResultNameModel = {"CDocumentManager"};
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultTypeModel = {IIndex.TYPE_CLASS};
int[] entryResultRefModel = {IIndex.DEFINITION};
IEntryResult[] eresults =ind.getEntries(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DEFINITION, name);
IEntryResult[] bogRe = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION);
assertTrue("Entry Result exists", eresults != null); //$NON-NLS-1$
if (eresults.length != entryResultNameModel.length)
fail("Entry Result length different from model"); //$NON-NLS-1$
for (int i=0;i<eresults.length; i++)
{
assertEquals(entryResultNameModel[i],eresults[i].getName());
assertEquals(entryResultMetaModel[i],eresults[i].getMetaKind());
assertEquals(entryResultTypeModel[i],eresults[i].getKind());
assertEquals(entryResultRefModel[i],eresults[i].getRefKind());
}
}
public void testRemoveProjectFromIndex() throws Exception{
//Add a file to the project
importFile("mail.cpp","resources/indexer/mail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
//Delete the project
safeDelete(testProject);
//See if the index is still there
ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index deleted",ind == null); //$NON-NLS-1$
}
/**
* @param testProject
*/
private void safeDelete(IProject testProject) throws InterruptedException, CoreException {
System.gc();
System.runFinalization();
try {
testProject.delete(true, monitor);
} catch (CoreException e) {
Thread.sleep(5000);
testProject.delete(true, monitor);
}
}
public void testRemoveFileFromIndex() throws Exception{
//Add a file to the project
importFile("mail.cpp","resources/indexer/mail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
importFile("DocumentManager.h","resources/indexer/DocumentManager.h"); //$NON-NLS-1$ //$NON-NLS-2$
importFile("DocumentManager.cpp","resources/indexer/DocumentManager.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
ind = sourceIndexer.getIndex(testProjectPath,true,true);
//Do a "before" deletion comparison
//ind = indexManager.getIndex(testProjectPath,true,true);
IEntryResult[] eresults = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION);
IEntryResult[] eresultsDecls = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION);
assertTrue("Entry result found for typdeDefn/", eresults != null); //$NON-NLS-1$
String [] entryResultBeforeModel ={"EntryResult: word=typeDecl/C/CDocumentManager, refs={ 2 }, offsets={ [ 2127] }",
"EntryResult: word=typeDecl/C/Mail, refs={ 3 }, offsets={ [ 294] }",
"EntryResult: word=typeDecl/C/Unknown, refs={ 3 }, offsets={ [ 2738] }",
"EntryResult: word=typeDecl/C/container, refs={ 3 }, offsets={ [ 21084] }",
"EntryResult: word=typeDecl/C/first_class, refs={ 3 }, offsets={ [ 2506] }",
"EntryResult: word=typeDecl/C/postcard, refs={ 3 }, offsets={ [ 2298] }",
"EntryResult: word=typeDecl/D/Mail, refs={ 3 }, offsets={ [ 294] }",
"EntryResult: word=typeDecl/D/first_class, refs={ 3 }, offsets={ [ 2506] }",
"EntryResult: word=typeDecl/D/postcard, refs={ 3 }, offsets={ [ 2298] }",
"EntryResult: word=typeDecl/V/PO_Box, refs={ 3 }, offsets={ [ 21371] }",
"EntryResult: word=typeDecl/V/index, refs={ 3 }, offsets={ [ 21303, 21846] }",
"EntryResult: word=typeDecl/V/mail, refs={ 3 }, offsets={ [ 21336, 21912] }",
"EntryResult: word=typeDecl/V/size, refs={ 3 }, offsets={ [ 21927] }",
"EntryResult: word=typeDecl/V/temp, refs={ 3 }, offsets={ [ 21964] }",
"EntryResult: word=typeDecl/V/x, refs={ 3 }, offsets={ [ 21201, 21526] }"};
String[] entryResultNameModel = {"CDocumentManager","Mail","Unknown","container","first_class","postcard","PO_Box", "size","temp","x"};
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultTypeModel = {IIndex.TYPE_CLASS, IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS, IIndex.TYPE, IIndex.TYPE, IIndex.VAR, IIndex.VAR};
int[] entryResultRefModel = {IIndex.DEFINITION};
if (eresults.length != entryResultNameModel.length)
fail("Entry Result length different from model"); //$NON-NLS-1$
for (int i=0;i<eresults.length; i++)
{
assertEquals(entryResultNameModel[i],eresults[i].getName());
assertEquals(entryResultMetaModel[0],eresults[i].getMetaKind());
assertEquals(entryResultTypeModel[i],eresults[i].getKind());
assertEquals(entryResultRefModel[0],eresults[i].getRefKind());
}
//Delete mail.cpp from the project, give some time to remove index
IResource resourceHdl = testProject.findMember("mail.cpp") ; //$NON-NLS-1$
// Cleaning up file handles before delete
System.gc();
System.runFinalization();
resetIndexState();
resourceHdl.delete(true,monitor);
waitForIndex(10); // wait up to 10 seconds for the index to be deleted.
//See if the index is still there
ind = sourceIndexer.getIndex(testProjectPath,true,true);
eresults = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION);
assertTrue("Entry exists", eresults != null); //$NON-NLS-1$
String [] entryResultAfterModel ={"EntryResult: word=typeDecl/C/CDocumentManager, refs={ 2 }, offsets={ [ 2127] }"}; //$NON-NLS-1$ //$NON-NLS-2$
String[] entryResultANameModel = {"CDocumentManager"};
int[] entryResultAMetaModel = {IIndex.TYPE};
int[] entryResultATypeModel = {IIndex.TYPE_CLASS};
int[] entryResultARefModel = {IIndex.DEFINITION};
if (eresults.length != entryResultANameModel.length)
fail("Entry Result length different from model"); //$NON-NLS-1$
for (int i=0;i<eresults.length; i++)
{
assertEquals(entryResultANameModel[i],eresults[i].getName());
assertEquals(entryResultAMetaModel[0],eresults[i].getMetaKind());
assertEquals(entryResultATypeModel[0],eresults[i].getKind());
assertEquals(entryResultARefModel[0],eresults[i].getRefKind());
}
}
public void testIndexContents() throws Exception{
//Add a new file to the project
importFile("extramail.cpp","resources/indexer/extramail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$ //$NON-NLS-2$
IEntryResult[] typerefreesults = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.REFERENCE);
assertTrue("Type Ref Results exist", typerefreesults != null); //$NON-NLS-1$
String[] entryResultDeclNameModel = {"Mail/Y/X/Z","first_class/Y/X/Z", "postcard/Y/X/Z", "test/Y/X/Z", "int32", "index", "mail",};
String[] entryResultDefnNameModel = {"Mail/Y/X/Z", "Unknown/Y/X/Z", "container/Y/X/Z", "first_class/Y/X/Z", "postcard/Y/X/Z", "PO_Box", "size", "temp", "x", "x/Z" };
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultDefnTypeModel = {IIndex.TYPE_CLASS, IIndex.TYPE_CLASS, IIndex.TYPE_CLASS, IIndex.TYPE_CLASS, IIndex.TYPE_CLASS,
IIndex.VAR,IIndex.VAR,IIndex.VAR,IIndex.VAR,IIndex.VAR};
int[] entryResultDeclTypeModel = {IIndex.TYPE_DERIVED, IIndex.TYPE_DERIVED, IIndex.TYPE_DERIVED, IIndex.TYPE_ENUM, IIndex.TYPE_TYPEDEF,IIndex.VAR,IIndex.VAR};
IEntryResult[] typedeclresults =ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION);
IEntryResult[] typedefinitionsresults = ind.getEntries(IIndex.TYPE, IIndex.ANY , IIndex.DEFINITION);
assertTrue("Type Decl Results exist", typedeclresults != null); //$NON-NLS-1$
if (typedefinitionsresults.length != entryResultDefnNameModel.length)
fail("Entry Result length different from model for typeDefn"); //$NON-NLS-1$
for (int i=0;i<typedeclresults.length; i++)
{
assertEquals(entryResultDefnNameModel[i],typedefinitionsresults[i].getName());
assertEquals(entryResultMetaModel[0],typedefinitionsresults[i].getMetaKind());
assertEquals(entryResultDefnTypeModel[i],typedefinitionsresults[i].getKind());
assertEquals(IIndex.DEFINITION,typedefinitionsresults[i].getRefKind());
}
String[] entryResultTNameModel = {"int32" };
int[] entryResultTMetaModel = {IIndex.TYPE};
int[] entryResultTTypeModel = {IIndex.TYPE_TYPEDEF};
int[] entryResultTRefModel = {IIndex.DECLARATION};
IEntryResult[] typedefresults =ind.getEntries(IIndex.TYPE, IIndex.TYPE_TYPEDEF, IIndex.DECLARATION);
assertTrue("Type Def Results exist", typedefresults != null); //$NON-NLS-1$
if (typedefresults.length != entryResultTNameModel.length)
fail("Entry Result length different from model for typeDef"); //$NON-NLS-1$
for (int i=0;i<typedefresults.length; i++)
{
assertEquals(entryResultTNameModel[i],typedefresults[i].getName());
assertEquals(entryResultTMetaModel[i],typedefresults[i].getMetaKind());
assertEquals(entryResultTTypeModel[i],typedefresults[i].getKind());
assertEquals(entryResultTRefModel[i],typedefresults[i].getRefKind());
}
String[] entryResultNNameModel = {"X/Z", "Y/X/Z" , "Z" };
int[] entryResultNMetaModel = {IIndex.NAMESPACE};
int[] entryResultNRefModel = {IIndex.DEFINITION};
IEntryResult[] namespaceresults =ind.getEntries(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION);
assertTrue("Namespace Results exist", namespaceresults != null); //$NON-NLS-1$
if (namespaceresults.length != entryResultNNameModel.length)
fail("Entry Result length different from model for namespace"); //$NON-NLS-1$
for (int i=0;i<namespaceresults.length; i++)
{
assertEquals(entryResultNNameModel[i],namespaceresults[i].getName());
assertEquals(entryResultNMetaModel[0],namespaceresults[i].getMetaKind());
assertEquals(entryResultNRefModel[0],namespaceresults[i].getRefKind());
}
String[] entryResultFNameModel = {"array/container/Y/X/Z", "index/container/Y/X/Z" , "postage/Mail/Y/X/Z","sz/container/Y/X/Z", "type/Mail/Y/X/Z"};
int[] entryResultFMetaModel = {IIndex.FIELD};
int[] entryResultFRefModel = {IIndex.DEFINITION};
IEntryResult[] fieldresults =ind.getEntries(IIndex.FIELD, IIndex.ANY, IIndex.DEFINITION);
assertTrue("Field Results exist", fieldresults != null); //$NON-NLS-1$
if (fieldresults.length != entryResultFNameModel.length)
fail("Entry Result length different from model for fieldDecl"); //$NON-NLS-1$
for (int i=0;i<fieldresults.length; i++)
{
assertEquals(entryResultFNameModel[i],fieldresults[i].getName());
assertEquals(entryResultFMetaModel[0],fieldresults[i].getMetaKind());
assertEquals(entryResultFRefModel[0],fieldresults[i].getRefKind());
}
String[] entryResultENameModel = {"bye/Y/X/Z", "cool/Y/X/Z" , "hi/Y/X/Z", "why/Y/X/Z"};
int[] entryResultEMetaModel = {IIndex.ENUMTOR};
int[] entryResultERefModel = {IIndex.DECLARATION};
IEntryResult[] enumeratorresults =ind.getEntries(IIndex.ENUMTOR, IIndex.ANY, IIndex.DECLARATION);
assertTrue("Enumerator Results exist", enumeratorresults != null); //$NON-NLS-1$
if (enumeratorresults.length != entryResultENameModel.length)
fail("Entry Result length different from model for enumtorDecl"); //$NON-NLS-1$
for (int i=0;i<enumeratorresults.length; i++)
{
assertEquals(entryResultENameModel[i],enumeratorresults[i].getName());
assertEquals(entryResultEMetaModel[0],enumeratorresults[i].getMetaKind());
assertEquals(entryResultERefModel[0],enumeratorresults[i].getRefKind());
}
String[] entryResultFNNameModel = {"doSomething"};
int[] entryResultFNMetaModel = {IIndex.FUNCTION};
int[] entryResultFNRefModel = {IIndex.DECLARATION};
IEntryResult[] functionresults =ind.getEntries(IIndex.FUNCTION, IIndex.ANY, IIndex.DECLARATION);
if (functionresults.length != entryResultFNNameModel.length)
fail("Entry Result length different from model for functionDecl"); //$NON-NLS-1$
for (int i=0;i<functionresults.length; i++)
{
assertEquals(entryResultFNNameModel[i],functionresults[i].getName());
assertEquals(entryResultFNMetaModel[0],functionresults[i].getMetaKind());
assertEquals(entryResultFNRefModel[0],functionresults[i].getRefKind());
}
String[] entryResultMNameDefnModel = {"Mail/Mail/Y/X/Z", "Unknown/Unknown/Y/X/Z" , "container/container/Y/X/Z", "first_class/first_class/Y/X/Z",
"print/Unknown/Y/X/Z","print/first_class/Y/X/Z", "print/postcard/Y/X/Z", "size/container/Y/X/Z", "~container/container/Y/X/Z"};
int[] entryResultMMetaDefnModel = {IIndex.METHOD};
int[] entryResultMRefDefnModel = {IIndex.DEFINITION};
String [] entryResultMNameDeclModel = {"operator =/container/Y/X/Z", "operator []/container/Y/X/Z","print/Mail/Y/X/Z"};
int[] entryResultMMetaDeclModel = {IIndex.METHOD};
int[] entryResultMRefDeclModel = {IIndex.DECLARATION};
IEntryResult[] methodresults =ind.getEntries(IIndex.METHOD, IIndex.ANY, IIndex.DECLARATION);
assertTrue("Entry exists", methodresults != null); //$NON-NLS-1$
if (methodresults.length != entryResultMNameDeclModel.length)
fail("Entry Result length different from model for functionDecl"); //$NON-NLS-1$
for (int i=0;i<methodresults.length; i++)
{
assertEquals(entryResultMNameDeclModel[i],methodresults[i].getName());
assertEquals(entryResultMMetaDeclModel[0],methodresults[i].getMetaKind());
assertEquals(entryResultMRefDeclModel[0],methodresults[i].getRefKind());
}
}
public void testRefs() throws Exception{
//Add a new file to the project
importFile("reftest.cpp","resources/indexer/reftest.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
String[] entryResultNameModel = {"C/B/A","ForwardA/A", "e1/B/A", "x/B/A"};
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultTypeModel = {IIndex.TYPE_CLASS, IIndex.TYPE_CLASS, IIndex.TYPE_ENUM, IIndex.VAR};
int[] entryResultRefModel = {IIndex.REFERENCE};
IEntryResult[] typerefresults = ind.getEntries(IIndex.TYPE,IIndex.ANY,IIndex.REFERENCE);
assertTrue("Entry exists",typerefresults != null); //$NON-NLS-1$
if (typerefresults.length != entryResultNameModel.length)
fail("Entry Result length different from model for typeRef"); //$NON-NLS-1$
for (int i=0;i<typerefresults.length; i++)
{
assertEquals(entryResultNameModel[i],typerefresults[i].getName());
assertEquals(entryResultMetaModel[0],typerefresults[i].getMetaKind());
assertEquals(entryResultTypeModel[i],typerefresults[i].getKind());
assertEquals(entryResultRefModel[0],typerefresults[i].getRefKind());
}
String[] entryResultFNameModel = {"something/A"};
int[] entryResultFMetaModel = {IIndex.FUNCTION};
int[] entryResultFRefModel = {IIndex.REFERENCE};
IEntryResult[] funRefresults = ind.getEntries(IIndex.FUNCTION,IIndex.ANY, IIndex.REFERENCE);
assertTrue("Entry exists",funRefresults != null); //$NON-NLS-1$
if (funRefresults.length != entryResultFNameModel.length)
fail("Entry Result length different from model for funcRef"); //$NON-NLS-1$
for (int i=0;i<funRefresults.length; i++)
{
assertEquals(entryResultFNameModel[i],funRefresults[i].getName());
assertEquals(entryResultFMetaModel[0],funRefresults[i].getMetaKind());
assertEquals(entryResultFRefModel[0],funRefresults[i].getRefKind());
}
String [] namespaceRefResultModel = {"EntryResult: word=namespaceRef/A, refs={ 1 }, offsets={ [ 2228, 2241, 2257, 2273, 2292, 2313, 2334] }",
"EntryResult: word=namespaceRef/B/A, refs={ 1 }, offsets={ [ 2231, 2244, 2260, 2276, 2295, 2337] }"}; //$NON-NLS-1$ //$NON-NLS-2$
String[] entryResultNNameModel = {"A", "B/A"};
int[] entryResultNMetaModel = {IIndex.NAMESPACE};
int[] entryResultNRefModel = {IIndex.REFERENCE};
IEntryResult[] namespacerefresults = ind.getEntries(IIndex.NAMESPACE, IIndex.ANY, IIndex.REFERENCE);
assertTrue("Entry exists",namespacerefresults!=null); //$NON-NLS-1$
if (namespacerefresults.length != entryResultNNameModel.length)
fail("Entry Result length different from model for namespaceRef"); //$NON-NLS-1$
for (int i=0;i<namespacerefresults.length; i++)
{
assertEquals(entryResultNNameModel[i],namespacerefresults[i].getName());
assertEquals(entryResultNMetaModel[0],namespacerefresults[i].getMetaKind());
assertEquals(entryResultNRefModel[0],namespacerefresults[i].getRefKind());
}
String[] entryResultFDNameModel = {"y/C/B/A"};
int[] entryResultFDMetaModel = {IIndex.FIELD};
int[] entryResultFDRefModel = {IIndex.REFERENCE};
IEntryResult[] fieldrefresults = ind.getEntries(IIndex.FIELD, IIndex.ANY, IIndex.REFERENCE);
assertTrue("Entry exists",fieldrefresults!=null); //$NON-NLS-1$
if (fieldrefresults.length != entryResultFDNameModel.length)
fail("Entry Result length different from model for fieldRef"); //$NON-NLS-1$
for (int i=0;i<fieldrefresults.length; i++)
{
assertEquals(entryResultFDNameModel[i],fieldrefresults[i].getName());
assertEquals(entryResultFDMetaModel[0],fieldrefresults[i].getMetaKind());
assertEquals(entryResultFDRefModel[0],fieldrefresults[i].getRefKind());
}
String[] entryResultMNameModel = {"bar/C/B/A"};
int[] entryResultMMetaModel = {IIndex.METHOD};
int[] entryResultMRefModel = {IIndex.REFERENCE};
IEntryResult[] methodrefresults = ind.getEntries(IIndex.METHOD, IIndex.ANY, IIndex.REFERENCE);
assertTrue("Entry exists", methodrefresults != null); //$NON-NLS-1$
if (methodrefresults.length != entryResultMNameModel.length)
fail("Entry Result length different from model for methodRef");//$NON-NLS-1$
for (int i=0;i<methodrefresults.length; i++)
{
assertEquals(entryResultMNameModel[i],methodrefresults[i].getName());
assertEquals(entryResultMMetaModel[0],methodrefresults[i].getMetaKind());
assertEquals(entryResultMRefModel[0],methodrefresults[i].getRefKind());
}
}
public void testExactDeclarations() throws Exception
{
importFile("a.h","resources/dependency/a.h");//$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
importFile("DepTest3.h","resources/dependency/DepTest3.h");//$NON-NLS-1$ //$NON-NLS-2$
importFile("DepTest3.cpp","resources/dependency/DepTest3.cpp");//$NON-NLS-1$ //$NON-NLS-2$
IEntryResult[] eResult = ind.getEntries(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DEFINITION);
IQueryResult[] qResult = ind.getPrefix(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DEFINITION);
assertTrue("Expected 2 files indexed", qResult.length == 2); //$NON-NLS-1$
assertTrue("Checking DepTest3.h location", qResult[0].getPath().equals("/IndexerTestProject/DepTest3.h")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Checking a.h location", qResult[1].getPath().equals("/IndexerTestProject/a.h")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Expect 2 class declaration entries", eResult.length == 2); //$NON-NLS-1$
int[] DepTest3FileRefs = {2};
int[] fileRefs = eResult[0].getFileReferences();
assertTrue("Check DepTest3 File Refs number", fileRefs.length == 1); //$NON-NLS-1$
for (int i=0; i<fileRefs.length; i++){
assertTrue("Verify DepTest3 File Ref",fileRefs[i] == DepTest3FileRefs[i]); //$NON-NLS-1$
}
int[] aFileRefs = {3};
fileRefs = eResult[1].getFileReferences();
assertTrue("Check a.h File Refs number", fileRefs.length == 1); //$NON-NLS-1$
for (int i=0; i<fileRefs.length; i++){
assertTrue("Verify a.h File Ref",fileRefs[i] == aFileRefs[i]); //$NON-NLS-1$
}
}
public void testMD5() throws Exception
{
importFile("extramail.cpp","resources/indexer/extramail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//importFile("mail.cpp","resources/indexer/mail.cpp");
MessageDigest md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
//MessageDigest md = MessageDigest.getInstance("SHA");
String fileName = testProject.getFile("extramail.cpp").getLocation().toOSString(); //$NON-NLS-1$
//String fileName = testProject.getFile("mail.cpp").getLocation().toOSString();
long startTime = System.currentTimeMillis();
FileInputStream stream = new FileInputStream(fileName);
FileChannel channel = stream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int)channel.size());
channel.read(byteBuffer);
byteBuffer.rewind();
md.update(byteBuffer.array());
byte[] messageDigest = md.digest();
//System.out.println("Elapsed Time: " + (System.currentTimeMillis() - startTime) + " ms");
}
public void testMacros() throws Exception
{
//Add a new file to the project
importFile("extramail.cpp","resources/indexer/extramail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
IEntryResult[] macroresults = ind.getEntries(IIndex.MACRO, IIndex.ANY, IIndex.DECLARATION);
assertTrue("Entry exists", macroresults != null); //$NON-NLS-1$
String[] entryResultNameModel = {"CASE", "MAX", "PRINT"};
int[] entryResultMetaModel = {IIndex.MACRO};
int[] entryResultRefModel = {IIndex.DECLARATION};
if (macroresults.length != entryResultNameModel.length)
fail("Entry Result length different from model for macros"); //$NON-NLS-1$
for (int i=0;i<macroresults.length; i++)
{
assertEquals(entryResultNameModel[i],macroresults[i].getName());
assertEquals(entryResultMetaModel[0],macroresults[i].getMetaKind());
assertEquals(entryResultRefModel[0],macroresults[i].getRefKind());
}
}
public void testIndexShutdown() throws Exception{
//Add a new file to the project
importFile("reftest.cpp","resources/indexer/reftest.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
//Create an empty index file
String badIndexFile = CCorePlugin.getDefault().getStateLocation().append("badIndex.index").toOSString(); //$NON-NLS-1$
FileWriter writer = null;
try {
writer = new FileWriter(badIndexFile);
writer.flush();
writer.close();
}
catch (IOException e){}
File indexesDirectory = new File(CCorePlugin.getDefault().getStateLocation().toOSString());
//This should get rid of the empty index file from the metadata and
//remove the index from the indexes (since its .index file is missing)
indexManager.shutdown();
File[] indexesFiles = indexesDirectory.listFiles();
if (indexesFiles != null) {
for (int i = 0, indexesFilesLength = indexesFiles.length; i < indexesFilesLength; i++) {
if(indexesFiles[i].getName().equals("badIndex.index")){ //$NON-NLS-1$
fail("Shutdown did not delete .index file"); //$NON-NLS-1$
}
}
}
}
public void testForwardDeclarations() throws Exception{
//Add a new file to the project
importFile("reftest.cpp","resources/indexer/reftest.cpp"); //$NON-NLS-1$ //$NON-NLS-2$
//Make sure project got added to index
IPath testProjectPath = testProject.getFullPath();
IIndex ind = sourceIndexer.getIndex(testProjectPath,true,true);
assertTrue("Index exists for project",ind != null); //$NON-NLS-1$
IEntryResult[] fwdDclResults = ind.getEntries(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DECLARATION, "ForwardA/A" ); //$NON-NLS-1$
assertTrue("Entry exists",fwdDclResults != null); //$NON-NLS-1$
String [] fwdDclModel = {"EntryResult: word=typeDecl/G/ForwardA/A, refs={ 1 }, offsets={ [ 225] }"}; //$NON-NLS-1$
String[] entryResultNameModel = {"ForwardA/A"};
int[] entryResultMetaModel = {IIndex.TYPE};
int[] entryResultTypeModel = {IIndex.TYPE_CLASS};
int[] entryResultRefModel = {IIndex.DECLARATION};
if (fwdDclResults.length != fwdDclModel.length)
fail("Entry Result length different from model for forward declarations"); //$NON-NLS-1$
for (int i=0;i<fwdDclResults.length; i++)
{
assertEquals(entryResultNameModel[i],fwdDclResults[i].getName());
assertEquals(entryResultMetaModel[i],fwdDclResults[i].getMetaKind());
assertEquals(entryResultTypeModel[i],fwdDclResults[i].getKind());
assertEquals(entryResultRefModel[i],fwdDclResults[i].getRefKind());
}
IEntryResult[] fwdDclRefResults = ind.getEntries(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.REFERENCE, "ForwardA/A"); //$NON-NLS-1$
assertTrue("Entry exists", fwdDclRefResults!= null); //$NON-NLS-1$
String [] fwdDclRefModel = {"EntryResult: word=typeRef/G/ForwardA/A, refs={ 1 }, offsets={ [ 237] }"}; //$NON-NLS-1$
String[] entryResultName2Model = {"ForwardA/A"};
int[] entryResultMeta2Model = {IIndex.TYPE};
int[] entryResultType2Model = {IIndex.TYPE_CLASS};
int[] entryResultRef2Model = {IIndex.REFERENCE};
if (fwdDclRefResults.length != fwdDclRefModel.length)
fail("Entry Result length different from model for forward declarations refs"); //$NON-NLS-1$
for (int i=0;i<fwdDclRefResults.length; i++)
{
assertEquals(entryResultName2Model[i],fwdDclRefResults[i].getName());
assertEquals(entryResultMeta2Model[i],fwdDclRefResults[i].getMetaKind());
assertEquals(entryResultType2Model[i],fwdDclRefResults[i].getKind());
assertEquals(entryResultRef2Model[i],fwdDclRefResults[i].getRefKind());
}
}
public void indexChanged(IndexChangeEvent event) {
IIndexDelta delta = event.getDelta();
if (delta.getDeltaType() == IIndexDelta.MERGE_DELTA){
fileIndexed = true;
}
}
}

View file

@ -1,790 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on Sep 25, 2003
*/
package org.eclipse.cdt.core.indexer.tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorOperation;
import org.eclipse.cdt.core.index.IIndexChangeListener;
import org.eclipse.cdt.core.index.IIndexDelta;
import org.eclipse.cdt.core.index.IndexChangeEvent;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.search.BasicSearchResultCollector;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.ICSearchResultCollector;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.IMatch;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.core.tests.FailingTest;
import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexerRunner;
import org.eclipse.cdt.internal.core.search.PathCollector;
import org.eclipse.cdt.internal.core.search.PatternSearchJob;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.matching.CSearchPattern;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.cdt.internal.core.sourcedependency.DependencyQueryJob;
import org.eclipse.cdt.internal.core.sourcedependency.UpdateDependency;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
/**
* @author bgheorgh
*/
public class DependencyTests extends TestCase implements IIndexChangeListener {
IFile file;
IProject testProject;
NullProgressMonitor monitor;
IndexManager indexManager;
IWorkspace workspace;
BasicSearchResultCollector resultCollector;
SearchEngine searchEngine;
ICSearchScope scope;
DOMSourceIndexer sourceIndexer;
boolean fileIndexed;
public static final int TIMEOUT = 50;
public static Test suite() {
TestSuite suite = new TestSuite(DependencyTests.class.getName());
suite.addTest(new DependencyTests("testDependencyTree"));
//suite.addTest(new DependencyTests("testDepTable"));
suite.addTest(new DependencyTests("testDepSourceChangeTree"));
suite.addTest(new DependencyTests("testDepHeaderChangeTree"));
suite.addTest(new DependencyTests("testDepHeaderChangeReindex"));
suite.addTest(new DependencyTests("testDepSourceChangeTable"));
suite.addTest(new DependencyTests("testDepHeaderChangeTable"));
suite.addTest(new DependencyTests("testUpdateDependancyNPE"));
return suite;
}
/**
* @param name
*/
public DependencyTests(String name) {
super(name);
// TODO Auto-generated constructor stub
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
//Create temp project
testProject = createProject("DepTestProject");
IPath pathLoc = CCorePlugin.getDefault().getStateLocation();
File indexFile = new File(pathLoc.append("281274758.index").toOSString());
if (indexFile.exists())
indexFile.delete();
if (testProject==null)
fail("Unable to create project");
resetIndexer(DOMSourceIndexer.ID);
//The DOM Source Indexer checks to see if a file has any scanner info
//set prior to indexing it in order to increase efficiency. We need to let it know
//that it is running in test mode in order to allow for this scanner info test to be skipped
DOMSourceIndexerRunner.setSkipScannerInfoTest(true);
TypeCacheManager typeCacheManager = TypeCacheManager.getInstance();
typeCacheManager.setProcessTypeCacheEvents(false);
workspace = ResourcesPlugin.getWorkspace();
scope = SearchEngine.createWorkspaceScope();
monitor = new NullProgressMonitor();
resultCollector = new BasicSearchResultCollector();
searchEngine = new SearchEngine();
indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(testProject);
sourceIndexer.addIndexChangeListener(this);
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() {
try {
super.tearDown();
} catch (Exception e1) {
}
sourceIndexer.shutdown();
//Delete project
if (testProject.exists()){
try {
System.gc();
System.runFinalization();
testProject.delete(true,monitor);
} catch (CoreException e) {
fail(getMessage(e.getStatus()));
}
}
}
private String getMessage(IStatus status) {
StringBuffer message = new StringBuffer("[");
message.append(status.getMessage());
if (status.isMultiStatus()) {
IStatus children[] = status.getChildren();
for (int i = 0; i < children.length; i++) {
message.append(getMessage(children[i]));
}
}
message.append("]");
return message.toString();
}
public void testDependencyTree() throws Exception{
//Add a file to the project
importFile("c.h","resources/dependency/c.h");
importFile("a.h","resources/dependency/a.h");
importFile("Inc1.h","resources/dependency/Inc1.h");
importFile("DepTest.h","resources/dependency/DepTest.h");
importFile("d.h","resources/dependency/d.h");
importFile("DepTest2.h","resources/dependency/DepTest2.h");
IFile depTest = importFile("DepTest.cpp","resources/dependency/DepTest.cpp");
IFile depTest2 = importFile("DepTest2.cpp","resources/dependency/DepTest2.cpp");
String[] depTestModel = {File.separator + "DepTestProject" + File.separator + "d.h", File.separator + "DepTestProject" + File.separator + "Inc1.h", File.separator + "DepTestProject" + File.separator + "c.h", File.separator + "DepTestProject" + File.separator + "a.h", File.separator + "DepTestProject" + File.separator + "DepTest.h"};
String[] depTest2Model = {File.separator + "DepTestProject" + File.separator + "d.h", File.separator + "DepTestProject" + File.separator + "DepTest2.h"};
ArrayList includes = new ArrayList();
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTest,sourceIndexer,includes),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null,null);
String[] depTestModelLocal = convertToLocalPath(depTestModel);
String[] depTestIncludes = new String[includes.size()];
Iterator includesIterator = includes.iterator();
int i=0;
while(includesIterator.hasNext()){
depTestIncludes[i] = (String) includesIterator.next();
i++;
}
if (depTestModelLocal.length != depTestIncludes.length)
fail("Number of included files differsfrom model");
Arrays.sort(depTestModelLocal);
Arrays.sort(depTestIncludes);
for (i=0;i<depTestIncludes.length; i++)
{
assertEquals(depTestModelLocal[i],depTestIncludes[i]);
}
ArrayList includes2 = new ArrayList();
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTest2,sourceIndexer,includes2),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null,null);
String[] depTest2ModelLocal = convertToLocalPath(depTest2Model);
String[] depTest2Includes = new String[includes2.size()];
Iterator includes2Iterator = includes2.iterator();
i=0;
while(includes2Iterator.hasNext()){
depTest2Includes[i] = (String) includes2Iterator.next();
i++;
}
if (depTest2ModelLocal.length != depTest2Includes.length)
fail("Number of included files differsfrom model");
Arrays.sort(depTest2ModelLocal);
Arrays.sort(depTest2Includes);
for (i=0;i<depTest2Includes.length; i++)
{
assertEquals(depTest2ModelLocal[i],depTest2Includes[i]);
}
}
public void testDepTable() throws Exception{
//Add a file to the project
IFile depTest2C = importFile("DepTest2.cpp","resources/dependency/DepTest2.cpp");
IFile depTestC = importFile("DepTest.cpp","resources/dependency/DepTest.cpp");
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile Inc1H = importFile("Inc1.h","resources/dependency/Inc1.h");
IFile dH = importFile("d.h","resources/dependency/d.h");
IFile depTestH = importFile("DepTest.h","resources/dependency/DepTest.h");
IFile depTest2H = importFile("DepTest2.h","resources/dependency/DepTest2.h");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
PathCollector pathCollector = new PathCollector();
getTableRefs(dH, pathCollector);
String[] dHModel = {IPath.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest2.cpp", IPath.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest.cpp"};
String[] iPath = pathCollector.getPaths();
if (dHModel.length != iPath.length)
fail("Number of included files differsfrom model");
Arrays.sort(dHModel);
Arrays.sort(iPath);
for (int i=0;i<iPath.length; i++)
{
assertEquals(iPath[i],dHModel[i]);
}
pathCollector = new PathCollector();
getTableRefs(Inc1H, pathCollector);
String[] Inc1HModel = {IPath.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest.cpp"};
iPath = pathCollector.getPaths();
if (Inc1HModel.length != iPath.length)
fail("Number of included files differsfrom model");
Arrays.sort(Inc1HModel);
Arrays.sort(iPath);
for (int i=0;i<iPath.length; i++)
{
assertEquals(iPath[i],Inc1HModel[i]);
}
}
public void testDepSourceChangeTable() throws Exception{
//Add a file to the project
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile Inc1H = importFile("Inc1.h","resources/dependency/Inc1.h");
IFile dH = importFile("d.h","resources/dependency/d.h");
IFile depTestH = importFile("DepTest.h","resources/dependency/DepTest.h");
IFile depTestC = importFile("DepTest.cpp","resources/dependency/DepTest.cpp");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
String[] beforeModel = {Path.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest.cpp"};
PathCollector pathCollector = new PathCollector();
getTableRefs(depTestH, pathCollector);
String[] iPath = pathCollector.getPaths();
compareArrays(iPath,beforeModel);
pathCollector = new PathCollector();
getTableRefs(dH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,beforeModel);
pathCollector = new PathCollector();
getTableRefs(Inc1H, pathCollector);
iPath = pathCollector.getPaths();
String[] inc1Model = {Path.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest.cpp"};
compareArrays(iPath,inc1Model);
pathCollector = new PathCollector();
getTableRefs(aH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,inc1Model);
pathCollector = new PathCollector();
getTableRefs(cH, pathCollector);
iPath = pathCollector.getPaths();
String[] cHModel = {Path.SEPARATOR + "DepTestProject" + Path.SEPARATOR + "DepTest.cpp"};
compareArrays(iPath,cHModel);
editCode(depTestC,"#include \"DepTest.h\"","//#include \"DepTest.h\"");
pathCollector = new PathCollector();
getTableRefs(depTestH, pathCollector);
iPath = pathCollector.getPaths();
if (iPath.length != 0)
fail("Number of included files differs from model");
pathCollector = new PathCollector();
getTableRefs(dH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,beforeModel);
pathCollector = new PathCollector();
getTableRefs(Inc1H, pathCollector);
iPath = pathCollector.getPaths();
if (iPath.length != 0)
fail("Number of included files differs from model");
pathCollector = new PathCollector();
getTableRefs(aH, pathCollector);
iPath = pathCollector.getPaths();
if (iPath.length != 0)
fail("Number of included files differs from model");
pathCollector = new PathCollector();
getTableRefs(cH, pathCollector);
iPath = pathCollector.getPaths();
if (iPath.length != 0)
fail("Number of included files differs from model");
}
public void testDepSourceChangeTree() throws Exception{
// Add a file to the project
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile Inc1H = importFile("Inc1.h","resources/dependency/Inc1.h");
IFile depTestH = importFile("DepTest.h","resources/dependency/DepTest.h");
IFile dH = importFile("d.h","resources/dependency/d.h");
IFile depTest2H = importFile("DepTest2.h","resources/dependency/DepTest2.h");
IFile depTestC = importFile("DepTest.cpp","resources/dependency/DepTest.cpp");
IFile depTest2C = importFile("DepTest2.cpp","resources/dependency/DepTest2.cpp");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
String[] preDepTestModel = {File.separator + "DepTestProject" + File.separator + "DepTest.h", File.separator + "DepTestProject" + File.separator + "Inc1.h", File.separator + "DepTestProject" + File.separator + "a.h", File.separator + "DepTestProject" + File.separator + "c.h", File.separator + "DepTestProject" + File.separator + "d.h"};
ArrayList includes = new ArrayList();
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTestC,sourceIndexer,includes),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null, null);
String[] preDepTestModelLocal = convertToLocalPath(preDepTestModel);
String[] preDepTestIncludes = new String[includes.size()];
Iterator includesIterator = includes.iterator();
int i=0;
while(includesIterator.hasNext()){
preDepTestIncludes[i] = (String) includesIterator.next();
i++;
}
if (preDepTestModelLocal.length != preDepTestIncludes.length)
fail("Number of included files differs from model");
Arrays.sort(preDepTestModelLocal);
Arrays.sort(preDepTestIncludes);
for (i=0;i<preDepTestIncludes.length; i++){
assertEquals(preDepTestModelLocal[i],preDepTestIncludes[i]);
}
editCode(depTestC,"#include \"DepTest.h\"","//#include \"DepTest.h\"");
String[] postDepTestModel = {File.separator + "DepTestProject" + File.separator + "d.h"};
ArrayList includes2 = new ArrayList();
testProject.refreshLocal(IResource.DEPTH_INFINITE,null);
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTestC,sourceIndexer,includes2),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null, null);
String[] postDepTestModelLocal = convertToLocalPath(postDepTestModel);
String[] postDepTestIncludes = new String[includes2.size()];
Iterator includesIterator2 = includes2.iterator();
int j=0;
while(includesIterator2.hasNext()){
postDepTestIncludes[j] = (String) includesIterator2.next();
j++;
}
if (postDepTestModelLocal.length != postDepTestIncludes.length)
fail("Number of included files differs from model");
Arrays.sort(postDepTestModelLocal);
Arrays.sort(postDepTestIncludes);
for (i=0;i<postDepTestIncludes.length; i++){
assertEquals(postDepTestModelLocal[i],postDepTestIncludes[i]);
}
}
public void testDepHeaderChangeTree() throws Exception{
// Add a file to the project
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile depTest3H = importFile("DepTest3.h","resources/dependency/DepTest3.h");
IFile depTest3C = importFile("DepTest3.cpp","resources/dependency/DepTest3.cpp");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
String[] preDepTestModel = {File.separator + "DepTestProject" + File.separator + "DepTest3.h", File.separator + "DepTestProject" + File.separator + "a.h", File.separator + "DepTestProject" + File.separator + "c.h"};
ArrayList includes = new ArrayList();
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTest3C,sourceIndexer,includes),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null, null);
String[] preDepTestModelLocal = convertToLocalPath(preDepTestModel);
String[] preDepTestIncludes = new String[includes.size()];
Iterator includesIterator = includes.iterator();
int i=0;
while(includesIterator.hasNext()){
preDepTestIncludes[i] = (String) includesIterator.next();
i++;
}
if (preDepTestModelLocal.length != preDepTestIncludes.length)
fail("Number of included files differs from model");
Arrays.sort(preDepTestModelLocal);
Arrays.sort(preDepTestIncludes);
for (i=0;i<preDepTestIncludes.length; i++){
assertEquals(preDepTestModelLocal[i],preDepTestIncludes[i]);
}
editCode(aH,"#include \"c.h\"","//#include \"c.h\"");
String[] postDepTestModel = {File.separator + "DepTestProject" + File.separator + "DepTest3.h", File.separator + "DepTestProject" + File.separator + "a.h"};
ArrayList includes2 = new ArrayList();
testProject.refreshLocal(IResource.DEPTH_INFINITE,null);
indexManager.performConcurrentJob(new DependencyQueryJob(testProject,depTest3C,sourceIndexer,includes2),ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,null, null);
String[] postDepTestModelLocal = convertToLocalPath(postDepTestModel);
String[] postDepTestIncludes = new String[includes2.size()];
Iterator includesIterator2 = includes2.iterator();
int j=0;
while(includesIterator2.hasNext()){
postDepTestIncludes[j] = (String) includesIterator2.next();
j++;
}
assertEquals(postDepTestModelLocal.length, postDepTestIncludes.length);
Arrays.sort(postDepTestModelLocal);
Arrays.sort(postDepTestIncludes);
for (i=0;i<postDepTestIncludes.length; i++){
assertEquals(postDepTestModelLocal[i],postDepTestIncludes[i]);
}
}
public void testDepHeaderChangeTable() throws Exception{
// Add a file to the project
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile depTest3H = importFile("DepTest3.h","resources/dependency/DepTest3.h");
IFile depTest3C = importFile("DepTest3.cpp","resources/dependency/DepTest3.cpp");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
String[] beforeModel = {Path.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest3.cpp"};
String[] cHModel = {Path.SEPARATOR + "DepTestProject" + IPath.SEPARATOR + "DepTest3.cpp"};
String[] aHModel = {Path.SEPARATOR + "DepTestProject" + Path.SEPARATOR + "DepTest3.cpp"};
PathCollector pathCollector = new PathCollector();
getTableRefs(depTest3H, pathCollector);
String[] iPath = pathCollector.getPaths();
compareArrays(iPath,beforeModel);
pathCollector = new PathCollector();
getTableRefs(cH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,cHModel);
pathCollector = new PathCollector();
getTableRefs(aH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,aHModel);
editCode(aH,"#include \"c.h\"","//#include \"c.h\"");
pathCollector = new PathCollector();
getTableRefs(depTest3H, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,beforeModel);
pathCollector = new PathCollector();
getTableRefs(cH, pathCollector);
iPath = pathCollector.getPaths();
if (iPath.length != 0)
fail("Number of included files differs from model");
pathCollector = new PathCollector();
getTableRefs(aH, pathCollector);
iPath = pathCollector.getPaths();
compareArrays(iPath,aHModel);
}
public void testUpdateDependancyNPE() {
IResource nonExistantResource = ResourcesPlugin.getWorkspace().getRoot().getProject("non-existant-project-aha");
assertFalse(nonExistantResource.exists());
assertNull(nonExistantResource.getLocation());
IIndexJob job = new UpdateDependency(nonExistantResource, sourceIndexer);
assertFalse(job.execute(new NullProgressMonitor()));
}
public void testDepHeaderChangeReindex() throws Exception{
// Add a file to the project
IFile cH = importFile("c.h","resources/dependency/c.h");
IFile aH = importFile("a.h","resources/dependency/a.h");
IFile depTest3H = importFile("DepTest3.h","resources/dependency/DepTest3.h");
IFile depTest3C = importFile("DepTest3.cpp","resources/dependency/DepTest3.cpp");
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
ICSearchPattern pattern = SearchEngine.createSearchPattern( "Z", ICSearchConstants.TYPE, ICSearchConstants.DEFINITIONS, true );
search(workspace,pattern,scope,resultCollector);
Set resultSet = resultCollector.getSearchResults();
if (resultSet.size() != 1)
fail("Expected 1 match");
Iterator iter = resultSet.iterator();
IMatch match = (IMatch) iter.next();
if (!(match.getName().equals("Z")) &&
(match.getElementType() != 64 ))
fail("Wrong search result");
editCode(depTest3H,"#include \"a.h\"","//#include \"a.h\"");
search(workspace,pattern,scope,resultCollector);
resultSet = resultCollector.getSearchResults();
if (resultSet.size() != 1)
fail("Expected no matches");
}
private String[] convertToLocalPath(String[] model) {
IPath defaultPath = Platform.getLocation();
String pathString = defaultPath.toOSString();
char endChar = pathString.charAt(pathString.length() - 1);
if (endChar == '/' ||
endChar == '\\')
{
pathString = pathString.substring(0, pathString.length() - 1);
}
String[] tempLocalArray = new String[model.length];
for (int i=0;i<model.length;i++){
StringBuffer buffer = new StringBuffer();
buffer.append(pathString);
buffer.append(model[i]);
tempLocalArray[i]=buffer.toString();
}
return tempLocalArray;
}
private void getTableRefs(IFile tempFile, PathCollector pathCollector) throws InterruptedException{
ICSearchScope scope = SearchEngine.createWorkspaceScope();
CSearchPattern pattern = CSearchPattern.createPattern(tempFile.getLocation().toOSString(),ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES,ICSearchConstants.EXACT_MATCH,true);
IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
indexManager.performConcurrentJob(
new PatternSearchJob(
(CSearchPattern) pattern,
scope,
pathCollector,
indexManager
),
ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
null, null );
}
private void editCode(IFile tempFile, String beforeString, String afterString) throws IOException, CoreException, InterruptedException{
FileReader fileReader = null;
try {
fileReader = new FileReader(tempFile.getLocation().toOSString());
} catch (FileNotFoundException e) {
fail(e.getMessage());
}
BufferedReader buff = new BufferedReader(fileReader);
String tempString;
File tempUtilFile= new File(tempFile.getLocation().toOSString() + "TempFile");
FileWriter writer = new FileWriter(tempUtilFile);
try {
while ((tempString = buff.readLine())!= null ) {
if (tempString.equals(beforeString)){
writer.write(afterString + "\n" );
writer.flush();
}
else{
writer.write(tempString + "\n" );
writer.flush();
}
}
} catch (IOException e1) {
fail(e1.getMessage());
}
writer.close();
buff.close();
FileInputStream buff2 = new FileInputStream(tempUtilFile);
tempFile.setContents(buff2,true,false,null);
tempFile.refreshLocal(IResource.DEPTH_INFINITE, null);
//buff2.close();
}
private void compareArrays(String[] first, String[] second){
if (first.length != second.length)
fail("Number of included files differs from model");
Arrays.sort(first);
Arrays.sort(second);
for (int i=0;i<first.length; i++)
{
assertEquals(first[i],second[i]);
}
}
protected void search(IWorkspace workspace, ICSearchPattern pattern, ICSearchScope scope, ICSearchResultCollector collector) {
try {
searchEngine.search( workspace, pattern, scope, collector, false );
} catch (InterruptedException e) {
}
}
/*
* Utils
*/
private IProject createProject(String projectName) throws CoreException
{
ICProject cproject = CProjectHelper.createCCProject(projectName, "bin");
return cproject.getProject();
}
private IFile importFile(String fileName, String resourceLocation)throws Exception {
resetIndexState();
//Obtain file handle
file = testProject.getProject().getFile(fileName);
//Create file input stream
monitor = new NullProgressMonitor();
if (!file.exists()) {
file.create(new FileInputStream(
CTestPlugin.getDefault().getFileInPlugin(new Path(resourceLocation))),
false, monitor);
}
waitForIndex(10); // only wait 20 seconds max.
return file;
}
public void resetIndexState() {
fileIndexed = false;
}
public void waitForIndex(int maxSec) throws Exception {
int delay = 0;
while (fileIndexed != true && delay < (maxSec * 1000))
{
Thread.sleep(TIMEOUT);
delay += TIMEOUT;
}
}
public void indexChanged(IndexChangeEvent event) {
IIndexDelta delta = event.getDelta();
if (delta.getDeltaType() == IIndexDelta.MERGE_DELTA){
fileIndexed = true;
}
}
public void resetIndexer(final String indexerId){
if ( testProject != null) {
ICDescriptorOperation op = new ICDescriptorOperation() {
public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException {
descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID);
descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId);
}
};
try {
CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor());
CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject);
} catch (CoreException e) {}
}
}
}

View file

@ -1,103 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.indexer.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.cindexstorage.ICIndexStorageConstants;
import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.GammaCompressedIndexBlock;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexBlock;
/**
* @author Bogdan Gheorghe
*/
public class IndexerOffsetTests extends TestCase {
public static void main(String[] args) {
}
public static Test suite() {
TestSuite suite = new TestSuite(IndexerOffsetTests.class.getName());
suite.addTest(new IndexerOffsetTests("testOffsetsResizing")); //$NON-NLS-1$
return suite;
}
/**
* Constructor for IndexerOffsetTests.
* @param name
*/
public IndexerOffsetTests(String name) {
super(name);
}
public void testOffsetsResizing() throws Exception{
WordEntry word = new WordEntry("typeDecl/C/Test".toCharArray());
word.addRef(2);
word.addOffset(235,5,2,IIndex.OFFSET);
word.addOffset(512,3,2,IIndex.OFFSET);
word.addOffset(512,3,2,IIndex.OFFSET);
word.addOffset(512,3,2,IIndex.OFFSET);
word.addModifiers(18,2);
word.addRef(5);
word.addOffset(43,6,5,IIndex.OFFSET);
word.addOffset(2,3,5,IIndex.LINE);
word.addOffset(89,8,5,IIndex.OFFSET);
word.addOffset(63,2,5,IIndex.LINE);
word.addOffset(124,7,5,IIndex.OFFSET);
word.addModifiers(4,5);
word.addRef(9);
word.addOffset(433,5,9,IIndex.OFFSET);
word.addOffset(234,3,9,IIndex.OFFSET);
word.addModifiers(1,9);
word.addRef(11);
word.addOffset(4233,2,11,IIndex.OFFSET);
word.addOffset(2314,7,11,IIndex.OFFSET);
word.addModifiers(8,11);
word.addRef(17);
word.addOffset(2,7,17,IIndex.OFFSET);
word.addOffset(52,8,17,IIndex.OFFSET);
word.addModifiers(32,17);
int[] test =word.getOffsets(1);
int[] modifierTest=word.getModifiers();
WordEntry word2 = new WordEntry("typeDecl/C/Test".toCharArray());
word2.addRef(4);
word2.addOffset(13,4,4, IIndex.OFFSET);
word2.addOffset(17,3,4, IIndex.OFFSET);
word2.addOffset(20,6,4,IIndex.OFFSET);
word2.addModifiers(64,4);
word2.addRef(7);
word2.addOffset(21,2,7, IIndex.OFFSET);
word2.addOffset(24,3,7, IIndex.OFFSET);
word2.addOffset(28,7,7,IIndex.OFFSET);
word2.addModifiers(128,7);
word.addWordInfo(word2.getRefs(), word2.getOffsets(), word2.getOffsetLengths(), word2.getOffsetCount(),word2.getModifiers());
word.mapRefs(new int[]{-1, 1, 17, 3, 4, 11, 6, 7, 8, 24, 10, 5, 12, 13, 14, 15, 16, 2});
IndexBlock block= new GammaCompressedIndexBlock(ICIndexStorageConstants.BLOCK_SIZE);
block.addEntry(word);
block.flush();
WordEntry entry= new WordEntry();
block.nextEntry(entry);
}
}

View file

@ -70,7 +70,6 @@ import org.eclipse.cdt.core.parser.ast.IASTVariable;
import org.eclipse.cdt.core.parser.ast.IASTVariableReference;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.FileManager;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.parser.Parser;
import org.eclipse.cdt.internal.core.parser.ParserException;
import org.eclipse.core.resources.IFile;
@ -105,7 +104,6 @@ public class FileBasePluginTest extends TestCase {
cPrj = CProjectHelper.createCCProject("ParserTestProject", "bin"); //$NON-NLS-1$ //$NON-NLS-2$
project = cPrj.getProject();
project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(false));
// ugly
if (className == null || !className.equals(aClassName)) {

View file

@ -23,7 +23,6 @@ import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.FileManager;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
@ -56,7 +55,6 @@ public class AST2FileBasePluginTest extends TestCase {
cPrj = CProjectHelper.createCCProject("AST2BasedProjectMofo", "bin"); //$NON-NLS-1$ //$NON-NLS-2$
project = cPrj.getProject();
project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(false));
// ugly
if (className == null || !className.equals(aClassName)) {

View file

@ -23,7 +23,6 @@ import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.FileManager;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
@ -56,7 +55,6 @@ public class DOMFileBasePluginTest extends TestCase {
cPrj = CProjectHelper.createCCProject("ParserTestProject", "bin"); //$NON-NLS-1$ //$NON-NLS-2$
project = cPrj.getProject();
project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(false));
// ugly
if (className == null || !className.equals(aClassName)) {

View file

@ -10,10 +10,12 @@
*******************************************************************************/
package org.eclipse.cdt.core.parser.tests.ast2;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.dom.DOMSearchUtil;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.search.DOMSearchUtil;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.core.resources.IFile;
/**
@ -30,30 +32,15 @@ public class DOMSelectionParseBaseTest extends DOMFileBasePluginTest {
return parse( code, offset1, offset2, true );
}
/**
* @param code
* @param offset1
* @param offset2
* @param b
* @return
*/
protected IASTNode parse(String code, int offset1, int offset2, boolean expectedToPass) throws Exception {
IFile file = importFile("temp.cpp", code); //$NON-NLS-1$
IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, offset1, offset2 - offset1);
if (!expectedToPass) return null;
if (names.length == 0) {
assertFalse(true);
} else {
return names[0];
}
return null;
return parse(file, offset1, offset2, expectedToPass);
}
protected IASTNode parse(IFile file, int offset1, int offset2, boolean expectedToPass) throws Exception {
IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, offset1, offset2 - offset1);
ITranslationUnit tu = (ITranslationUnit)CCorePlugin.getDefault().getCoreModel().create(file);
IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0);
IASTName[] names = tu.getLanguage().getSelectedNames(ast, offset1, offset2 - offset1);
if (!expectedToPass) return null;
@ -67,10 +54,10 @@ public class DOMSelectionParseBaseTest extends DOMFileBasePluginTest {
}
protected IASTName[] getDeclarationOffTU(IASTName name) {
return DOMSearchUtil.getNamesFromDOM(name, ICSearchConstants.DECLARATIONS);
return DOMSearchUtil.getNamesFromDOM(name, DOMSearchUtil.DECLARATIONS);
}
protected IASTName[] getReferencesOffTU(IASTName name) {
return DOMSearchUtil.getNamesFromDOM(name, ICSearchConstants.REFERENCES);
return DOMSearchUtil.getNamesFromDOM(name, DOMSearchUtil.REFERENCES);
}
}

View file

@ -20,8 +20,6 @@ import java.io.InputStream;
import junit.framework.TestCase;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorOperation;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.FileManager;
@ -31,7 +29,6 @@ import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
/**
@ -75,20 +72,7 @@ abstract public class BaseTestFramework extends TestCase {
}
public void disableIndexing(){
if ( project != null) {
ICDescriptorOperation op = new ICDescriptorOperation() {
public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException {
descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID);
descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,CCorePlugin.NULL_INDEXER_UNIQUE_ID);
}
};
try {
CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(project, op, new NullProgressMonitor());
CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(project);
indexDisabled=true;
} catch (CoreException e) {}
}
// TODO turn off PDOM indexing?
}
public BaseTestFramework()

View file

@ -40,10 +40,8 @@ public class RegressionTestSuite extends TestSuite {
public static Test suite() {
final RegressionTestSuite suite = new RegressionTestSuite();
suite.addTest( SearchRegressionTests.suite( false ) );
suite.addTest( SelectionRegressionTest.suite( false ) );
suite.addTest( new SearchRegressionTests("cleanupProject") ); //$NON-NLS-1$
return suite;
}
}

View file

@ -32,8 +32,6 @@ import org.eclipse.cdt.core.parser.ast.IASTNode;
import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement;
import org.eclipse.cdt.core.parser.tests.CompleteParseBaseTest.FullParseCallback;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
@ -103,8 +101,6 @@ public class SelectionRegressionTest extends BaseTestFramework {
}
} catch ( CoreException e ) { //boo
}
TypeCacheManager typeCacheManager = TypeCacheManager.getInstance();
typeCacheManager.setProcessTypeCacheEvents(false);
}
protected void tearDown() throws Exception {
@ -112,7 +108,6 @@ public class SelectionRegressionTest extends BaseTestFramework {
return;
try{
project.setSessionProperty( DOMSourceIndexer.activationKey, new Boolean( false ) );
project.delete(true,true,new NullProgressMonitor());
project = null;
} catch ( CoreException e ) { //boo

View file

@ -1,179 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
*******************************************************************************/
/*
* Created on Jul 22, 2003
*/
package org.eclipse.cdt.core.search.tests;
import java.io.FileInputStream;
import junit.framework.TestCase;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.ICDescriptor;
import org.eclipse.cdt.core.ICDescriptorOperation;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.search.BasicSearchResultCollector;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.ICSearchResultCollector;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.core.testplugin.CProjectHelper;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.core.testplugin.FileManager;
import org.eclipse.cdt.internal.core.index.cindexstorage.Index;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexerRunner;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class BaseSearchTest extends TestCase implements ICSearchConstants {
static protected ICSearchScope scope;
static protected IFile file;
static protected IProject testProject;
static protected NullProgressMonitor monitor;
static protected IWorkspace workspace;
static protected BasicSearchResultCollector resultCollector;
static protected SearchEngine searchEngine;
static protected FileManager fileManager;
static final String sourceIndexerID = "org.eclipse.cdt.core.originalsourceindexer"; //$NON-NLS-1$
static protected DOMSourceIndexer sourceIndexer;
{
//(CCorePlugin.getDefault().getCoreModel().getIndexManager()).reset();
monitor = new NullProgressMonitor();
workspace = ResourcesPlugin.getWorkspace();
CCorePlugin.getDefault().getPluginPreferences().setValue(CCorePlugin.PREF_INDEXER, CCorePlugin.DEFAULT_INDEXER_UNIQ_ID);
try {
//Create temp project
testProject = createProject("SearchTestProject");
resetIndexer(DOMSourceIndexer.ID);
testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true));
//Set the id of the source indexer extension point as a session property to allow
//index manager to instantiate it
//testProject.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID);
sourceIndexer = (DOMSourceIndexer) CCorePlugin.getDefault().getCoreModel().getIndexManager().getIndexerForProject(testProject);
} catch (CoreException e) {}
resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID);
//The DOM Source Indexer checks to see if a file has any scanner info
//set prior to indexing it in order to increase efficiency. We need to let it know
//that it is running in test mode in order to allow for this scanner info test to be skipped
DOMSourceIndexerRunner.setSkipScannerInfoTest(true);
if (testProject == null)
fail("Unable to create project");
//Create file manager
fileManager = new FileManager();
try {
//Add a file to the project
//importFile("mail.cpp", "resources/indexer/mail.cpp");
importFile("classDecl.cpp", "resources/search/classDecl.cpp");
importFile("include.h", "resources/search/include.h");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
scope = SearchEngine.createWorkspaceScope();
resultCollector = new BasicSearchResultCollector();
searchEngine = new SearchEngine();
}
public BaseSearchTest(String name) {
super(name);
}
protected void setUp() throws Exception {
}
protected void tearDown() {
}
private IProject createProject(String projectName) throws CoreException {
ICProject cPrj = CProjectHelper.createCCProject(projectName, "bin");
return cPrj.getProject();
}
private void importFile(String fileName, String resourceLocation) throws Exception{
//Obtain file handle
file = testProject.getProject().getFile(fileName);
//Create file input stream
if (!file.exists()){
file.create(new FileInputStream(
CTestPlugin.getDefault().getFileInPlugin(new Path(resourceLocation))),
false,monitor);
fileManager.addFile(file);
}
}
protected char[] getSearchPattern(int meta_kind, int kind, int ref, String name) {
return Index.encodeEntry(meta_kind, kind, ref, name);
}
public void assertEquals(char [] first, char [] second) {
assertEquals( new String(first), new String(second));
}
protected void search(IWorkspace workspace, ICSearchPattern pattern, ICSearchScope scope, ICSearchResultCollector collector) {
try {
searchEngine.search( workspace, pattern, scope, collector, false );
} catch (InterruptedException e) {
}
}
public void resetIndexer(final String indexerId){
if ( testProject != null) {
ICDescriptorOperation op = new ICDescriptorOperation() {
public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException {
descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID);
descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId);
}
};
try {
CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor());
CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject);
} catch (CoreException e) {}
}
}
}

View file

@ -1,287 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
*******************************************************************************/
/*
* Created on Jul 3, 2003
*/
package org.eclipse.cdt.core.search.tests;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.IMatch;
import org.eclipse.cdt.core.search.IOffsetLocatable;
import org.eclipse.cdt.core.search.OrPattern;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.search.matching.ClassDeclarationPattern;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ClassDeclarationPatternTests extends BaseSearchTest implements ICSearchConstants {
public ClassDeclarationPatternTests(String name) {
super(name);
}
public void testMatchSimpleDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", TYPE, DEFINITIONS, false );
assertTrue( pattern instanceof ClassDeclarationPattern );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
//Changed to 2 since we also return Derived as a Typdecl
assertEquals( 2, matches.size() );
}
public void testMatchNamespaceNestedDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "NS::B", TYPE, DEFINITIONS, true );
assertTrue( pattern instanceof ClassDeclarationPattern );
ClassDeclarationPattern clsPattern = (ClassDeclarationPattern)pattern;
assertTrue( CharOperation.equals( new char[] { 'B' }, clsPattern.getName() ) );
assertTrue( clsPattern.getContainingTypes().length == 1 );
assertTrue( CharOperation.equals( new char[] { 'N', 'S' }, clsPattern.getContainingTypes()[0] ) );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 1, matches.size() );
}
public void testBug39652() {
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B", TYPE, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
/* Test should find 1 match */
assertTrue( matches != null );
assertTrue( matches.size() == 1 );
pattern = SearchEngine.createSearchPattern( "NS::NS2::a", TYPE, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertTrue( matches != null );
pattern = SearchEngine.createSearchPattern( "NS::B::AA", TYPE, DEFINITIONS, true ); //TODO was NS::B::A, changed for bug 41445
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertTrue( matches != null );
}
public void testMatchStruct(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "AA", STRUCT, DEFINITIONS, true ); //TODO was A, changed for bug 41445
assertTrue( pattern instanceof ClassDeclarationPattern );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "NS::B::AA", TYPE, DEFINITIONS, true ); //TODO was 2, changed for bug 41445
search( workspace, pattern, scope, resultCollector );
Set matches2 = resultCollector.getSearchResults();
assertTrue( matches2 != null );
assertEquals( matches2.size(), 1 );
Iterator iter = matches.iterator();
Iterator iter2 = matches2.iterator();
IMatch match = (IMatch)iter.next();
IMatch match2 = (IMatch)iter2.next();
//assertTrue( match.path.equals( match2.path ) );
assertEquals( ((IOffsetLocatable) match.getLocatable()).getNameStartOffset(), ((IOffsetLocatable) match2.getLocatable()).getNameStartOffset() );
assertEquals( ((IOffsetLocatable) match.getLocatable()).getNameEndOffset() , ((IOffsetLocatable) match2.getLocatable()).getNameEndOffset() );
}
public void testWildcardQualification() {
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::*::A", TYPE, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 0 );
pattern = SearchEngine.createSearchPattern( "NS::*::A", TYPE, DEFINITIONS, false );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 ); //TODO was 1, changed for bug 41445
}
public void testElaboratedType(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "struct AA", TYPE, DEFINITIONS, true ); //TODO was 2, changed for bug 41445
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "union u", TYPE, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
pattern = SearchEngine.createSearchPattern( "union ::*::u", TYPE, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testClassIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "struct A::B::*::c", TYPE, DECLARATIONS, true );
assertTrue( pattern instanceof ClassDeclarationPattern );
ClassDeclarationPattern clsPattern = (ClassDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_STRUCT, IIndex.DECLARATION, "c/"), clsPattern.indexEntryPrefix());
clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "class ::*::A::B::c", TYPE, DECLARATIONS, true );
assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DECLARATION, "c/B/A/"), clsPattern.indexEntryPrefix());
clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "enum ::RT*::c", TYPE, REFERENCES, true );
assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_ENUM, IIndex.REFERENCE,"c/RT"), clsPattern.indexEntryPrefix());
clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "union A::B::c", TYPE, REFERENCES, false );
assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_UNION, IIndex.REFERENCE, ""), clsPattern.indexEntryPrefix());
}
public void testGloballyQualifiedItem(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::A", TYPE, DEFINITIONS, true );
assertTrue( pattern instanceof ClassDeclarationPattern );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "::u", TYPE, DEFINITIONS, true );
assertTrue( pattern instanceof ClassDeclarationPattern );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1);
}
public void testClassReferences(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::A", TYPE, REFERENCES, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 6, matches.size());
}
public void testClassReferenceInFieldType(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::B::AA", TYPE, REFERENCES, true ); //TODO was A, changed for bug 41445
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testTypeReferenceVisibleByUsingDirective(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::NS2::a", STRUCT, REFERENCES, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testEnumerationReferenceVisibleByInheritance(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::B::e", ENUM, REFERENCES, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testHeadersVisitedTwice(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "Hea*", CLASS, DEFINITIONS, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
//1 for Heal, 1 for Head
assertEquals( matches.size(), 2 );
}
public void testAllOccurences(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", TYPE, ALL_OCCURRENCES, true );
assertTrue( pattern instanceof OrPattern );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals(8, matches.size() );
}
public void testReferencesInFunction(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "AClassForFoo", CLASS, REFERENCES, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 3 );
Iterator iter = matches.iterator();
while( iter.hasNext() ){
IMatch match = (IMatch) iter.next();
assertTrue( match.getName().equals("AClassForFoo") );
}
}
public void testbug42902_TypeDefs(){
ICSearchPattern pattern = SearchEngine.createSearchPattern("NS_B", TYPEDEF, ALL_OCCURRENCES, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
}
/* public void testBug54169(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "e", TYPE, DECLARATIONS, true );
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "NS_B", TYPE, DECLARATIONS, true );
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}*/
}

View file

@ -1,256 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
*******************************************************************************/
/*
* Created on Jul 23, 2003
*/
package org.eclipse.cdt.core.search.tests;
import java.util.Set;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.IMatch;
import org.eclipse.cdt.core.search.IOffsetLocatable;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.search.matching.MethodDeclarationPattern;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class FunctionMethodPatternTests extends BaseSearchTest {
/**
* @param name
*/
public FunctionMethodPatternTests(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void testFunctionIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "c()", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$
MethodDeclarationPattern functionPattern = (MethodDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.DECLARATION, "c"), functionPattern.indexEntryPrefix() ); //$NON-NLS-1$
functionPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "rt*()", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.DECLARATION, "rt"), functionPattern.indexEntryPrefix()); //$NON-NLS-1$
functionPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "Ac", FUNCTION, REFERENCES, false ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.REFERENCE, ""), functionPattern.indexEntryPrefix()); //$NON-NLS-1$
}
public void testMethodIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
MethodDeclarationPattern methodPattern = (MethodDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.DECLARATION, "c/B/A"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$
methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.DECLARATION, "c/B/A/"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$
methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", METHOD, REFERENCES, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.REFERENCE, "c/RT"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$
methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", METHOD, REFERENCES, false ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.REFERENCE, ""), methodPattern.indexEntryPrefix()); //$NON-NLS-1$
}
public void testMethodDeclaration() {
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 4 );
}
public void testMethodDeclarationWithParams() {
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f( A )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 1, matches.size());
}
public void testMethodDeclarationParameterMatching(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "f( A & )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 1,matches.size() );
pattern = SearchEngine.createSearchPattern( "f( A * )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( 1, matches.size());
pattern = SearchEngine.createSearchPattern( "f( int &, const char [], A** )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( 1, matches.size() );
}
public void testMethodWithNoParameters(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "turn( )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 2, matches.size());
pattern = SearchEngine.createSearchPattern( "turn(void)", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( 2, matches.size());
pattern = SearchEngine.createSearchPattern( "turnAgain()", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( 1, matches.size());
}
public void testOperators_bug43063_bug42979(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "operator \\*", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match1 = (IMatch) matches.iterator().next();
pattern = SearchEngine.createSearchPattern( "operator \\*", METHOD, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match2 = (IMatch) matches.iterator().next();
assertTrue( ((IOffsetLocatable)match1.getLocatable()).getNameStartOffset() == ((IOffsetLocatable)match2.getLocatable()).getNameStartOffset() );
pattern = SearchEngine.createSearchPattern( "operator \\*=", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
match1 = (IMatch) matches.iterator().next();
pattern = SearchEngine.createSearchPattern( "operator \\*=", METHOD, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
match2 = (IMatch) matches.iterator().next();
assertTrue( ((IOffsetLocatable)match1.getLocatable()).getNameStartOffset() != ((IOffsetLocatable)match2.getLocatable()).getNameStartOffset() );
pattern = SearchEngine.createSearchPattern( "operator *", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 5 );
pattern = SearchEngine.createSearchPattern( "operator *", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 8 ); //2 in classDecl.cpp
pattern = SearchEngine.createSearchPattern( "operator ->\\*", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
MethodDeclarationPattern methodPattern = (MethodDeclarationPattern) pattern;
char [] string = new char[] {'o','p','e','r','a','t','o','r',' ','-','>','\\','*'};
assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) );
}
public void testBug43498(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "operator ?elete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
MethodDeclarationPattern methodPattern = (MethodDeclarationPattern) pattern;
char [] string = new char[] {'o','p','e','r','a','t','o','r',' ','?','e','l','e','t','e'};
assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) );
pattern = SearchEngine.createSearchPattern( "operator delete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
methodPattern = (MethodDeclarationPattern) pattern;
string = new char[] {'o','p','e','r','a','t','o','r',' ','d','e','l','e','t','e'};
assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) );
pattern = SearchEngine.createSearchPattern( "word?word", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
methodPattern = (MethodDeclarationPattern) pattern;
string = new char[] {'w','o','r','d','?','w','o','r','d'};
assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) );
pattern = SearchEngine.createSearchPattern( "operato? delete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof MethodDeclarationPattern );
methodPattern = (MethodDeclarationPattern) pattern;
string = new char[] {'o','p','e','r','a','t','o','?',' ','d','e','l','e','t','e'};
assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) );
}
public void testBug43062(){
MethodDeclarationPattern pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator const short &", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
char [] string = new char [] { 'o','p','e','r','a','t','o','r',' ','c','o','n','s','t',' ','s','h','o','r','t',' ','&' };
assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) );
pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator short", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
string = new char [] { 'o','p','e','r','a','t','o','r',' ','s','h','o','r','t' };
assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) );
pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator short int", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
string = new char [] { 'o','p','e','r','a','t','o','r',' ','s','h','o','r','t',' ','i','n','t' };
assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) );
}
public void testConstructorDestructor(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "~A", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testLookupForDefinition(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "turn", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 3 );
pattern = SearchEngine.createSearchPattern( "Direction::turn", METHOD, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 0 );
}
public void testBug63478(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f(*)", METHOD, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 4 );
}
}

View file

@ -1,368 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
*******************************************************************************/
/*
* Created on Jul 23, 2003
*/
package org.eclipse.cdt.core.search.tests;
import java.util.Set;
import org.eclipse.cdt.core.search.BasicSearchMatch;
import org.eclipse.cdt.core.search.ICSearchPattern;
import org.eclipse.cdt.core.search.IMatch;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.search.matching.FieldDeclarationPattern;
import org.eclipse.cdt.internal.core.search.matching.MatchLocator;
import org.eclipse.cdt.internal.core.search.matching.NamespaceDeclarationPattern;
import org.eclipse.core.runtime.Path;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class OtherPatternTests extends BaseSearchTest {
/**
* @param name
*/
public OtherPatternTests(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void testNamespaceIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof NamespaceDeclarationPattern );
NamespaceDeclarationPattern nsPattern = (NamespaceDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION, "c/B/A"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$
nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION, "c/B/A/"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$
nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.REFERENCE, "c/RT"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$
nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", NAMESPACE, REFERENCES, false ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.REFERENCE, ""), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$
}
public void testVariableIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "c", VAR, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof FieldDeclarationPattern );
FieldDeclarationPattern variablePattern = (FieldDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.DECLARATION, "c"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$
variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "rt*", VAR, DECLARATIONS, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.DECLARATION, "rt"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$
variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "Ac", VAR, REFERENCES, false ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.REFERENCE, ""), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$
variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "A?c", VAR, REFERENCES, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.REFERENCE, "A"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$
}
public void testFieldIndexPrefix(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", FIELD, DECLARATIONS, true ); //$NON-NLS-1$
assertTrue( pattern instanceof FieldDeclarationPattern );
FieldDeclarationPattern fieldPattern = (FieldDeclarationPattern)pattern;
assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.DECLARATION, "c/B/A"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$
fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", FIELD, DECLARATIONS, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.DECLARATION, "c/B/A/"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$
fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", FIELD, REFERENCES, true ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.REFERENCE, "c/RT"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$
fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", FIELD, REFERENCES, false ); //$NON-NLS-1$
assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.REFERENCE, ""), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$
}
public void testNamespaceDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "NS*", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 3 );
}
public void testNamespaceReferenceInUsingDirective() {
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::NS2", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testNamespaceReferenceInClassBaseClause(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
}
public void testFieldDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "a*Struct", FIELD, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testVariableDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "b?", VAR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
IMatch match = (IMatch) matches.iterator().next();
assertTrue( match.getParentName().equals( "" ) ); //$NON-NLS-1$
}
/*public void testParameterDeclaration(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "index", VAR, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( 5, matches.size());
}
public void testOrPattern(){
OrPattern orPattern = new OrPattern();
orPattern.addPattern( SearchEngine.createSearchPattern( "::NS::B::e", ENUM, REFERENCES, true ) ); //$NON-NLS-1$
orPattern.addPattern( SearchEngine.createSearchPattern( "Hea*", CLASS, DECLARATIONS, true ) ); //$NON-NLS-1$
search( workspace, orPattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 3 );
orPattern = new OrPattern();
orPattern.addPattern( SearchEngine.createSearchPattern( "b?", VAR, DECLARATIONS, true ) ); //$NON-NLS-1$
orPattern.addPattern( SearchEngine.createSearchPattern( "a*Struct", FIELD, DECLARATIONS, true ) ); //$NON-NLS-1$
orPattern.addPattern( SearchEngine.createSearchPattern( "::NS::NS2", NAMESPACE, REFERENCES, true ) ); //$NON-NLS-1$
orPattern.addPattern( SearchEngine.createSearchPattern( "A::B::f( A )", METHOD, DECLARATIONS, true ) ); //$NON-NLS-1$
search( workspace, orPattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( 5, matches.size() );
}*/
public void testMacroPattern(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "FOO", MACRO, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match = (IMatch) matches.iterator().next();
assertTrue( match.getName().equals( "FOO" ) ); //$NON-NLS-1$
assertTrue( match.getParentName().equals( "" )); //$NON-NLS-1$
pattern = SearchEngine.createSearchPattern( "FOO", MACRO, ALL_OCCURRENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
public void testDerived(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", DERIVED, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match = (IMatch) matches.iterator().next();
assertTrue( match.getName().equals( "A" ) ); //$NON-NLS-1$
}
public void testEnumerators(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "One", ENUMTOR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match = (IMatch) matches.iterator().next();
assertTrue( match.getName().equals( "One" ) ); //$NON-NLS-1$
pattern = SearchEngine.createSearchPattern( "NS::B::Two", ENUMTOR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
match = (IMatch) matches.iterator().next();
assertTrue( match.getName().equals( "Two" ) ); //$NON-NLS-1$
}
public void testEnumeratorReferences(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "One", ENUMTOR, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
IMatch match = (IMatch) matches.iterator().next();
assertTrue( match.getName().equals( "One" ) ); //$NON-NLS-1$
}
/*public void testParameterReferences(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "index", VAR, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 3 );
}*/
/*public void testBug43129(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "externalInt", VAR, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "externalIntWithInitializer", VAR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "externCInt", VAR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "externCIntWithInitializer", VAR, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "forwardFunction", FUNCTION, ALL_OCCURRENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
pattern = SearchEngine.createSearchPattern( "normalFunction", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "normalFunction", FUNCTION, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "forwardMethod", METHOD, ALL_OCCURRENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
pattern = SearchEngine.createSearchPattern( "staticField", FIELD, ALL_OCCURRENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 2 );
}*/
public void testNoResourceSearching() throws Exception {
String path = CTestPlugin.getDefault().getFileInPlugin(new Path("resources/search/include.h")).getAbsolutePath(); //$NON-NLS-1$
ICSearchPattern pattern = SearchEngine.createSearchPattern( "Head", CLASS, REFERENCES, true ); //$NON-NLS-1$
resultCollector.aboutToStart();
MatchLocator matchLocator = new MatchLocator( pattern, resultCollector, scope);
matchLocator.setProgressMonitor(monitor);
try {
matchLocator.locateMatches( new String [] { path }, workspace, null );
} catch (InterruptedException e1) { //boo
}
resultCollector.done();
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 4 );
}
public void testBug42911_43988(){
BasicSearchMatch match1 = new BasicSearchMatch();
BasicSearchMatch match2 = new BasicSearchMatch();
assertTrue( match1.equals( match2 ) );
assertTrue( match2.equals( match1 ) );
match1.setName( "IWasSaying" ); //$NON-NLS-1$
match1.setParentName( "boo" ); //$NON-NLS-1$
match1.setReturnType( "urns" ); //$NON-NLS-1$
assertFalse( match1.equals( match2 ) );
assertFalse( match2.equals( match1 ) );
match2.setName( "IWasSaying" ); //$NON-NLS-1$
match2.setParentName( "boo" ); //$NON-NLS-1$
match2.setReturnType( "urns" ); //$NON-NLS-1$
assertTrue( match1.equals( match2 ) );
}
public void testBug68235(){
ICSearchPattern pattern = SearchEngine.createSearchPattern( "bug68235::xTag", STRUCT, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
Set matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "bug68235::yTag", STRUCT, DEFINITIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "bug68235::xType", TYPEDEF, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "bug68235::yType", TYPEDEF, DECLARATIONS, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "bug68235::xType", TYPEDEF, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
pattern = SearchEngine.createSearchPattern( "bug68235::yType", TYPEDEF, REFERENCES, true ); //$NON-NLS-1$
search( workspace, pattern, scope, resultCollector );
matches = resultCollector.getSearchResults();
assertEquals( matches.size(), 1 );
}
}

View file

@ -1,66 +0,0 @@
/*******************************************************************************
* Copyright (c) 2002, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.search.tests;
import java.io.File;
import junit.framework.TestCase;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.NullLogService;
import org.eclipse.cdt.core.parser.NullSourceElementRequestor;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.core.runtime.Path;
/**
* @author jcamelon
*
*/
public class ParseTestOnSearchFiles extends TestCase
{
private String name;
private String fullPathName;
/**
*
*/
public ParseTestOnSearchFiles()
{
super();
}
/**
* @param name
*/
public ParseTestOnSearchFiles(String name)
{
super(name);
}
protected void setUp() throws Exception {
name = "resources/search/classDecl.cpp";
File f = CTestPlugin.getDefault().getFileInPlugin(new Path(name));
fullPathName = f.getAbsolutePath();
}
public void testParseOfAndrewsFile() throws Exception
{
ISourceElementRequestor requestor = new NullSourceElementRequestor();
IScanner scanner = ParserFactory.createScanner( fullPathName, new ScannerInfo(), ParserMode.COMPLETE_PARSE, ParserLanguage.CPP, requestor, new NullLogService(), null );
IParser parser = ParserFactory.createParser( scanner, requestor, ParserMode.COMPLETE_PARSE, ParserLanguage.CPP, null );
assertTrue( parser.parse() );
}
}

View file

@ -1,34 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corp. - Rational Software - initial implementation
*******************************************************************************/
package org.eclipse.cdt.core.search.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author aniefer
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class SearchTestSuite extends TestCase {
public static Test suite() {
TestSuite suite= new TestSuite(SearchTestSuite.class.getName());
suite.addTestSuite(ClassDeclarationPatternTests.class);
suite.addTestSuite(FunctionMethodPatternTests.class);
suite.addTestSuite(OtherPatternTests.class);
suite.addTestSuite(ParseTestOnSearchFiles.class);
return suite;
}
}

View file

@ -1,13 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="index"/>
<classpathentry kind="src" path="model"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="utils"/>
<classpathentry kind="src" path="search"/>
<classpathentry kind="src" path="dependency"/>
<classpathentry kind="src" path="parser"/>
<classpathentry kind="src" path="browser"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>

View file

@ -7,8 +7,6 @@ Bundle-Activator: org.eclipse.cdt.core.CCorePlugin
Bundle-Vendor: %providerName
Bundle-Localization: plugin
Export-Package: org.eclipse.cdt.core,
org.eclipse.cdt.core.browser,
org.eclipse.cdt.core.browser.typehierarchy,
org.eclipse.cdt.core.dom,
org.eclipse.cdt.core.dom.ast,
org.eclipse.cdt.core.dom.ast.c,
@ -17,29 +15,19 @@ Export-Package: org.eclipse.cdt.core,
org.eclipse.cdt.core.dom.ast.gnu.c,
org.eclipse.cdt.core.dom.ast.gnu.cpp,
org.eclipse.cdt.core.formatter,
org.eclipse.cdt.core.index,
org.eclipse.cdt.core.model,
org.eclipse.cdt.core.model.util,
org.eclipse.cdt.core.parser,
org.eclipse.cdt.core.parser.ast,
org.eclipse.cdt.core.parser.ast.gcc,
org.eclipse.cdt.core.parser.extension,
org.eclipse.cdt.core.parser.util,
org.eclipse.cdt.core.resources,
org.eclipse.cdt.core.search,
org.eclipse.cdt.internal.core,
org.eclipse.cdt.internal.core.browser.cache,
org.eclipse.cdt.internal.core.browser.util,
org.eclipse.cdt.internal.core.dom,
org.eclipse.cdt.internal.core.dom.parser,
org.eclipse.cdt.internal.core.dom.parser.c,
org.eclipse.cdt.internal.core.dom.parser.cpp,
org.eclipse.cdt.internal.core.index,
org.eclipse.cdt.internal.core.index.cindexstorage,
org.eclipse.cdt.internal.core.index.cindexstorage.io,
org.eclipse.cdt.internal.core.index.ctagsindexer,
org.eclipse.cdt.internal.core.index.domsourceindexer,
org.eclipse.cdt.internal.core.index.impl,
org.eclipse.cdt.internal.core.index.nullindexer,
org.eclipse.cdt.internal.core.model,
org.eclipse.cdt.internal.core.parser,
org.eclipse.cdt.internal.core.parser.ast,
@ -57,11 +45,6 @@ Export-Package: org.eclipse.cdt.core,
org.eclipse.cdt.internal.core.pdom.dom,
org.eclipse.cdt.internal.core.pdom.dom.c,
org.eclipse.cdt.internal.core.pdom.dom.cpp,
org.eclipse.cdt.internal.core.search,
org.eclipse.cdt.internal.core.search.indexing,
org.eclipse.cdt.internal.core.search.matching,
org.eclipse.cdt.internal.core.search.processing,
org.eclipse.cdt.internal.core.sourcedependency,
org.eclipse.cdt.internal.core.util,
org.eclipse.cdt.internal.errorparsers,
org.eclipse.cdt.internal.formatter,

View file

@ -1,108 +0,0 @@
2005-03-29 Chris Wiebe
small change for potential reduction in memory usage
* browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java
2005-03-29 Chris Wiebe
temporary fix for type parser timeout
* browser/org/eclipse/cdt/core/browser/cache/TypeParser.java
2005-03-13 Bogdan Gheorghe
Updated references to IndexManager to reflect new multi-indexer framework.
* browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependencies.java
* browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob.java
* browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob.java
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeCache.java
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacherJob.java
Added temporary flag to TypeCacheManager to prevent deadlocks during JUnit runs, pending
changes to Index Storage framework.
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java
2005-01-06 Chris Wiebe
added parser timeout to TypeParser
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java
2004-11-08 Chris Wiebe
fix for 68883
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java
2004-09-15 Chris Wiebe
add getTypes and getAllTypes methods
* browser/org/eclipse/cdt/core/browser/TypeUtil.java
2004-09-02 Chris Wiebe
add method to get global namespace
* browser/org/eclipse/cdt/internal/core/browser/AllTypesCache.java
2004-09-01 Chris Wiebe
avoid unnecessary deltas
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java
2004-08-31 Chris Wiebe
Fix for 68883
* browser/org/eclipse/cdt/core/browser/AllTypesCache.java
* browser/org/eclipse/cdt/core/browser/ITypeCacheChangedListener.java
* browser/org/eclipse/cdt/core/browser/ITypeInfo.java
* browser/org/eclipse/cdt/core/browser/TypeInfo.java
* browser/org/eclipse/cdt/core/browser/TypeUtil.java
* browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchy.java
* browser/org/eclipse/cdt/core/browser/cache/ITypeCache.java
* browser/org/eclipse/cdt/core/browser/cache/TypeCache.java
* browser/org/eclipse/cdt/core/browser/cache/TypeCacheManager.java
2004-08-26 Chris Wiebe
make QualifiedTypeName immutable class
get rid of unnecessary memory allocations
* browser/org/eclipse/cdt/core/browser/IQualifiedTypeName.java
* browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java
* browser/org/eclipse/cdt/core/browser/TypeInfo.java
* browser/org/eclipse/cdt/internal/core/browser/TypeCache.java
2004-07-16 Chris Wiebe
Fixing numerous warnings.
2004-07-06 Chris Wiebe
This patch prevents some NPEs from happening in the class browser. I
suggest this should be applied to both HEAD and CDT_2_0 branch.
* browser/org/eclipse/cdt/core/browser/TypeInfo.java
2004-06-22 Alain Magloire
Part of PR 68246.
Close the inputstream to release resource handle
when we done with it, we can not rely on the GC to do it for us.
* browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java
2004-06-21 Chris Wiebe
- fix for bug #66108 (C++ browser cannot show members of class)
- TypeParser now uses resource to get scanner info
2004-06-17 Alain Magloire
Changes from Chris Wiebe to deal
with the memory consumption.
2004-05-12 Chris Wiebe
Heavy refactoring of type cache to address scalability
concerns.
2004-05-06 Chris Wiebe
Creating a new Job to handle the changes, instead
of reusing the same job.
2004-04-20 Chris Wiebe
refactored TypeCacheDeltaListener into standalone class
added option in Work In Progress prefs page to disable background cache
2004-04-06 Chris Wiebe
initial placement of non-ui code into org.eclipse.cdt.core.browser

View file

@ -1,366 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy;
import org.eclipse.cdt.core.browser.typehierarchy.TypeHierarchyBuilder;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ElementChangedEvent;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.IElementChangedListener;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.cdt.internal.core.browser.cache.ITypeCache;
import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager;
import org.eclipse.cdt.internal.core.browser.util.ArrayUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
/**
* Manages a search cache for types in the workspace. Instead of returning
* objects of type <code>ICElement</code> the methods of this class returns a
* list of the lightweight objects <code>TypeInfo</code>.
* <P>
* AllTypesCache runs asynchronously using a background job to rebuild the cache
* as needed. If the cache becomes dirty again while the background job is
* running, the job is restarted.
* <P>
* If <code>getTypes</code> is called in response to a user action, a progress
* dialog is shown. If called before the background job has finished, getTypes
* waits for the completion of the background job.
*/
public class AllTypesCache {
private static final int INITIAL_DELAY = 5000;
private static IWorkingCopyProvider fgWorkingCopyProvider;
private static TypeHierarchyBuilder fgTypeHierarchyBuilder;
private static IElementChangedListener fgElementChangedListener;
private static IPropertyChangeListener fgPropertyChangeListener;
static boolean fgEnableIndexing = true;
/** Preference key for enabling background cache */
public final static String ENABLE_BACKGROUND_TYPE_CACHE = "enableBackgroundTypeCache"; //$NON-NLS-1$
/**
* Initializes the AllTypesCache service.
*
* @param provider A working copy provider.
*/
public static void initialize(IWorkingCopyProvider workingCopyProvider) {
fgWorkingCopyProvider = workingCopyProvider;
TypeCacheManager.getInstance().setWorkingCopyProvider(fgWorkingCopyProvider);
fgTypeHierarchyBuilder = new TypeHierarchyBuilder();
// load prefs
// Preferences prefs = CCorePlugin.getDefault().getPluginPreferences();
// if (prefs.contains(ENABLE_BACKGROUND_TYPE_CACHE)) {
// fgEnableIndexing = prefs.getBoolean(ENABLE_BACKGROUND_TYPE_CACHE);
// } else {
// prefs.setDefault(ENABLE_BACKGROUND_TYPE_CACHE, false);
// prefs.setValue(ENABLE_BACKGROUND_TYPE_CACHE, false);
// CCorePlugin.getDefault().savePluginPreferences();
// fgEnableIndexing = true;
// }
fgEnableIndexing = false;
// start jobs in background after INITIAL_DELAY
TypeCacheManager.getInstance().reconcile(fgEnableIndexing, Job.BUILD, INITIAL_DELAY);
// add delta listener
fgElementChangedListener = new IElementChangedListener() {
public void elementChanged(ElementChangedEvent event) {
TypeCacheManager.getInstance().processElementChanged(event, fgEnableIndexing);
}
};
CoreModel.getDefault().addElementChangedListener(fgElementChangedListener);
// // add property change listener
// fgPropertyChangeListener = new IPropertyChangeListener() {
// public void propertyChange(PropertyChangeEvent event) {
// String property = event.getProperty();
// if (property.equals(ENABLE_BACKGROUND_TYPE_CACHE)) {
// String value = (String) event.getNewValue();
// fgEnableIndexing = Boolean.valueOf(value).booleanValue();
// if (!fgEnableIndexing) {
// TypeCacheManager.getInstance().cancelJobs();
// } else {
// TypeCacheManager.getInstance().reconcile(fgEnableIndexing, Job.BUILD, 0);
// }
// }
// }
// };
// prefs.addPropertyChangeListener(fgPropertyChangeListener);
}
/**
* Terminates the service provided by AllTypesCache.
*/
public static void terminate() {
// remove delta listener
if (fgElementChangedListener != null)
CoreModel.getDefault().removeElementChangedListener(fgElementChangedListener);
// remove property change listener
if (fgPropertyChangeListener != null)
CCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener(fgPropertyChangeListener);
// terminate all running jobs
if (TypeCacheManager.getInstance() != null) {
TypeCacheManager.getInstance().cancelJobs();
}
}
/**
* Returns all types in the workspace.
*/
public static ITypeInfo[] getAllTypes() {
final Collection fAllTypes = new ArrayList();
TypeSearchScope workspaceScope = new TypeSearchScope(true);
IProject[] projects = workspaceScope.getEnclosingProjects();
ITypeInfoVisitor visitor = new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
fAllTypes.add(info);
return true;
}
public boolean shouldContinue() { return true; }
};
for (int i = 0; i < projects.length; ++i) {
TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor);
}
return (ITypeInfo[]) fAllTypes.toArray(new ITypeInfo[fAllTypes.size()]);
}
/**
* Returns all types in the given scope.
*
* @param scope The search scope
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS,
* C_UNION, C_ENUMERATION, C_TYPEDEF
*/
public static ITypeInfo[] getTypes(ITypeSearchScope scope, int[] kinds) {
final Collection fTypesFound = new ArrayList();
final ITypeSearchScope fScope = scope;
final int[] fKinds = kinds;
IProject[] projects = scope.getEnclosingProjects();
ITypeInfoVisitor visitor = new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
if (ArrayUtil.contains(fKinds, info.getCElementType())
&& (fScope != null && info.isEnclosed(fScope))) {
fTypesFound.add(info);
}
return true;
}
public boolean shouldContinue() { return true; }
};
for (int i = 0; i < projects.length; ++i) {
TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor);
}
return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]);
}
/**
* Returns all types matching name in the given scope.
*
* @param scope The search scope
* @param qualifiedName The qualified type name
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS,
* C_UNION, C_ENUMERATION, C_TYPEDEF
* @param matchEnclosed <code>true</code> if enclosed types count as matches (foo::bar == bar)
*/
public static ITypeInfo[] getTypes(ITypeSearchScope scope, IQualifiedTypeName qualifiedName, int[] kinds, boolean matchEnclosed) {
final Collection fTypesFound = new ArrayList();
final ITypeSearchScope fScope = scope;
final int[] fKinds = kinds;
final IQualifiedTypeName fQualifiedName = qualifiedName;
final boolean fMatchEnclosed = matchEnclosed;
IProject[] projects = scope.getEnclosingProjects();
ITypeInfoVisitor visitor = new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
if (ArrayUtil.contains(fKinds, info.getCElementType())
&& (fScope != null && info.isEnclosed(fScope))) {
IQualifiedTypeName currName = info.getQualifiedTypeName();
if (fMatchEnclosed && currName.segmentCount() > fQualifiedName.segmentCount()
&& currName.lastSegment().equals(fQualifiedName.lastSegment())) {
currName = currName.removeFirstSegments(currName.segmentCount() - fQualifiedName.segmentCount());
}
if (currName.equals(fQualifiedName)) {
fTypesFound.add(info);
}
}
return true;
}
public boolean shouldContinue() { return true; }
};
for (int i = 0; i < projects.length; ++i) {
TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor);
}
return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]);
}
/**
* Returns all namespaces in the given scope.
*
* @param scope The search scope
* @param includeGlobalNamespace <code>true</code> if the global (default) namespace should be returned
*/
public static ITypeInfo[] getNamespaces(ITypeSearchScope scope, boolean includeGlobalNamespace) {
final Collection fTypesFound = new ArrayList();
final ITypeSearchScope fScope = scope;
IProject[] projects = scope.getEnclosingProjects();
ITypeInfoVisitor visitor = new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
if (info.getCElementType() == ICElement.C_NAMESPACE
&& (fScope != null && info.isEnclosed(fScope))) {
fTypesFound.add(info);
}
return true;
}
public boolean shouldContinue() { return true; }
};
for (int i = 0; i < projects.length; ++i) {
ITypeCache cache = TypeCacheManager.getInstance().getCache(projects[i]);
cache.accept(visitor);
if (includeGlobalNamespace) {
fTypesFound.add(cache.getGlobalNamespace());
}
}
return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]);
}
/**
* Returns the global (default) namespace for the given project.
*
* @param project the project
*/
public static ITypeInfo getGlobalNamespace(IProject project) {
ITypeCache cache = TypeCacheManager.getInstance().getCache(project);
return cache.getGlobalNamespace();
}
/**
* Returns true if the type cache is up to date.
*/
public static boolean isCacheUpToDate(ITypeSearchScope scope) {
forceDeltaComplete();
IProject[] projects = scope.getEnclosingProjects();
for (int i = 0; i < projects.length; ++i) {
IProject project = projects[i];
if (project.exists() && project.isOpen()) {
if (!TypeCacheManager.getInstance().getCache(project).isUpToDate())
return false;
}
}
return true;
}
private static void forceDeltaComplete() {
if (fgWorkingCopyProvider != null) {
IWorkingCopy[] workingCopies = fgWorkingCopyProvider.getWorkingCopies();
for (int i = 0; i < workingCopies.length; ++i) {
IWorkingCopy wc = workingCopies[i];
try {
synchronized (wc) {
wc.reconcile();
}
} catch (CModelException ex) {
}
}
}
}
/**
* Updates the type cache.
*
* @param monitor the progress monitor
*/
public static void updateCache(ITypeSearchScope scope, IProgressMonitor monitor) {
TypeCacheManager.getInstance().updateCache(scope, monitor);
}
/**
* Resolves a type location.
*
* @param info the type to search for
* @param monitor the progress monitor
*/
public static ITypeReference resolveTypeLocation(ITypeInfo info, IProgressMonitor monitor) {
return TypeCacheManager.getInstance().resolveTypeLocation(info, monitor, fgEnableIndexing);
}
/** Returns first type in the cache which matches the given
* type and name. If no type is found, <code>null</code>
* is returned.
*
* @param project the enclosing project
* @param type the ICElement type
* @param qualifiedName the qualified type name to match
* @return the matching type
*/
public static ITypeInfo getType(IProject project, int type, IQualifiedTypeName qualifiedName) {
ITypeCache cache = TypeCacheManager.getInstance().getCache(project);
return cache.getType(type, qualifiedName);
}
/**
* Returns all types matching name in the given project.
*
* @param project the enclosing project
* @param qualifiedName The qualified type name
* @param matchEnclosed <code>true</code> if enclosed types count as matches (foo::bar == bar)
* @param ignoreCase <code>true</code> if case-insensitive
* @return Array of types
*/
public static ITypeInfo[] getTypes(IProject project, IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase) {
ITypeCache cache = TypeCacheManager.getInstance().getCache(project);
return cache.getTypes(qualifiedName, matchEnclosed, ignoreCase);
}
/**
* Creates and returns a type hierarchy for this type containing
* this type and all of its supertypes and subtypes in the workspace.
*
* @param info the given type
* @param monitor the given progress monitor
* @return a type hierarchy for the given type
*/
public static ITypeHierarchy createTypeHierarchy(ICElement type, IProgressMonitor monitor) throws CModelException {
ITypeInfo info = TypeCacheManager.getInstance().getTypeForElement(type, true, true, fgEnableIndexing, monitor);
if (info != null)
return fgTypeHierarchyBuilder.createTypeHierarchy(info, fgEnableIndexing, monitor);
return null;
}
public static void addTypeCacheChangedListener(ITypeCacheChangedListener listener) {
TypeCacheManager.getInstance().addTypeCacheChangedListener(listener);
}
public static void removeTypeCacheChangedListener(ITypeCacheChangedListener listener) {
TypeCacheManager.getInstance().removeTypeCacheChangedListener(listener);
}
public static ITypeInfo getTypeForElement(ICElement element, boolean forceUpdate, boolean forceResolve, IProgressMonitor monitor) {
return TypeCacheManager.getInstance().getTypeForElement(element, forceUpdate, forceResolve, fgEnableIndexing, monitor);
}
public static ICElement getElementForType(ITypeInfo type, boolean forceUpdate, boolean forceResolve, IProgressMonitor monitor) {
return TypeCacheManager.getInstance().getElementForType(type, forceUpdate, forceResolve, fgEnableIndexing, monitor);
}
}

View file

@ -1,32 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.core.resources.IProject;
/**
* A listener which gets notified when the type cache changes.
* <p>
* This interface may be implemented by clients.
* </p>
*/
public interface ITypeCacheChangedListener {
/**
* Notifies that the type cache for the given project has changed in some way
* and should be refreshed at some point to make it consistent with the current
* state of the C model.
*
* @param project the given project
*/
void typeCacheChanged(IProject project);
}

View file

@ -1,209 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.browser.cache.ITypeCache;
import org.eclipse.core.resources.IProject;
/**
* Type information.
*/
public interface ITypeInfo extends Comparable {
public static final int KNOWN_TYPES[] = {
ICElement.C_NAMESPACE,
ICElement.C_CLASS,
ICElement.C_STRUCT,
ICElement.C_UNION,
ICElement.C_ENUMERATION,
ICElement.C_TYPEDEF
};
/**
* Gets the CElement type.
* @return ICElement.C_NAMESPACE, C_CLASS, C_STRUCT, C_UNION, C_ENUMERATION, or C_TYPEDEF,
* or zero if unknown type.
*/
public int getCElementType();
/**
* Sets the CElement type.
*/
public void setCElementType(int type);
/**
* Gets the type name.
*/
public String getName();
/**
* Gets the qualified type name.
*/
public IQualifiedTypeName getQualifiedTypeName();
/**
* Returns true if the type exists.
*/
public boolean exists();
/**
* Returns true if the element type is unknown.
*/
public boolean isUndefinedType();
/**
* Returns true if this type is enclosed by other types,
* i.e. declared an inside another namespace or class.
*/
public boolean isEnclosedType();
/** Gets the enclosing type, i.e. the outer class or namespace which contains this type.
* @return the enclosing type, or <code>null</code> if not found.
*/
public ITypeInfo getEnclosingType();
/** Gets the enclosing namespace for this type.
* @return the enclosing namespace, or <code>null</code> if none exists.
*/
public ITypeInfo getEnclosingNamespace(boolean includeGlobalNamespace);
/** Gets the first enclosing type which matches one of the given kinds.
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT
* @return the enclosing type, or <code>null</code> if not found.
*/
public ITypeInfo getEnclosingType(int[] kinds);
/** Gets the root namespace, i.e. the outermost namespace
* which contains this type.
* @param includeGlobalNamespace <code>true</code> if the global (default) namespace should be returned
* @return the namespace, or <code>null</code> if not found.
*/
public ITypeInfo getRootNamespace(boolean includeGlobalNamespace);
/**
* Returns true if this type is capable of enclosing other types,
* i.e. it is a namespace, class, or struct.
*/
public boolean isEnclosingType();
/**
* Returns true if this type encloses other types, i.e. contains
* inner classes or namespaces.
*/
public boolean hasEnclosedTypes();
/**
* Returns true if this type encloses the given type.
*/
public boolean encloses(ITypeInfo info);
/**
* Returns true if this type is enclosed by the given type.
*/
public boolean isEnclosed(ITypeInfo info);
/** Gets the enclosed types, i.e. inner classes or classes inside this namespace.
* @return array of inner types, or empty array if not found.
*/
public ITypeInfo[] getEnclosedTypes();
/** Gets the enclosed types, i.e. inner classes or classes inside this namespace.
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT,
* C_UNION, C_ENUMERATION, C_TYPEDEF
* @return array of inner types, or empty array if not found.
*/
public ITypeInfo[] getEnclosedTypes(int kinds[]);
/**
* Gets the enclosing project.
*/
public IProject getEnclosingProject();
/**
* Returns true if type is enclosed in the given scope.
*/
public boolean isEnclosed(ITypeSearchScope scope);
/**
* Adds a source reference.
*/
public void addReference(ITypeReference location);
/** Gets the originating locations where this type was declared.
* @return all known source references, or an empty
* array if none found.
*/
public ITypeReference[] getReferences();
/** Gets the real location where type was declared.
* @return the parsed source reference (with offset and length),
* or <code>null</code> if not found.
*/
public ITypeReference getResolvedReference();
/**
* Returns true if the type can be substituted.
*/
public boolean canSubstituteFor(ITypeInfo info);
public ITypeCache getCache();
public void setCache(ITypeCache typeCache);
/**
* Returns true if other types extend this type.
*/
public boolean hasSubTypes();
/** Gets all types which extend this type.
* @return array of types, or <code>null</code> if none found.
*/
public ITypeInfo[] getSubTypes();
/**
* Returns true if this type has base classes.
*/
public boolean hasSuperTypes();
/** Gets the base classes.
* @return array of types, or <code>null</code> if none found.
*/
public ITypeInfo[] getSuperTypes();
/**
* Gets the base class access visibility (PRIVATE, PROTECTED, PUBLIC)
*/
public ASTAccessVisibility getSuperTypeAccess(ITypeInfo subType);
/**
* Adds a derived class reference, i.e. this type is used as
* a base class at the given location.
*/
public void addDerivedReference(ITypeReference location);
/** Gets the originating locations where this type was
* used as a base class.
* @return all known source references, or an empty
* array if none found.
*/
public ITypeReference[] getDerivedReferences();
/**
* Returns true if the type is a class or struct.
*/
public boolean isClass();
/**
* Returns true if type is referenced in the given scope.
*/
public boolean isReferenced(ITypeSearchScope scope);
}

View file

@ -1,18 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
public interface ITypeInfoVisitor {
public boolean visit(ITypeInfo info);
public boolean shouldContinue();
}

View file

@ -1,91 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
public interface ITypeReference {
/**
* Returns the full, absolute path of this reference
* relative to the workspace, or null if no path can be
* determined.
*/
public IPath getPath();
/**
* Returns the absolute path in the local file system
* to this reference, or null if no path can be
* determined.
*/
public IPath getLocation();
/**
* Returns the resource.
*/
public IResource getResource();
/**
* Returns the working copy.
*/
public IWorkingCopy getWorkingCopy();
/**
* Returns the project.
*/
public IProject getProject();
/**
* Returns the offset.
*/
public int getOffset();
/**
* Returns the length.
*/
public int getLength();
/**
* Returns the CElements located at the stored offset and length,
* or <code>null</code> if not found.
*/
public ICElement[] getCElements();
/**
* Returns a translation unit for this location.
*/
public ITranslationUnit getTranslationUnit();
/** Gets the path for this location, relative to one of
* the given project's include paths.
*
* @param project the project to use as a reference.
* @return The path to this location, relative to the longest
* matching include path in the given project.
*/
public IPath getRelativeIncludePath(IProject project);
/** Gets the path for this location, relative to the
* given path.
*
* @param relativeToPath the path to use as a reference.
* @return The path to this location, relative to the
* given path.
*/
public IPath getRelativePath(IPath relativeToPath);
boolean isLineNumber();
}

View file

@ -1,47 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import java.util.Collection;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
public interface ITypeSearchScope {
public boolean isPathScope();
public boolean isProjectScope();
public boolean isWorkspaceScope();
public boolean isEmpty();
public boolean encloses(ITypeSearchScope scope);
public boolean encloses(IProject project);
public boolean encloses(IPath path);
public boolean encloses(String path);
public boolean encloses(ICElement element);
public boolean encloses(IWorkingCopy workingCopy);
public void add(IWorkingCopy workingCopy);
public void add(IPath path, boolean addSubfolders, IProject enclosingProject);
public void add(IProject project);
public void add(ICElement elem);
public void add(ITypeSearchScope scope);
public void addWorkspace();
public void clear();
public IProject[] getEnclosingProjects();
public Collection pathSet();
public Collection containerSet();
public Collection projectSet();
public Collection enclosingProjectSet();
}

View file

@ -1,330 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.browser.cache.ITypeCache;
import org.eclipse.cdt.internal.core.browser.util.ArrayUtil;
import org.eclipse.core.resources.IProject;
public class TypeInfo implements ITypeInfo
{
protected ITypeCache fTypeCache;
protected int fElementType;
protected IQualifiedTypeName fQualifiedName;
protected ITypeReference[] fSourceRefs = null;
protected int fSourceRefsCount = 0;
protected ITypeReference[] fDerivedSourceRefs = null;
protected int fDerivedSourceRefsCount = 0;
protected final static int INITIAL_REFS_SIZE = 1;
protected final static int REFS_GROW_BY = 2;
protected final static ITypeInfo[] EMPTY_TYPES = new ITypeInfo[0];
public TypeInfo(int elementType, IQualifiedTypeName typeName) {
fElementType = elementType;
fQualifiedName = typeName;
}
public void addReference(ITypeReference location) {
if (fSourceRefs == null) {
fSourceRefs = new ITypeReference[INITIAL_REFS_SIZE];
fSourceRefsCount = 0;
} else if (fSourceRefsCount == fSourceRefs.length) {
ITypeReference[] refs = new ITypeReference[fSourceRefs.length + REFS_GROW_BY];
System.arraycopy(fSourceRefs, 0, refs, 0, fSourceRefsCount);
fSourceRefs = refs;
}
fSourceRefs[fSourceRefsCount] = location;
++fSourceRefsCount;
}
public ITypeReference[] getReferences() {
if (fSourceRefs != null) {
ITypeReference[] refs = new ITypeReference[fSourceRefsCount];
System.arraycopy(fSourceRefs, 0, refs, 0, fSourceRefsCount);
return refs;
}
return null;
}
public ITypeReference getResolvedReference() {
for (int i = 0; i < fSourceRefsCount; ++i) {
ITypeReference location = fSourceRefs[i];
if (location.isLineNumber() )
return location;
if( location.getLength() != 0) {
return location;
}
}
return null;
}
public boolean isReferenced() {
return (fSourceRefs != null || fDerivedSourceRefs != null);
}
public boolean isReferenced(ITypeSearchScope scope) {
if (scope == null || scope.isWorkspaceScope())
return true;
// check if path is in scope
for (int i = 0; i < fSourceRefsCount; ++i) {
ITypeReference location = fSourceRefs[i];
if (scope.encloses(location.getPath()))
return true;
}
for (int i = 0; i < fDerivedSourceRefsCount; ++i) {
ITypeReference location = fDerivedSourceRefs[i];
if (scope.encloses(location.getPath()))
return true;
}
return false;
}
public boolean isUndefinedType() {
return fElementType == 0;
}
public boolean canSubstituteFor(ITypeInfo info) {
return isExactMatch(info);
}
protected boolean isExactMatch(ITypeInfo info) {
if (hashCode() != info.hashCode())
return false;
if (fElementType == info.getCElementType()
&& fQualifiedName.equals(info.getQualifiedTypeName())) {
IProject project1 = getEnclosingProject();
IProject project2 = info.getEnclosingProject();
if (project1 == null && project2 == null)
return true;
if (project1 == null || project2 == null)
return false;
return project1.equals(project2);
}
return false;
}
public boolean exists() {
return fTypeCache != null;
}
public int getCElementType() {
return fElementType;
}
public void setCElementType(int type) {
fElementType = type;
}
public IQualifiedTypeName getQualifiedTypeName() {
return fQualifiedName;
}
public String getName() {
return fQualifiedName.getName();
}
public boolean isEnclosedType() {
return (fQualifiedName.isQualified());
}
public ITypeInfo getEnclosingType(int kinds[]) {
if (fTypeCache != null) {
return fTypeCache.getEnclosingType(this, kinds);
}
return null;
}
public ITypeInfo getEnclosingType() {
return getEnclosingType(KNOWN_TYPES);
}
public ITypeInfo getEnclosingNamespace(boolean includeGlobalNamespace) {
if (fTypeCache != null) {
return fTypeCache.getEnclosingNamespace(this, includeGlobalNamespace);
}
return null;
}
public ITypeInfo getRootNamespace(boolean includeGlobalNamespace) {
if (fTypeCache != null) {
return fTypeCache.getRootNamespace(this, includeGlobalNamespace);
}
return null;
}
public boolean isEnclosingType() {
return (fElementType == ICElement.C_NAMESPACE
|| fElementType == ICElement.C_CLASS
|| fElementType == ICElement.C_STRUCT);
}
public boolean encloses(ITypeInfo info) {
if (isEnclosingType() && fTypeCache == info.getCache()) {
return fQualifiedName.isPrefixOf(info.getQualifiedTypeName());
}
return false;
}
public boolean isEnclosed(ITypeInfo info) {
return info.encloses(this);
}
public boolean hasEnclosedTypes() {
if (isEnclosingType() && fTypeCache != null) {
return fTypeCache.hasEnclosedTypes(this);
}
return false;
}
public ITypeInfo[] getEnclosedTypes() {
return getEnclosedTypes(KNOWN_TYPES);
}
public ITypeInfo[] getEnclosedTypes(int kinds[]) {
if (fTypeCache != null) {
return fTypeCache.getEnclosedTypes(this, kinds);
}
return EMPTY_TYPES;
}
public IProject getEnclosingProject() {
if (fTypeCache != null) {
return fTypeCache.getProject();
}
return null;
}
public String toString() {
return fQualifiedName.toString();
}
public boolean isEnclosed(ITypeSearchScope scope) {
if (scope == null || scope.isWorkspaceScope())
return true;
// check if path is in scope
for (int i = 0; i < fSourceRefsCount; ++i) {
ITypeReference location = fSourceRefs[i];
if (scope.encloses(location.getPath()))
return true;
}
return false;
}
public int hashCode() {
int hashCode = fQualifiedName.hashCode() + fElementType;
IProject project = getEnclosingProject();
if (project != null)
hashCode += project.hashCode();
return hashCode;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof TypeInfo)) {
return false;
}
return isExactMatch((TypeInfo)obj);
}
public int compareTo(Object obj) {
if (obj == this) {
return 0;
}
if( !(obj instanceof TypeInfo)) {
throw new ClassCastException();
}
TypeInfo info= (TypeInfo)obj;
if (fElementType != info.fElementType)
return (fElementType < info.fElementType) ? -1 : 1;
return fQualifiedName.compareTo(info.getQualifiedTypeName());
}
public static boolean isValidType(int type) {
return ArrayUtil.contains(KNOWN_TYPES, type);
}
public ITypeCache getCache() {
return fTypeCache;
}
public void setCache(ITypeCache typeCache) {
fTypeCache = typeCache;
}
public void addDerivedReference(ITypeReference location) {
if (fDerivedSourceRefs == null) {
fDerivedSourceRefs = new ITypeReference[INITIAL_REFS_SIZE];
fDerivedSourceRefsCount = 0;
} else if (fDerivedSourceRefsCount == fDerivedSourceRefs.length) {
ITypeReference[] refs = new ITypeReference[fDerivedSourceRefs.length + REFS_GROW_BY];
System.arraycopy(fDerivedSourceRefs, 0, refs, 0, fDerivedSourceRefsCount);
fDerivedSourceRefs = refs;
}
fDerivedSourceRefs[fDerivedSourceRefsCount] = location;
++fDerivedSourceRefsCount;
}
public ITypeReference[] getDerivedReferences() {
if (fDerivedSourceRefs != null) {
ITypeReference[] refs = new ITypeReference[fDerivedSourceRefsCount];
System.arraycopy(fDerivedSourceRefs, 0, refs, 0, fDerivedSourceRefsCount);
return refs;
}
return null;
}
public boolean hasSubTypes() {
return (fDerivedSourceRefs != null);
}
public ITypeInfo[] getSubTypes() {
if (fTypeCache != null) {
return fTypeCache.getSubtypes(this);
}
return null;
}
public boolean hasSuperTypes() {
if (fTypeCache != null) {
return (fTypeCache.getSupertypes(this) != null);
}
return false;
// return true; //TODO can't know this until we parse
}
public ITypeInfo[] getSuperTypes() {
if (fTypeCache != null) {
return fTypeCache.getSupertypes(this);
}
return null;
}
public ASTAccessVisibility getSuperTypeAccess(ITypeInfo superType) {
if (fTypeCache != null) {
return fTypeCache.getSupertypeAccess(this, superType);
}
return null;
}
public boolean isClass() {
return (fElementType == ICElement.C_CLASS
|| fElementType == ICElement.C_STRUCT);
}
}

View file

@ -1,245 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
public class TypeReference implements ITypeReference {
private IPath fPath;
private IProject fProject;
private IResource fResource;
private IWorkingCopy fWorkingCopy;
private int fOffset;
private int fLength;
public boolean offsetIsLineNumber = false;
public TypeReference(IPath path, IProject project, int offset, int length) {
fPath = path;
fProject = project;
fWorkingCopy = null;
fResource = null;
fOffset = offset;
fLength = length;
}
public TypeReference(IResource resource, IProject project, int offset, int length) {
fPath = null;
fProject = project;
fWorkingCopy = null;
fResource = resource;
fOffset = offset;
fLength = length;
}
public TypeReference(IWorkingCopy workingCopy, IProject project, int offset, int length) {
fPath = null;
fProject = project;
fWorkingCopy = workingCopy;
fResource = null;
fOffset = offset;
fLength = length;
}
public TypeReference(IPath path, IProject project) {
this(path, project, 0, 0);
}
public TypeReference(IResource resource, IProject project) {
this(resource, project, 0, 0);
}
public TypeReference(IWorkingCopy workingCopy, IProject project) {
this(workingCopy, project, 0, 0);
}
public IPath getPath() {
if (fWorkingCopy != null) {
return fWorkingCopy.getPath();
} else if (fResource != null) {
return fResource.getFullPath();
} else {
return fPath;
}
}
public IPath getLocation() {
if (fWorkingCopy != null) {
IResource resource = fWorkingCopy.getUnderlyingResource();
if (resource != null) {
return resource.getLocation();
}
return null;
} else if (fResource != null) {
return fResource.getLocation();
} else if (fPath != null) {
return fPath;
} else if (fProject != null) {
return fProject.getLocation();
} else {
return null;
}
}
public IResource getResource() {
return fResource;
}
public IWorkingCopy getWorkingCopy() {
return fWorkingCopy;
}
public IProject getProject() {
if (fProject != null) {
return fProject;
}
if (fWorkingCopy != null) {
ICProject cProject = fWorkingCopy.getCProject();
if (cProject != null) {
return cProject.getProject();
}
return null;
} else if (fResource != null) {
return fResource.getProject();
} else {
return null;
}
}
public ITranslationUnit getTranslationUnit() {
ITranslationUnit unit = null;
if (fWorkingCopy != null) {
unit = fWorkingCopy.getTranslationUnit();
} else if (fResource != null) {
ICElement elem = CoreModel.getDefault().create(fResource);
if (elem instanceof ITranslationUnit)
unit = (ITranslationUnit) elem;
} else {
IPath path = getLocation();
ICElement elem = CoreModel.getDefault().create(path);
if (elem instanceof ITranslationUnit)
unit = (ITranslationUnit) elem;
}
if (unit == null) {
IProject project = getProject();
if (project != null) {
ICProject cProject = findCProject(project);
if (cProject != null) {
IPath path = getLocation();
ICElement elem = CoreModel.getDefault().createTranslationUnitFrom(cProject, path);
if (elem instanceof ITranslationUnit)
unit = (ITranslationUnit) elem;
}
}
}
return unit;
}
private ICProject findCProject(IProject project) {
try {
ICProject[] cProjects = CoreModel.getDefault().getCModel().getCProjects();
if (cProjects != null) {
for (int i = 0; i < cProjects.length; ++i) {
ICProject cProject = cProjects[i];
if (project.equals(cProjects[i].getProject()))
return cProject;
}
}
} catch (CModelException e) {
}
return null;
}
public ICElement[] getCElements() {
ITranslationUnit unit = getTranslationUnit();
if (unit != null) {
try {
if( offsetIsLineNumber )
{
ICElement [] result = new ICElement[1];
result[0] = unit.getElementAtLine(fOffset);
return result;
}
return unit.getElementsAtOffset(fOffset);
} catch (CModelException e) {
}
}
return null;
}
public int getOffset() {
return fOffset;
}
public int getLength() {
return fLength;
}
public IPath getRelativeIncludePath(IProject project) {
IPath path = getLocation();
if (path != null) {
IPath relativePath = PathUtil.makeRelativePathToProjectIncludes(path, project);
if (relativePath != null)
return relativePath;
}
return path;
}
public IPath getRelativePath(IPath relativeToPath) {
IPath path = getPath();
if (path != null) {
IPath relativePath = PathUtil.makeRelativePath(path, relativeToPath);
if (relativePath != null)
return relativePath;
}
return path;
}
public String toString() {
IPath path = getLocation();
if (path != null) {
if (fLength == 0 && fOffset == 0) {
return path.toString();
}
return path.toString() + ":" + fOffset + "-" + (fOffset + fLength); //$NON-NLS-1$//$NON-NLS-2$
}
return ""; //$NON-NLS-1$
}
public int hashCode() {
return toString().hashCode();
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ITypeReference)) {
return false;
}
ITypeReference ref = (ITypeReference)obj;
return toString().equals(ref.toString());
}
public boolean isLineNumber() {
return offsetIsLineNumber;
}
}

View file

@ -1,419 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.CProjectNature;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IScannerInfoProvider;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
public class TypeSearchScope implements ITypeSearchScope {
private Set fPathSet = new HashSet();
private Set fContainerSet = new HashSet();
private Set fProjectSet = new HashSet();
private Set fEnclosingProjectSet = new HashSet();
private boolean fWorkspaceScope = false;
// cached arrays
private IProject[] fAllProjects = null;
private IProject[] fProjects = null;
private IPath[] fContainerPaths = null;
public TypeSearchScope() {
}
public TypeSearchScope(boolean workspaceScope) {
fWorkspaceScope = workspaceScope;
}
public TypeSearchScope(ITypeSearchScope scope) {
add(scope);
}
public TypeSearchScope(IProject project) {
add(project);
}
public Collection pathSet() {
return fPathSet;
}
public Collection containerSet() {
return fContainerSet;
}
public Collection projectSet() {
return fProjectSet;
}
public Collection enclosingProjectSet() {
return fEnclosingProjectSet;
}
public boolean encloses(ITypeSearchScope scope) {
if (isWorkspaceScope())
return true;
if (!scope.pathSet().isEmpty()) {
// check if this scope encloses the other scope's paths
for (Iterator i = scope.pathSet().iterator(); i.hasNext(); ) {
IPath path = (IPath) i.next();
if (!encloses(path))
return false;
}
}
if (!scope.containerSet().isEmpty()) {
// check if this scope encloses the other scope's containers
for (Iterator i = scope.containerSet().iterator(); i.hasNext(); ) {
IPath path = (IPath) i.next();
if (!encloses(path))
return false;
}
}
if (!scope.projectSet().isEmpty()) {
// check if this scope encloses the other scope's projects
for (Iterator i = scope.projectSet().iterator(); i.hasNext(); ) {
IProject project = (IProject) i.next();
if (!encloses(project))
return false;
}
}
return true;
}
public boolean encloses(IProject project) {
if (isWorkspaceScope())
return true;
// check projects that were explicity added to scope
if (fProjectSet.contains(project))
return true;
return false;
}
public boolean encloses(IPath path) {
if (isWorkspaceScope())
return true;
// check files that were explicity added to scope
if (fPathSet.contains(path))
return true;
// check containers that were explicity added to scope
// including subdirs
if (fContainerSet.contains(path))
return true;
if (fContainerPaths == null) {
fContainerPaths = (IPath[]) fContainerSet.toArray(new IPath[fContainerSet.size()]);
// java.util.Arrays.sort(fContainerPaths);
}
for (int i = 0; i < fContainerPaths.length; ++i) {
if (fContainerPaths[i].isPrefixOf(path)) {
return true;
}
}
// check projects that were explicity added to scope
if (fProjectSet.contains(path))
return true;
// check projects that were explicity added to scope
if (fProjects == null) {
fProjects = (IProject[]) fProjectSet.toArray(new IProject[fProjectSet.size()]);
}
// check if one of the projects contains path
for (int i = 0; i < fProjects.length; ++i) {
if (projectContainsPath(fProjects[i], path, false)) {
return true;
}
}
return false;
}
public boolean encloses(String path) {
return encloses(new Path(path));
}
public boolean encloses(ICElement element) {
return encloses(element.getPath());
}
public boolean encloses(IWorkingCopy workingCopy) {
return encloses(workingCopy.getOriginalElement().getPath());
}
public IProject[] getEnclosingProjects() {
if (isWorkspaceScope()) {
return getAllProjects();
}
return (IProject[]) fEnclosingProjectSet.toArray(new IProject[fEnclosingProjectSet.size()]);
}
private static boolean projectContainsPath(IProject project, IPath path, boolean checkIncludePaths) {
IPath projectPath = project.getFullPath();
if (projectPath.isPrefixOf(path)) {
// ISourceRoot[] sourceRoots = null;
// try {
// sourceRoots = cProject.getSourceRoots();
// } catch (CModelException ex) {
// }
// if (sourceRoots != null) {
// for (int j = 0; j < sourceRoots.length; ++j) {
// ISourceRoot root = sourceRoots[j];
// if (root.isOnSourceEntry(path))
// return true;
// }
// }
return true;
}
if (checkIncludePaths) {
//TODO this appears to be very slow -- cache this?
IPath[] includePaths = getIncludePaths(project);
if (includePaths != null) {
for (int i = 0; i < includePaths.length; ++i) {
IPath include = includePaths[i];
if (include.isPrefixOf(path) || include.equals(path))
return true;
}
}
}
return false;
}
private static IPath[] getIncludePaths(IProject project) {
IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project);
if (provider != null) {
IScannerInfo info = provider.getScannerInformation(project);
if (info != null) {
String[] includes = info.getIncludePaths();
if (includes != null && includes.length > 0) {
IPath[] includePaths = new IPath[includes.length];
for (int i = 0; i < includes.length; ++i) {
includePaths[i] = new Path(includes[i]);
}
// java.util.Arrays.sort(includePaths);
return includePaths;
}
}
}
return null;
}
private static IProject[] getAllProjects() {
IProject[] projects = getCProjects();
if (projects == null)
projects = new IProject[0];
return projects;
}
private static IProject[] getCProjects() {
IProject[] allProjects = CCorePlugin.getWorkspace().getRoot().getProjects();
if (allProjects != null) {
IProject[] cProjects = new IProject[allProjects.length];
int count = 0;
for (int i = 0; i < allProjects.length; ++i) {
IProject project = allProjects[i];
if (isCProject(project)) {
cProjects[count++] = project;
}
}
if (count > 0) {
if (count == allProjects.length) {
return cProjects;
}
IProject[] newProjects = new IProject[count];
System.arraycopy(cProjects, 0, newProjects, 0, count);
return newProjects;
}
}
return null;
}
private static boolean isCProject(IProject project) {
IProjectDescription projDesc = null;
try {
projDesc = project.getDescription();
if (projDesc == null)
return false;
} catch (CoreException e) {
return false;
}
String[] natures = projDesc.getNatureIds();
if (natures != null) {
for (int i = 0; i < natures.length; ++i) {
if (natures[i].equals(CProjectNature.C_NATURE_ID)) {
return true;
}
}
}
return false;
}
public boolean isPathScope() {
return !fPathSet.isEmpty();
}
public boolean isProjectScope() {
return !fProjectSet.isEmpty();
}
public boolean isWorkspaceScope() {
return fWorkspaceScope;
}
public boolean isEmpty() {
return (!isWorkspaceScope() && fPathSet.isEmpty() && fContainerSet.isEmpty() && fProjectSet.isEmpty());
}
public void add(IWorkingCopy workingCopy) {
IPath path = workingCopy.getOriginalElement().getPath();
IProject enclosingProject = null;
ICProject cProject = workingCopy.getCProject();
if (cProject != null)
enclosingProject = cProject.getProject();
fPathSet.add(path);
if (enclosingProject != null)
addEnclosingProject(enclosingProject);
}
public void add(IPath path, boolean addSubfolders, IProject enclosingProject) {
if (addSubfolders) {
fContainerSet.add(path);
fContainerPaths = null;
} else {
fPathSet.add(path);
}
if (enclosingProject != null) {
addEnclosingProject(enclosingProject);
} else {
// check all projects in workspace
if (fAllProjects == null) {
fAllProjects = getAllProjects();
}
// check if one of the projects contains path
for (int i = 0; i < fAllProjects.length; ++i) {
if (projectContainsPath(fAllProjects[i], path, false)) {
addEnclosingProject(fAllProjects[i]);
break;
}
}
}
}
public void add(IProject project) {
fProjectSet.add(project);
fProjects = null;
fAllProjects = null;
addEnclosingProject(project);
}
private void addEnclosingProject(IProject project) {
fEnclosingProjectSet.add(project);
}
public void addWorkspace() {
fWorkspaceScope = true;
fProjects = null;
fAllProjects = null;
}
public void add(ICElement elem) {
if (elem == null)
return;
switch (elem.getElementType()) {
case ICElement.C_MODEL: {
addWorkspace();
break;
}
case ICElement.C_PROJECT: {
IProject project = ((ICProject)elem).getProject();
add(project);
break;
}
case ICElement.C_CCONTAINER: {
IProject project = null;
ICProject cProject = elem.getCProject();
if (cProject != null)
project = cProject.getProject();
add(elem.getPath(), true, project);
break;
}
case ICElement.C_UNIT: {
IProject project = null;
ICProject cProject = elem.getCProject();
if (cProject != null)
project = cProject.getProject();
add(elem.getPath(), false, project);
break;
}
case ICElement.C_INCLUDE:
case ICElement.C_NAMESPACE:
case ICElement.C_TEMPLATE_CLASS:
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
case ICElement.C_UNION:
case ICElement.C_ENUMERATION:
case ICElement.C_TYPEDEF: {
IProject project = null;
ICProject cProject = elem.getCProject();
if (cProject != null)
project = cProject.getProject();
add(elem.getPath(), false, project);
break;
}
}
}
public void add(ITypeSearchScope scope) {
fPathSet.addAll(scope.pathSet());
fContainerSet.addAll(scope.containerSet());
fProjectSet.addAll(scope.projectSet());
fEnclosingProjectSet.addAll(scope.enclosingProjectSet());
fProjects = null;
fAllProjects = null;
fContainerPaths = null;
fWorkspaceScope |= scope.isWorkspaceScope();
}
public void clear() {
fPathSet.clear();
fContainerSet.clear();
fProjectSet.clear();
fEnclosingProjectSet.clear();
fWorkspaceScope = false;
fProjects = null;
fAllProjects = null;
fContainerPaths = null;
}
}

View file

@ -1,41 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser;
import org.eclipse.core.runtime.IPath;
public class UnknownTypeInfo extends TypeInfo {
public UnknownTypeInfo(String name, IPath path) {
this(new QualifiedTypeName(name));
if (path != null) {
addReference(new TypeReference(path, null));
}
}
public UnknownTypeInfo(IQualifiedTypeName typeName) {
super(0, typeName);
}
public boolean isUndefinedType() {
return true;
}
public boolean canSubstituteFor(ITypeInfo info) {
if (fTypeCache == info.getCache()) {
int compareType = info.getCElementType();
if (fElementType == 0 || compareType == 0 || fElementType == compareType) {
return fQualifiedName.equals(info.getQualifiedTypeName());
}
}
return false;
}
}

View file

@ -1,451 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.eclipse.cdt.core.browser.TypeUtil;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.model.IMember;
import org.eclipse.cdt.core.model.IParent;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.core.model.CElement;
/*
* Collects changes (reported through fine-grained deltas) that can affect a type hierarchy.
*/
public class ChangeCollector {
/*
* A table from ICElements to TypeDeltas
*/
HashMap changes = new HashMap();
TypeHierarchy hierarchy;
public ChangeCollector(TypeHierarchy hierarchy) {
this.hierarchy = hierarchy;
}
/*
* Adds the children of the given delta to the list of changes.
*/
private void addAffectedChildren(ICElementDelta delta) throws CModelException {
// ICElementDelta[] children = delta.getAffectedChildren();
// for (int i = 0, length = children.length; i < length; i++) {
// ICElementDelta child = children[i];
// ICElement childElement = child.getElement();
// switch (childElement.getElementType()) {
// case ICElement.IMPORT_CONTAINER:
// addChange((IImportContainer)childElement, child);
// break;
// case ICElement.IMPORT_DECLARATION:
// addChange((IImportDeclaration)childElement, child);
// break;
// case ICElement.TYPE:
// addChange((ICElement)childElement, child);
// break;
// case ICElement.INITIALIZER:
// case ICElement.FIELD:
// case ICElement.METHOD:
// addChange((IMember)childElement, child);
// break;
// }
// }
}
/*
* Adds the given delta on a compilation unit to the list of changes.
*/
public void addChange(ITranslationUnit cu, ICElementDelta newDelta) throws CModelException {
// int newKind = newDelta.getKind();
// switch (newKind) {
// case ICElementDelta.ADDED:
// ArrayList allTypes = new ArrayList();
// getAllTypesFromElement(cu, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement type = (ICElement)allTypes.get(i);
// addTypeAddition(type, (SimpleDelta)this.changes.get(type));
// }
// break;
// case ICElementDelta.REMOVED:
// allTypes = new ArrayList();
// getAllTypesFromHierarchy((JavaElement)cu, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement type = (ICElement)allTypes.get(i);
// addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
// }
// break;
// case ICElementDelta.CHANGED:
// addAffectedChildren(newDelta);
// break;
// }
}
/* private void addChange(IImportContainer importContainer, ICElementDelta newDelta) throws CModelException {
int newKind = newDelta.getKind();
if (newKind == ICElementDelta.CHANGED) {
addAffectedChildren(newDelta);
return;
}
SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importContainer);
if (existingDelta != null) {
switch (newKind) {
case ICElementDelta.ADDED:
if (existingDelta.getKind() == ICElementDelta.REMOVED) {
// REMOVED then ADDED
this.changes.remove(importContainer);
}
break;
case ICElementDelta.REMOVED:
if (existingDelta.getKind() == ICElementDelta.ADDED) {
// ADDED then REMOVED
this.changes.remove(importContainer);
}
break;
// CHANGED handled above
}
} else {
SimpleDelta delta = new SimpleDelta();
switch (newKind) {
case ICElementDelta.ADDED:
delta.added();
break;
case ICElementDelta.REMOVED:
delta.removed();
break;
}
this.changes.put(importContainer, delta);
}
}
private void addChange(IImportDeclaration importDecl, ICElementDelta newDelta) {
SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importDecl);
int newKind = newDelta.getKind();
if (existingDelta != null) {
switch (newKind) {
case ICElementDelta.ADDED:
if (existingDelta.getKind() == ICElementDelta.REMOVED) {
// REMOVED then ADDED
this.changes.remove(importDecl);
}
break;
case ICElementDelta.REMOVED:
if (existingDelta.getKind() == ICElementDelta.ADDED) {
// ADDED then REMOVED
this.changes.remove(importDecl);
}
break;
// CHANGED cannot happen for import declaration
}
} else {
SimpleDelta delta = new SimpleDelta();
switch (newKind) {
case ICElementDelta.ADDED:
delta.added();
break;
case ICElementDelta.REMOVED:
delta.removed();
break;
}
this.changes.put(importDecl, delta);
}
}
*/
/*
* Adds a change for the given member (a method, a field or an initializer) and the types it defines.
*/
private void addChange(IMember member, ICElementDelta newDelta) throws CModelException {
// int newKind = newDelta.getKind();
// switch (newKind) {
// case ICElementDelta.ADDED:
// ArrayList allTypes = new ArrayList();
// getAllTypesFromElement(member, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement innerType = (ICElement)allTypes.get(i);
// addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
// }
// break;
// case ICElementDelta.REMOVED:
// allTypes = new ArrayList();
// getAllTypesFromHierarchy((JavaElement)member, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement type = (ICElement)allTypes.get(i);
// addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
// }
// break;
// case ICElementDelta.CHANGED:
// addAffectedChildren(newDelta);
// break;
// }
}
/*
* Adds a change for the given type and the types it defines.
*/
private void addChange(ICElement type, ICElementDelta newDelta) throws CModelException {
// int newKind = newDelta.getKind();
// SimpleDelta existingDelta = (SimpleDelta)this.changes.get(type);
// switch (newKind) {
// case ICElementDelta.ADDED:
// addTypeAddition(type, existingDelta);
// ArrayList allTypes = new ArrayList();
// getAllTypesFromElement(type, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement innerType = (ICElement)allTypes.get(i);
// addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
// }
// break;
// case ICElementDelta.REMOVED:
// addTypeRemoval(type, existingDelta);
// allTypes = new ArrayList();
// getAllTypesFromHierarchy((JavaElement)type, allTypes);
// for (int i = 0, length = allTypes.size(); i < length; i++) {
// ICElement innerType = (ICElement)allTypes.get(i);
// addTypeRemoval(innerType, (SimpleDelta)this.changes.get(innerType));
// }
// break;
// case ICElementDelta.CHANGED:
// addTypeChange(type, newDelta.getFlags(), existingDelta);
// addAffectedChildren(newDelta);
// break;
// }
}
/* private void addTypeAddition(ICElement type, SimpleDelta existingDelta) throws CModelException {
if (existingDelta != null) {
switch (existingDelta.getKind()) {
case ICElementDelta.REMOVED:
// REMOVED then ADDED
boolean hasChange = false;
if (hasSuperTypeChange(type)) {
existingDelta.superTypes();
hasChange = true;
}
if (hasVisibilityChange(type)) {
existingDelta.modifiers();
hasChange = true;
}
if (!hasChange) {
this.changes.remove(type);
}
break;
// CHANGED then ADDED
// or ADDED then ADDED: should not happen
}
} else {
// check whether the type addition affects the hierarchy
String typeName = type.getElementName();
if (this.hierarchy.hasSupertype(typeName)
|| this.hierarchy.subtypesIncludeSupertypeOf(type)
|| this.hierarchy.missingTypes.contains(typeName)) {
SimpleDelta delta = new SimpleDelta();
delta.added();
this.changes.put(type, delta);
}
}
}
*/
/* private void addTypeChange(ICElement type, int newFlags, SimpleDelta existingDelta) throws CModelException {
if (existingDelta != null) {
switch (existingDelta.getKind()) {
case ICElementDelta.CHANGED:
// CHANGED then CHANGED
int existingFlags = existingDelta.getFlags();
boolean hasChange = false;
if ((existingFlags & ICElementDelta.F_SUPER_TYPES) != 0
&& hasSuperTypeChange(type)) {
existingDelta.superTypes();
hasChange = true;
}
if ((existingFlags & ICElementDelta.F_MODIFIERS) != 0
&& hasVisibilityChange(type)) {
existingDelta.modifiers();
hasChange = true;
}
if (!hasChange) {
// super types and visibility are back to the ones in the existing hierarchy
this.changes.remove(type);
}
break;
// ADDED then CHANGED: leave it as ADDED
// REMOVED then CHANGED: should not happen
}
} else {
// check whether the type change affects the hierarchy
SimpleDelta typeDelta = null;
if ((newFlags & ICElementDelta.F_SUPER_TYPES) != 0
&& this.hierarchy.includesTypeOrSupertype(type)) {
typeDelta = new SimpleDelta();
typeDelta.superTypes();
}
if ((newFlags & ICElementDelta.F_MODIFIERS) != 0
&& this.hierarchy.hasSupertype(type.getElementName())) {
if (typeDelta == null) {
typeDelta = new SimpleDelta();
}
typeDelta.modifiers();
}
if (typeDelta != null) {
this.changes.put(type, typeDelta);
}
}
}
*/
/* private void addTypeRemoval(ICElement type, SimpleDelta existingDelta) {
if (existingDelta != null) {
switch (existingDelta.getKind()) {
case ICElementDelta.ADDED:
// ADDED then REMOVED
this.changes.remove(type);
break;
case ICElementDelta.CHANGED:
// CHANGED then REMOVED
existingDelta.removed();
break;
// REMOVED then REMOVED: should not happen
}
} else {
// check whether the type removal affects the hierarchy
if (this.hierarchy.contains(type)) {
SimpleDelta typeDelta = new SimpleDelta();
typeDelta.removed();
this.changes.put(type, typeDelta);
}
}
}
*/
/*
* Returns all types defined in the given element excluding the given element.
*/
private void getAllTypesFromElement(ICElement element, ArrayList allTypes) throws CModelException {
switch (element.getElementType()) {
case ICElement.C_UNIT:
ICElement[] types = TypeUtil.getTypes((ITranslationUnit)element);
for (int i = 0, length = types.length; i < length; i++) {
ICElement type = types[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
break;
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
// types = ((ICElement)element).getTypes();
types = TypeUtil.getTypes(element);
for (int i = 0, length = types.length; i < length; i++) {
ICElement type = types[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
break;
// case ICElement.INITIALIZER:
// case ICElement.FIELD:
case ICElement.C_METHOD:
if (element instanceof IParent) {
ICElement[] children = ((IParent)element).getChildren();
for (int i = 0, length = children.length; i < length; i++) {
ICElement type = (ICElement)children[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
}
break;
}
}
/*
* Returns all types in the existing hierarchy that have the given element as a parent.
*/
private void getAllTypesFromHierarchy(CElement element, ArrayList allTypes) {
switch (element.getElementType()) {
case ICElement.C_UNIT:
ArrayList types = (ArrayList)this.hierarchy.files.get(element);
if (types != null) {
allTypes.addAll(types);
}
break;
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
// case ICElement.INITIALIZER:
// case ICElement.FIELD:
case ICElement.C_METHOD:
types = (ArrayList)this.hierarchy.files.get(((IMember)element).getTranslationUnit());
if (types != null) {
for (int i = 0, length = types.size(); i < length; i++) {
ICElement type = (ICElement)types.get(i);
if (element.isAncestorOf(type)) {
allTypes.add(type);
}
}
}
break;
}
}
private boolean hasSuperTypeChange(ICElement type) throws CModelException {
// // check super class
// ICElement superclass = this.hierarchy.getSuperclass(type);
// String existingSuperclassName = superclass == null ? null : superclass.getElementName();
// String newSuperclassName = type.getSuperclassName();
// if (existingSuperclassName != null && !existingSuperclassName.equals(newSuperclassName)) {
// return true;
// }
//
// // check super interfaces
// ICElement[] existingSuperInterfaces = this.hierarchy.getSuperInterfaces(type);
// String[] newSuperInterfaces = type.getSuperInterfaceNames();
// if (existingSuperInterfaces.length != newSuperInterfaces.length) {
// return true;
// }
// for (int i = 0, length = newSuperInterfaces.length; i < length; i++) {
// String superInterfaceName = newSuperInterfaces[i];
// if (!superInterfaceName.equals(newSuperInterfaces[i])) {
// return true;
// }
// }
return false;
}
private boolean hasVisibilityChange(ICElement type) throws CModelException {
// int existingFlags = this.hierarchy.getCachedFlags(type);
// int newFlags = type.getFlags();
// return existingFlags != newFlags;
return false;
}
/*
* Whether the hierarchy needs refresh according to the changes collected so far.
*/
public boolean needsRefresh() {
return changes.size() != 0;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
Iterator iterator = this.changes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry)iterator.next();
buffer.append(((CElement)entry.getKey()).toDebugString());
buffer.append(entry.getValue());
if (iterator.hasNext()) {
buffer.append('\n');
}
}
return buffer.toString();
}
}

View file

@ -1,171 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
import java.io.OutputStream;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* A type hierarchy provides navigations between a type and its resolved
* supertypes and subtypes for a specific type or for all types within a region.
* Supertypes may extend outside of the type hierarchy's region in which it was
* created such that the root of the hierarchy is always included. For example, if a type
* hierarchy is created for a <code>java.io.File</code>, and the region the hierarchy was
* created in is the package fragment <code>java.io</code>, the supertype
* <code>java.lang.Object</code> will still be included.
* <p>
* A type hierarchy is static and can become stale. Although consistent when
* created, it does not automatically track changes in the model.
* As changes in the model potentially invalidate the hierarchy, change notifications
* are sent to registered <code>ICElementHierarchyChangedListener</code>s. Listeners should
* use the <code>exists</code> method to determine if the hierarchy has become completely
* invalid (for example, when the type or project the hierarchy was created on
* has been removed). To refresh a hierarchy, use the <code>refresh</code> method.
* </p>
* <p>
* The type hierarchy may contain cycles due to malformed supertype declarations.
* Most type hierarchy queries are oblivious to cycles; the <code>getAll* </code>
* methods are implemented such that they are unaffected by cycles.
* </p>
* <p>
* This interface is not intended to be implemented by clients.
* </p>
*/
public interface ITypeHierarchy {
/**
* Adds the given listener for changes to this type hierarchy. Listeners are
* notified when this type hierarchy changes and needs to be refreshed.
* Has no effect if an identical listener is already registered.
*
* @param listener the listener
*/
void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
/**
* Returns whether the given type is part of this hierarchy.
*
* @param type the given type
* @return true if the given type is part of this hierarchy, false otherwise
*/
boolean contains(ICElement type);
/**
* Returns whether the type and project this hierarchy was created on exist.
* @return true if the type and project this hierarchy was created on exist, false otherwise
*/
boolean exists();
/**
* Returns all resolved subtypes (direct and indirect) of the
* given type, in no particular order, limited to the
* types in this type hierarchy's graph. An empty array
* is returned if there are no resolved subtypes for the
* given type.
*
* @param type the given type
* @return all resolved subtypes (direct and indirect) of the given type
*/
ICElement[] getAllSubtypes(ICElement type);
/**
* Returns all resolved superclasses of the
* given class, in bottom-up order. An empty array
* is returned if there are no resolved superclasses for the
* given class.
*
* <p>NOTE: once a type hierarchy has been created, it is more efficient to
* query the hierarchy for superclasses than to query a class recursively up
* the superclass chain. Querying an element performs a dynamic resolution,
* whereas the hierarchy returns a pre-computed result.
*
* @param type the given type
* @return all resolved superclasses of the given class, in bottom-up order, an empty
* array if none.
*/
ICElement[] getAllSupertypes(ICElement type);
/**
* Returns all classes in the graph which have no resolved superclass,
* in no particular order.
*
* @return all classes in the graph which have no resolved superclass
*/
ICElement[] getRootClasses();
/**
* Returns the direct resolved subtypes of the given type,
* in no particular order, limited to the types in this
* type hierarchy's graph.
* If the type is a class, this returns the resolved subclasses.
* If the type is an interface, this returns both the classes which implement
* the interface and the interfaces which extend it.
*
* @param type the given type
* @return the direct resolved subtypes of the given type limited to the types in this
* type hierarchy's graph
*/
ICElement[] getSubtypes(ICElement type);
/**
* Returns the resolved supertypes of the given type,
* in no particular order, limited to the types in this
* type hierarchy's graph.
* For classes, this returns its superclass and the interfaces that the class implements.
* For interfaces, this returns the interfaces that the interface extends. As a consequence
* <code>java.lang.Object</code> is NOT considered to be a supertype of any interface
* type.
*
* @param type the given type
* @return the resolved supertypes of the given type limited to the types in this
* type hierarchy's graph
*/
ICElement[] getSupertypes(ICElement type);
/**
* Returns the type this hierarchy was computed for.
* Returns <code>null</code> if this hierarchy was computed for a region.
*
* @return the type this hierarchy was computed for
*/
ICElement getType();
/**
* Re-computes the type hierarchy reporting progress.
*
* @param monitor the given progress monitor
* @exception JavaModelException if unable to refresh the hierarchy
*/
void refresh(IProgressMonitor monitor) throws CModelException;
/**
* Removes the given listener from this type hierarchy.
* Has no affect if an identical listener is not registered.
*
* @param listener the listener
*/
void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
/**
* Stores the type hierarchy in an output stream. This stored hierarchy can be load by
* ICElement#loadTypeHierachy(IJavaProject, InputStream, IProgressMonitor).
* Listeners of this hierarchy are not stored.
*
* Only hierarchies created by the following methods can be store:
* <ul>
* <li>ICElement#newSupertypeHierarchy(IProgressMonitor)</li>
* <li>ICElement#newTypeHierarchy(IJavaProject, IProgressMonitor)</li>
* <li>ICElement#newTypeHierarchy(IProgressMonitor)</li>
* </u>
*
* @param outputStream output stream where the hierarchy will be stored
* @param monitor the given progress monitor
* @exception JavaModelException if unable to store the hierarchy in the ouput stream
* @see ICElement#loadTypeHierachy(java.io.InputStream, IProgressMonitor)
* @since 2.1
*/
void store(OutputStream outputStream, IProgressMonitor monitor) throws CModelException;
}

View file

@ -1,29 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
/**
* A listener which gets notified when a particular type hierarchy object
* changes.
* <p>
* This interface may be implemented by clients.
* </p>
*/
public interface ITypeHierarchyChangedListener {
/**
* Notifies that the given type hierarchy has changed in some way and should
* be refreshed at some point to make it consistent with the current state of
* the Java model.
*
* @param typeHierarchy the given type hierarchy
*/
void typeHierarchyChanged(ITypeHierarchy typeHierarchy);
}

View file

@ -1,582 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.ICLogConstants;
import org.eclipse.cdt.core.browser.AllTypesCache;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ElementChangedEvent;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.IElementChangedListener;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.internal.core.model.Util;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.Platform;
public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
public static boolean DEBUG = false;
private static final class TypeEntry {
ITypeInfo type;
ASTAccessVisibility access;
TypeEntry(ITypeInfo type, ASTAccessVisibility access) {
this.type = type;
this.access = access;
}
}
private static final int INITIAL_SUPER_TYPES = 1;
private static final int INITIAL_SUB_TYPES = 1;
private static final ITypeInfo[] NO_TYPES = new ITypeInfo[0];
private ArrayList fRootTypes = new ArrayList();
private Map fTypeToSuperTypes = new HashMap();
private Map fTypeToSubTypes = new HashMap();
private ITypeInfo fFocusType;
/**
* The progress monitor to report work completed too.
*/
protected IProgressMonitor fProgressMonitor = null;
/**
* Change listeners - null if no one is listening.
*/
protected ArrayList fChangeListeners = null;
/*
* A map from Openables to ArrayLists of ITypes
*/
public Map files = null;
/**
* Whether this hierarchy should contains subtypes.
*/
protected boolean fComputeSubtypes;
/**
* The scope this hierarchy should restrain itsef in.
*/
ICSearchScope fScope;
/*
* Whether this hierarchy needs refresh
*/
public boolean fNeedsRefresh = true;
// /*
// * Collects changes to types
// */
// protected ChangeCollector fChangeCollector;
/**
* Creates a TypeHierarchy on the given type.
*/
public TypeHierarchy(ITypeInfo type) {
fFocusType = type;
}
/**
* Adds the type to the collection of root classes
* if the classes is not already present in the collection.
*/
public void addRootType(ITypeInfo type) {
if (!fRootTypes.contains(type)) {
fRootTypes.add(type);
}
}
/**
* Adds the given supertype to the type.
*/
public void addSuperType(ITypeInfo type, ITypeInfo superType, ASTAccessVisibility access) {
Collection superEntries = (Collection) fTypeToSuperTypes.get(type);
if (superEntries == null) {
superEntries = new ArrayList(INITIAL_SUPER_TYPES);
fTypeToSuperTypes.put(type, superEntries);
}
Collection subTypes = (Collection) fTypeToSubTypes.get(superType);
if (subTypes == null) {
subTypes = new ArrayList(INITIAL_SUB_TYPES);
fTypeToSubTypes.put(superType, subTypes);
}
if (!subTypes.contains(type)) {
subTypes.add(type);
}
for (Iterator i = superEntries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
if (entry.type.equals(superType)) {
// update the access
entry.access = access;
return; // don't add if already exists
}
}
TypeEntry typeEntry = new TypeEntry(superType, access);
superEntries.add(typeEntry);
}
/**
* Adds the given subtype to the type.
*/
protected void addSubType(ITypeInfo type, ITypeInfo subType) {
Collection subTypes = (Collection) fTypeToSubTypes.get(type);
if (subTypes == null) {
subTypes = new ArrayList(INITIAL_SUB_TYPES);
fTypeToSubTypes.put(type, subTypes);
}
if (!subTypes.contains(subType)) {
subTypes.add(subType);
}
Collection superEntries = (Collection) fTypeToSuperTypes.get(subType);
if (superEntries == null) {
superEntries = new ArrayList(INITIAL_SUPER_TYPES);
fTypeToSuperTypes.put(subType, superEntries);
}
for (Iterator i = superEntries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
if (entry.type.equals(type))
return; // don't add if already exists
}
// default to private access
TypeEntry typeEntry = new TypeEntry(type, ASTAccessVisibility.PRIVATE);
superEntries.add(typeEntry);
}
/**
* Returns true if type already has the given supertype.
*/
public boolean hasSuperType(ITypeInfo type, ITypeInfo superType) {
Collection entries = (Collection) fTypeToSuperTypes.get(type);
if (entries != null) {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
if (entry.type.equals(superType))
return true;
}
}
return false;
}
/**
* Returns an array of supertypes for the given type - will never return null.
*/
public ITypeInfo[] getSuperTypes(ITypeInfo type) {
Collection entries = (Collection) fTypeToSuperTypes.get(type);
if (entries != null) {
ArrayList superTypes = new ArrayList(INITIAL_SUPER_TYPES);
for (Iterator i = entries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
superTypes.add(entry.type);
}
return (ITypeInfo[])superTypes.toArray(new ITypeInfo[superTypes.size()]);
}
return NO_TYPES;
}
/**
* Returns an array of subtypes for the given type - will never return null.
*/
public ITypeInfo[] getSubTypes(ITypeInfo type) {
Collection subTypes = (Collection) fTypeToSubTypes.get(type);
if (subTypes != null) {
return (ITypeInfo[])subTypes.toArray(new ITypeInfo[subTypes.size()]);
}
return NO_TYPES;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#addTypeHierarchyChangedListener(org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchyChangedListener)
*/
public void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
ArrayList listeners = fChangeListeners;
if (listeners == null) {
fChangeListeners = listeners = new ArrayList();
}
// register with JavaCore to get Java element delta on first listener added
if (listeners.size() == 0) {
CoreModel.getDefault().addElementChangedListener(this);
}
// add listener only if it is not already present
if (listeners.indexOf(listener) == -1) {
listeners.add(listener);
}
}
/**
* @see ITypeHierarchy
*/
public synchronized void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
ArrayList listeners = fChangeListeners;
if (listeners == null) {
return;
}
listeners.remove(listener);
// deregister from JavaCore on last listener removed
if (listeners.isEmpty()) {
CoreModel.getDefault().removeElementChangedListener(this);
}
}
/**
* Determines if the change effects this hierarchy, and fires
* change notification if required.
*/
public void elementChanged(ElementChangedEvent event) {
// type hierarchy change has already been fired
if (fNeedsRefresh) return;
if (isAffected(event.getDelta())) {
fNeedsRefresh = true;
fireChange();
}
}
/**
* Returns true if the given delta could change this type hierarchy
*/
public synchronized boolean isAffected(ICElementDelta delta) {
// ICElement element= delta.getElement();
// switch (element.getElementType()) {
// case ICElement.C_MODEL:
// return isAffectedByCModel(delta, element);
// case ICElement.C_PROJECT:
// return isAffectedByCProject(delta, element);
// case ICElement.C_UNIT:
// return isAffectedByOpenable(delta, element);
// }
// return false;
return true;
}
/**
* Notifies listeners that this hierarchy has changed and needs
* refreshing. Note that listeners can be removed as we iterate
* through the list.
*/
public void fireChange() {
ArrayList listeners = fChangeListeners;
if (listeners == null) {
return;
}
if (DEBUG) {
System.out.println("FIRING hierarchy change ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$
if (fFocusType != null) {
System.out.println(" for hierarchy focused on " + fFocusType.toString()); //$NON-NLS-1$
}
}
// clone so that a listener cannot have a side-effect on this list when being notified
listeners = (ArrayList)listeners.clone();
for (int i= 0; i < listeners.size(); i++) {
final ITypeHierarchyChangedListener listener= (ITypeHierarchyChangedListener)listeners.get(i);
Platform.run(new ISafeRunnable() {
public void handleException(Throwable exception) {
Util.log(exception, "Exception occurred in listener of Type hierarchy change notification", ICLogConstants.CDT); //$NON-NLS-1$
}
public void run() throws Exception {
listener.typeHierarchyChanged(TypeHierarchy.this);
}
});
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#contains(org.eclipse.cdt.core.model.ICElement)
*/
public boolean contains(ICElement type) {
// classes
ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null);
if (info == null)
return false;
if (fTypeToSuperTypes.get(info) != null) {
return true;
}
// root classes
if (fRootTypes.contains(type)) return true;
return false;
}
/**
* @see ITypeHierarchy
*/
public boolean exists() {
if (!fNeedsRefresh) return true;
return (fFocusType == null || fFocusType.exists()) && cProject().exists();
}
/**
* Returns the C project this hierarchy was created in.
*/
public ICProject cProject() {
IProject project = fFocusType.getCache().getProject();
return findCProject(project);
}
private ICProject findCProject(IProject project) {
try {
ICProject[] cProjects = CoreModel.getDefault().getCModel().getCProjects();
if (cProjects != null) {
for (int i = 0; i < cProjects.length; ++i) {
ICProject cProject = cProjects[i];
if (project.equals(cProjects[i].getProject()))
return cProject;
}
}
} catch (CModelException e) {
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllClasses()
*/
public ICElement[] getAllClasses() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getRootClasses()
*/
public ICElement[] getRootClasses() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getSubtypes(org.eclipse.cdt.core.model.ICElement)
*/
public ICElement[] getSubtypes(ICElement type) {
List list = new ArrayList();
ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null);
Collection entries = (Collection) fTypeToSubTypes.get(info);
if (entries != null) {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
ITypeInfo subType = (ITypeInfo)i.next();
ICElement elem = AllTypesCache.getElementForType(subType, true, true, null);
if (elem != null) {
list.add(elem);
}
}
}
return (ICElement[])list.toArray(new ICElement[list.size()]);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllSuperclasses(org.eclipse.cdt.core.model.ICElement)
*/
public ICElement[] getAllSubtypes(ICElement type) {
List list = new ArrayList();
ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null);
addSubs(info, list);
//convert list to ICElements
ICElement[] elems = new ICElement[list.size()];
int count = 0;
for (Iterator i = list.iterator(); i.hasNext(); ) {
ITypeInfo subType = (ITypeInfo) i.next();
elems[count++] = AllTypesCache.getElementForType(subType, true, true, null);
}
return elems;
}
private void addSubs(ITypeInfo type, List list) {
Collection entries = (Collection) fTypeToSubTypes.get(type);
if (entries != null) {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
ITypeInfo subType = (ITypeInfo)i.next();
if (!list.contains(subType)) {
list.add(subType);
}
addSubs(subType, list);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getSupertypes(org.eclipse.cdt.core.model.ICElement)
*/
public ICElement[] getSupertypes(ICElement type) {
List list = new ArrayList();
ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null);
Collection entries = (Collection) fTypeToSuperTypes.get(info);
if (entries != null) {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
ITypeInfo superType = entry.type;
ICElement elem = AllTypesCache.getElementForType(superType, true, true, null);
if (elem != null) {
list.add(elem);
}
}
}
return (ICElement[])list.toArray(new ICElement[list.size()]);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllSuperclasses(org.eclipse.cdt.core.model.ICElement)
*/
public ICElement[] getAllSupertypes(ICElement type) {
List list = new ArrayList();
ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null);
addSupers(info, list);
//convert list to ICElements
ICElement[] elems = new ICElement[list.size()];
int count = 0;
for (Iterator i = list.iterator(); i.hasNext(); ) {
ITypeInfo superType = (ITypeInfo) i.next();
elems[count++] = AllTypesCache.getElementForType(superType, true, true, null);
}
return elems;
}
private void addSupers(ITypeInfo type, List list) {
Collection entries = (Collection) fTypeToSuperTypes.get(type);
if (entries != null) {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
TypeEntry entry = (TypeEntry)i.next();
ITypeInfo superType = entry.type;
if (!list.contains(superType)) {
list.add(superType);
}
addSupers(superType, list);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getType()
*/
public ICElement getType() {
if (fFocusType != null)
return AllTypesCache.getElementForType(fFocusType, true, true, null);
return null;
}
/**
* @see ITypeHierarchy
* TODO (jerome) should use a PerThreadObject to build the hierarchy instead of synchronizing
* (see also isAffected(IJavaElementDelta))
*/
public synchronized void refresh(IProgressMonitor monitor) throws CModelException {
try {
fProgressMonitor = monitor;
if (monitor != null) {
if (fFocusType != null) {
monitor.beginTask(TypeHierarchyMessages.getFormattedString("hierarchy.creatingOnType", fFocusType.getQualifiedTypeName().getFullyQualifiedName()), 100); //$NON-NLS-1$
} else {
monitor.beginTask(TypeHierarchyMessages.getString("hierarchy.creating"), 100); //$NON-NLS-1$
}
}
long start = -1;
if (DEBUG) {
start = System.currentTimeMillis();
if (fComputeSubtypes) {
System.out.println("CREATING TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
System.out.println("CREATING SUPER TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (fFocusType != null) {
System.out.println(" on type " + fFocusType.toString()); //$NON-NLS-1$
}
}
compute();
// initializeRegions();
fNeedsRefresh = false;
// fChangeCollector = null;
if (DEBUG) {
if (fComputeSubtypes) {
System.out.println("CREATED TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
System.out.println("CREATED SUPER TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
System.out.println(this.toString());
}
} finally {
if (monitor != null) {
monitor.done();
}
fProgressMonitor = null;
}
}
/**
* Compute this type hierarchy.
*/
protected void compute() {
if (fFocusType != null) {
// HierarchyBuilder builder =
// new IndexBasedHierarchyBuilder(
// this,
// this.scope);
// builder.build(this.computeSubtypes);
// initialize(1);
// buildSupertypes();
} // else a RegionBasedTypeHierarchy should be used
}
/**
* Initializes this hierarchy's internal tables with the given size.
*/
/* protected void initialize(int size) {
if (size < 10) {
size = 10;
}
int smallSize = (size / 2);
this.classToSuperclass = new HashMap(size);
this.interfaces = new ArrayList(smallSize);
this.missingTypes = new ArrayList(smallSize);
this.rootClasses = new TypeVector();
this.typeToSubtypes = new HashMap(smallSize);
this.typeToSuperInterfaces = new HashMap(smallSize);
this.typeFlags = new HashMap(smallSize);
this.projectRegion = new Region();
this.packageRegion = new Region();
this.files = new HashMap(5);
}
*/
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#store(java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor)
*/
public void store(OutputStream outputStream, IProgressMonitor monitor) throws CModelException {
// TODO Auto-generated method stub
}
}

View file

@ -1,129 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.ICModelStatusConstants;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager;
import org.eclipse.cdt.internal.core.model.CModelStatus;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
public class TypeHierarchyBuilder {
public TypeHierarchyBuilder() {
}
public ITypeHierarchy createTypeHierarchy(ITypeInfo info, boolean enableIndexing, IProgressMonitor monitor) throws CModelException {
TypeHierarchy typeHierarchy = new TypeHierarchy(info);
Set processedTypes = new HashSet();
addSuperClasses(typeHierarchy, info, processedTypes, enableIndexing, monitor);
typeHierarchy.addRootType(info);
processedTypes.clear();
addSubClasses(typeHierarchy, info, processedTypes, enableIndexing, monitor);
return typeHierarchy;
}
private void addSuperClasses(TypeHierarchy typeHierarchy, ITypeInfo type, Set processedTypes, boolean enableIndexing, IProgressMonitor monitor) throws CModelException {
if (type.hasSuperTypes()) {
ITypeInfo[] superTypes = TypeCacheManager.getInstance().locateSuperTypesAndWait(type, enableIndexing, Job.SHORT, monitor);
if (superTypes == null)
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
for (int i = 0; i < superTypes.length; ++i) {
ITypeInfo superType = superTypes[i];
// recursively process sub sub classes
if (!processedTypes.contains(superType)) {
processedTypes.add(superType);
addSuperClasses(typeHierarchy, superType, processedTypes, enableIndexing, monitor);
}
ASTAccessVisibility access = type.getSuperTypeAccess(superType);
typeHierarchy.addSuperType(type, superType, access);
}
} else {
typeHierarchy.addRootType(type);
}
}
private void addSubClasses(TypeHierarchy typeHierarchy, ITypeInfo type, Set processedTypes, boolean enableIndexing, IProgressMonitor monitor) throws CModelException {
if (type.hasSubTypes()) {
ITypeInfo[] subTypes = TypeCacheManager.getInstance().locateSubTypesAndWait(type, enableIndexing, Job.SHORT, monitor);
if (subTypes == null)
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
for (int i = 0; i < subTypes.length; ++i) {
ITypeInfo subType = subTypes[i];
// recursively process sub sub classes
if (!processedTypes.contains(subType)) {
processedTypes.add(subType);
addSubClasses(typeHierarchy, subType, processedTypes, enableIndexing, monitor);
}
typeHierarchy.addSubType(type, subType);
}
}
}
/*
private IStructure findCElementForType(ITypeInfo info, boolean enableIndexing, IProgressMonitor monitor) throws CModelException {
if (!info.exists())
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
if (!info.isClass())
throw new CModelException(new CModelStatus(ICModelStatusConstants.INVALID_ELEMENT_TYPES));
// first we need to resolve the type location
ITypeReference location = TypeCacheManager.getInstance().locateTypeAndWait(info, enableIndexing, Job.SHORT, monitor);
if (location == null)
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
ICElement cElem = location.getCElement();
if (cElem == null)
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
if (!(cElem instanceof IStructure))
throw new CModelException(new CModelStatus(ICModelStatusConstants.INVALID_ELEMENT_TYPES));
IStructure cClass = (IStructure)cElem;
// check if type exists in cache
ITypeInfo type = TypeCacheManager.getInstance().getTypeForElement(cElem);
if (type == null || !type.equals(info))
throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST));
return cClass;
}
private ITypeInfo findTypeInCache(ITypeCache cache, String name) {
IQualifiedTypeName qualName = new QualifiedTypeName(name);
ITypeInfo[] superTypes = cache.getTypes(qualName);
for (int i = 0; i < superTypes.length; ++i) {
ITypeInfo superType = superTypes[i];
if (superType.isClass()) {
return superType;
}
}
return null;
}
*/
}

View file

@ -1,50 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.browser.typehierarchy;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class TypeHierarchyMessages {
private static final String RESOURCE_BUNDLE= TypeHierarchyMessages.class.getName();
private static ResourceBundle fgResourceBundle;
static {
try {
fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
} catch (MissingResourceException x) {
fgResourceBundle = null;
}
}
private TypeHierarchyMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
} catch (NullPointerException e) {
return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
public static String getFormattedString(String key, String arg) {
return getFormattedString(key, new String[] { arg });
}
public static String getFormattedString(String key, String[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -1,17 +0,0 @@
###############################################################################
# Copyright (c) 2000, 2004 QNX Software Systems and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# QNX Software Systems - Initial API and implementation
###############################################################################
### hierarchy
hierarchy.nullProject = Project argument cannot be null
hierarchy.nullRegion = Region cannot be null
hierarchy.nullFocusType = Type focus cannot be null
hierarchy.creating = Creating type hierarchy...
hierarchy.creatingOnType = Creating type hierarchy on {0}...

View file

@ -1,116 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.internal.core.browser.util.DelegatedProgressMonitor;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
public abstract class BasicJob extends Job {
private Object fFamily;
private DelegatedProgressMonitor fProgressMonitor= new DelegatedProgressMonitor();
private Object fRunLock = new Object();
private boolean fIsRunning = false;
private static boolean VERBOSE = false;
public BasicJob(String name, Object family) {
super(name);
fFamily = family;
setPriority(BUILD);
setSystem(true);
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor)
*/
protected abstract IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException;
/* (non-Javadoc)
* @see org.eclipse.core.internal.jobs.InternalJob#belongsTo(java.lang.Object)
*/
public boolean belongsTo(Object family) {
if (fFamily != null) {
return fFamily.equals(family);
}
return false;
}
public boolean isRunning() {
synchronized(fRunLock) {
return fIsRunning;
}
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor)
*/
public IStatus run(IProgressMonitor monitor) {
synchronized(fRunLock) {
fIsRunning = true;
}
fProgressMonitor.init();
fProgressMonitor.addDelegate(monitor);
IStatus result = Status.CANCEL_STATUS;
try {
if (monitor.isCanceled())
throw new InterruptedException();
result = runWithDelegatedProgress(fProgressMonitor);
if (monitor.isCanceled())
throw new InterruptedException();
} catch(InterruptedException ex) {
return Status.CANCEL_STATUS;
} catch (OperationCanceledException ex) {
return Status.CANCEL_STATUS;
} finally {
fProgressMonitor.done();
fProgressMonitor.removeAllDelegates();
fProgressMonitor.init();
synchronized(fRunLock) {
fIsRunning = false;
}
}
return result;
}
/**
* Forwards progress info to the progress monitor and
* blocks until the job is finished.
*
* @param monitor the progress monitor.
* @throws InterruptedException
*
* @see Job#join
*/
public void join(IProgressMonitor monitor) throws InterruptedException {
if (monitor != null) {
fProgressMonitor.addDelegate(monitor);
}
super.join();
}
/**
* Outputs message to console.
*/
protected static void trace(String msg) {
if (VERBOSE) {
System.out.println("(" + Thread.currentThread() + ") " + msg); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}

View file

@ -1,214 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.core.browser.IQualifiedTypeName;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeInfoVisitor;
import org.eclipse.cdt.core.browser.ITypeReference;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
public interface ITypeCache extends ISchedulingRule {
/** Returns whether cache contains any types.
*
* @return <code>true</code> if cache is empty
*/
public boolean isEmpty();
/** Returns whether cache is complete.
*
* @return <code>true</code> if cache is up to date.
*/
public boolean isUpToDate();
/** Inserts type into cache.
*
* @param info
*/
public void insert(ITypeInfo info);
/** Adds subtype to type.
*
* @param type
* @param subtype
*/
public void addSubtype(ITypeInfo type, ITypeInfo subtype);
/** Adds supertype to type.
*
* @param type the type
* @param supertype the supertype
* @param the access visibility (PUBLIC, PROTECTED, PRIVATE)
* @param isVirtual <code>true</code> if virtual base class
*/
public void addSupertype(ITypeInfo type, ITypeInfo supertype, ASTAccessVisibility access, boolean isVirtual);
/** Removes type from cache.
*
* @param info
*/
public void remove(ITypeInfo info);
/** Removes all types in the given scope.
*
* @param scope
*/
public void flush(ITypeSearchScope scope);
/** Removes all types referenced by the given path.
*
* @param path
*/
public void flush(IPath path);
/** Removes all types from the cache.
*/
public void flushAll();
/** Returns all paths in the cache which are enclosed by
* the given scope. If no paths are found, an empty
* array is returned.
*
* @param scope the scope to search, or <code>null</code> to
* search the entire cache.
* @return A collection of paths in the given scope.
*/
public IPath[] getPaths(ITypeSearchScope scope);
/** Returns all types in the cache which are enclosed by
* the given scope. If no types are found, an empty array
* is returned.
*
* @param scope the scope to search, or <code>null</code> to
* search the entire cache.
* @return Array of types in the given scope
*/
public ITypeInfo[] getTypes(ITypeSearchScope scope);
/** Returns all types in the cache which match the given
* name. If no types are found, an empty array is returned.
*
* @param qualifiedName the qualified type name to match
* @param matchEnclosed <code>true</code> if enclosed types count as matches (foo::bar == bar)
* @param ignoreCase <code>true</code> if case-insensitive
* @return Array of types
*/
public ITypeInfo[] getTypes(IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase);
/** Returns first type in the cache which matches the given
* type and name. If no type is found, <code>null</code>
* is returned.
*
* @param type the ICElement type
* @param qualifiedName the qualified type name to match
* @return the matching type
*/
public ITypeInfo getType(int type, IQualifiedTypeName qualifiedName);
/** Gets the first enclosing type which matches one of the given kinds.
*
* @param info the given type
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT
*
* @return the enclosing type, or <code>null</code> if not found.
*/
public ITypeInfo getEnclosingType(ITypeInfo info, int[] kinds);
/** Returns the enclosing namespace for the given type, or
* <code>null</code> if none exists.
*
* @param type the ICElement type
* @param includeGlobalNamespace <code>true</code> if the global (default) namespace should be returned
* @return the enclosing namespace, or <code>null</code> if not found.
*/
public ITypeInfo getEnclosingNamespace(ITypeInfo info, boolean includeGlobalNamespace);
/** Gets the root namespace of which encloses the given type.
*
* @param info the given type
* @param includeGlobalNamespace <code>true</code> if the global (default) namespace should be returned
* @return the enclosing namespace, or <code>null</code> if not found.
*/
public ITypeInfo getRootNamespace(ITypeInfo info, boolean includeGlobalNamespace);
/** Returns whether any types are enclosed by the given type.
*
* @param info the given type
* @return <code>true</code> if the given type encloses other types.
*/
public boolean hasEnclosedTypes(ITypeInfo info);
/** Gets the types which are enclosed by the given type.
*
* @param info the given type
* @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS,
* C_UNION, C_ENUMERATION, C_TYPEDEF
* @return the enclosed types, or an empty array if not found.
*/
public ITypeInfo[] getEnclosedTypes(ITypeInfo info, int kinds[]);
/** Returns all types in the cache are supertypes of the given type.
*
* @param info the given type
* @return Array of supertypes, or <code>null</code> if none found.
*/
public ITypeInfo[] getSupertypes(ITypeInfo info);
/** Returns the supertype access visiblity.
*
* @param type the given type
* @param supertype the supertype
* @return the visibility (PRIVATE, PROTECTED, PUBLIC) or <code>null</code> if none found.
*/
public ASTAccessVisibility getSupertypeAccess(ITypeInfo type, ITypeInfo superType);
/** Returns all types in the cache which extend the given type.
*
* @param info the given type
* @return Array of subtypes, or <code>null</code> if none found.
*/
public ITypeInfo[] getSubtypes(ITypeInfo info);
/** Returns the project associated with this cache.
*
* @return the project
*/
public IProject getProject();
/** Accepts a visitor and iterates over all types in the cache.
*
* @param visitor
*/
public void accept(ITypeInfoVisitor visitor);
public void addDelta(TypeCacheDelta delta);
public void reconcile(boolean enableIndexing, int priority, int delay);
public void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor);
public void cancelJobs();
public void locateType(ITypeInfo info, int priority, int delay);
public ITypeReference locateTypeAndWait(ITypeInfo info, int priority, IProgressMonitor monitor);
public void locateSupertypes(ITypeInfo info, int priority, int delay);
public ITypeInfo[] locateSupertypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor);
public void locateSubtypes(ITypeInfo info, int priority, int delay);
public ITypeInfo[] locateSubtypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor);
public ITypeInfo getGlobalNamespace();
}

View file

@ -1,93 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.cindexstorage.Index;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public class IndexerDependenciesJob extends IndexerJob {
private ITypeCache fTypeCache;
private ITypeSearchScope fScope;
public IndexerDependenciesJob(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) {
super(indexManager, typeCache.getProject());
fTypeCache = typeCache;
fScope = scope;
}
protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException {
IndexInput input = new BlocksIndexInput(index.getIndexFile());
try {
input.open();
flushDependencies(input, progressMonitor);
return true;
} catch (IOException e) {
return false;
} finally {
try {
input.close();
} catch (IOException e) {
return false;
}
}
}
private void flushDependencies(IndexInput input, IProgressMonitor progressMonitor)
throws InterruptedException, IOException {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IEntryResult[] includeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE));
if (includeEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < includeEntries.length; ++i) {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = includeEntries[i];
IPath includePath = getIncludePath(entry);
if (fScope != null && fScope.encloses(includePath)) {
int[] references = entry.getFileReferences();
if (references != null) {
for (int j = 0; j < references.length; ++j) {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IndexedFileEntry file = input.getIndexedFile(references[j]);
if (file != null && file.getPath() != null) {
IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
fTypeCache.flush(path);
}
}
}
}
}
}
}
private IPath getIncludePath(IEntryResult entry) {
return PathUtil.getWorkspaceRelativePath(entry.getName());
}
}

View file

@ -1,92 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.cindexstorage.Index;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public class IndexerDependenciesJob2 extends IndexerJob2 {
private ITypeCache fTypeCache;
private ITypeSearchScope fScope;
public IndexerDependenciesJob2(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) {
super(indexManager, typeCache.getProject());
fTypeCache = typeCache;
fScope = scope;
}
protected boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException {
IndexInput input = new BlocksIndexInput(fProjectIndex.getIndexFile());
try {
input.open();
flushDependencies(input, progressMonitor);
return true;
} catch (IOException e) {
return false;
} finally {
try {
input.close();
} catch (IOException e) {
return false;
}
}
}
private void flushDependencies(IndexInput input, IProgressMonitor progressMonitor)
throws InterruptedException, IOException {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IEntryResult[] includeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE));
if (includeEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < includeEntries.length; ++i) {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = includeEntries[i];
IPath includePath = getIncludePath(entry);
if (fScope != null && fScope.encloses(includePath)) {
int[] references = entry.getFileReferences();
if (references != null) {
for (int j = 0; j < references.length; ++j) {
if (progressMonitor.isCanceled())
throw new InterruptedException();
IndexedFileEntry file = input.getIndexedFile(references[j]);
if (file != null && file.getPath() != null) {
IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
fTypeCache.flush(path);
}
}
}
}
}
}
}
private IPath getIncludePath(IEntryResult entry) {
return PathUtil.getWorkspaceRelativePath(entry.getName());
}
}

View file

@ -1,157 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* QNX Software Systems - adapted for type cache
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.index.ICDTIndexer;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
public abstract class IndexerJob implements IIndexJob {
private IndexManager fIndexManager;
private IProject fProject;
private IIndex fProjectIndex = null;
private DOMSourceIndexer fSourceIndexer = null;
public static final String FAMILY= "BasicTypeIndexerJob"; //$NON-NLS-1$
public IndexerJob(IndexManager indexManager, IProject project) {
fIndexManager = indexManager;
fProject = project;
//Get the indexer assigned to this project; check to see if it's
//a Source Indexder
ICDTIndexer indexer = indexManager.getIndexerForProject(project);
if (indexer instanceof DOMSourceIndexer)
fSourceIndexer = (DOMSourceIndexer) indexer;
}
public boolean belongsTo(String family) {
return family == FAMILY;
}
public void cancel() {
}
public boolean isReadyToRun() {
if (fProjectIndex == null) { // only check once. As long as this job is used, it will keep the same index picture
getIndexForProject(fProject); // will only cache answer if all indexes were available originally
}
return true;
}
public String toString() {
return FAMILY;
}
protected abstract boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException;
public boolean execute(IProgressMonitor progressMonitor) {
boolean success = false;
try {
fProjectIndex = getIndexForProject(fProject);
if (fProjectIndex == null)
return false;
if (progressMonitor == null) {
progressMonitor = new NullProgressMonitor();
}
if (progressMonitor.isCanceled())
throw new OperationCanceledException();
progressMonitor.beginTask("", 1); //$NON-NLS-1$
success = prepareIndex(fProjectIndex, fProject, progressMonitor);
if (progressMonitor.isCanceled()) {
throw new OperationCanceledException();
}
progressMonitor.worked(1);
return success;
} catch (InterruptedException e) {
throw new OperationCanceledException();
} finally {
progressMonitor.done();
}
}
private boolean prepareIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException {
if (progressMonitor.isCanceled())
throw new InterruptedException();
if (index == null)
return COMPLETE;
if (fSourceIndexer == null)
return FAILED;
ReadWriteMonitor monitor = fSourceIndexer.getMonitorFor(index);
if (monitor == null)
return COMPLETE; // index got deleted since acquired
try {
monitor.enterRead(); // ask permission to read
/* if index has changed, commit these before querying */
if (index.hasChanged()) {
try {
monitor.exitRead(); // free read lock
monitor.enterWrite(); // ask permission to write
fSourceIndexer.saveIndex(index);
} catch (IOException e) {
return FAILED;
} finally {
monitor.exitWriteEnterRead(); // finished writing and reacquire read permission
}
}
if (progressMonitor.isCanceled())
throw new InterruptedException();
return processIndex(index, project, progressMonitor);
} finally {
monitor.exitRead(); // finished reading
}
}
private IIndex getIndexForProject(IProject project) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IPath path = project.getFullPath();
IPath location;
if ((!root.getProject(path.lastSegment()).exists()) // if project does not exist
&& path.segmentCount() > 1
&& ((location = root.getFile(path).getLocation()) == null
|| !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist
&& !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist
return null;
}
// may trigger some index recreation work
if (fSourceIndexer != null)
return fSourceIndexer.getIndex(path, true /*reuse index file*/, false /*do not create if none*/);
return null;
}
}

View file

@ -1,166 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004,2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software Systems - adapted for type cache
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.index.ICDTIndexer;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
public abstract class IndexerJob2 implements IIndexJob {
protected IProject fProject;
protected IIndex fProjectIndex = null;
protected ICDTIndexer fSourceIndexer = null;
public static final String FAMILY= "IndexerJob2"; //$NON-NLS-1$
public IndexerJob2(IndexManager indexManager, IProject project) {
fProject = project;
fSourceIndexer = indexManager.getIndexerForProject(project);
fProjectIndex = getIndexForProject();
}
public boolean belongsTo(String family) {
return family == FAMILY;
}
public void cancel() {
}
public boolean isReadyToRun() {
return true;
}
public String toString() {
return FAMILY;
}
protected abstract boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException;
public boolean execute(IProgressMonitor progressMonitor) {
boolean success = false;
try {
if (fProjectIndex == null)
return false;
if (progressMonitor == null) {
progressMonitor = new NullProgressMonitor();
}
if (progressMonitor.isCanceled())
throw new OperationCanceledException();
progressMonitor.beginTask("", 1); //$NON-NLS-1$
success = prepareIndex(progressMonitor);
if (progressMonitor.isCanceled()) {
throw new OperationCanceledException();
}
progressMonitor.worked(1);
return success;
} catch (InterruptedException e) {
throw new OperationCanceledException();
} finally {
progressMonitor.done();
}
}
private boolean prepareIndex(IProgressMonitor progressMonitor) throws InterruptedException {
if (progressMonitor.isCanceled())
throw new InterruptedException();
if (fProjectIndex == null)
return COMPLETE;
if (fSourceIndexer == null)
return FAILED;
ReadWriteMonitor monitor = fSourceIndexer.getMonitorFor(fProjectIndex);
if (monitor == null)
return COMPLETE; // index got deleted since acquired
try {
monitor.enterRead(); // ask permission to read
/* if index has changed, commit these before querying */
if (fProjectIndex.hasChanged()) {
try {
monitor.exitRead(); // free read lock
monitor.enterWrite(); // ask permission to write
fSourceIndexer.saveIndex(fProjectIndex);
} catch (IOException e) {
return FAILED;
} finally {
monitor.exitWriteEnterRead(); // finished writing and reacquire read permission
}
}
if (progressMonitor.isCanceled())
throw new InterruptedException();
return processIndex(progressMonitor);
} finally {
monitor.exitRead(); // finished reading
}
}
private IIndex getIndexForProject() {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IPath path = fProject.getFullPath();
IPath location;
if ((!root.getProject(path.lastSegment()).exists()) // if project does not exist
&& path.segmentCount() > 1
&& ((location = root.getFile(path).getLocation()) == null
|| !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist
&& !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist
return null;
}
// may trigger some index recreation work
if (fSourceIndexer != null)
return fSourceIndexer.getIndex(path, true /*reuse index file*/, false /*do not create if none*/);
return null;
}
protected int index2ICElement( int kind )
{
switch(kind) {
case IIndex.TYPE_CLASS:
return ICElement.C_CLASS;
case IIndex.TYPE_STRUCT:
return ICElement.C_STRUCT;
case IIndex.TYPE_ENUM:
return ICElement.C_ENUMERATION;
case IIndex.TYPE_UNION:
return ICElement.C_UNION;
case IIndex.TYPE_TYPEDEF:
return ICElement.C_TYPEDEF;
default:
return 0;
}
}
}

View file

@ -1,186 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.QualifiedTypeName;
import org.eclipse.cdt.core.browser.TypeInfo;
import org.eclipse.cdt.core.browser.TypeReference;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.cindexstorage.Index;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public class IndexerTypesJob extends IndexerJob {
private ITypeCache fTypeCache;
public IndexerTypesJob(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) {
super(indexManager, typeCache.getProject());
fTypeCache = typeCache;
}
protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException {
IndexInput input = new BlocksIndexInput(index.getIndexFile());
try {
input.open();
updateNamespaces(input, project, progressMonitor);
updateTypes(input, project, progressMonitor);
return true;
} catch (IOException e) {
return false;
} finally {
try {
input.close();
} catch (IOException e) {
return false;
}
}
}
private void updateNamespaces(IndexInput input, IProject project, IProgressMonitor monitor)
throws InterruptedException, IOException {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult[] namespaceEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.NAMESPACE, IIndex.ANY, IIndex.DECLARATION));
if (namespaceEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < namespaceEntries.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = namespaceEntries[i];
String name = entry.getName();
if (name.length() != 0) {
String[] enclosingNames = entry.getEnclosingNames();
addType(input, project, entry, ICElement.C_NAMESPACE, name, enclosingNames, monitor);
}
}
}
}
private void updateTypes(IndexInput input, IProject project, IProgressMonitor monitor)
throws InterruptedException, IOException {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult[] typeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION));
if (typeEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < typeEntries.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = typeEntries[i];
String name = entry.getName();
switch (entry.getKind() ) {
case IIndex.TYPE_CLASS :
case IIndex.TYPE_STRUCT :
case IIndex.TYPE_TYPEDEF :
case IIndex.TYPE_ENUM :
case IIndex.TYPE_UNION :
if (name.length() != 0) { // skip anonymous structs
addType(input, project, entry, entry.getKind(), name, entry.getEnclosingNames(), monitor);
}
break;
case IIndex.TYPE_DERIVED :
if (name.length() != 0) { // skip anonymous structs
addSuperTypeReference(input, project, entry, name, entry.getEnclosingNames(), monitor);
}
break;
default:
break;
}
}
}
}
private void addType(IndexInput input, IProject project, IEntryResult entry, int type, String name, String[] enclosingNames, IProgressMonitor monitor)
throws InterruptedException, IOException {
QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames);
ITypeInfo info = fTypeCache.getType(type, qualifiedName);
if (info == null || info.isUndefinedType()) {
int[] references = entry.getFileReferences();
if (references != null && references.length > 0) {
// add new type to cache
if (info != null) {
info.setCElementType(type);
} else {
info = new TypeInfo(type, qualifiedName);
fTypeCache.insert(info);
}
// for (int i = 0; i < references.length; ++i) {
// if (monitor.isCanceled())
// throw new InterruptedException();
//
// IndexedFile file = input.getIndexedFile(references[i]);
// if (file != null && file.getPath() != null) {
// IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
// info.addReference(new TypeReference(path, project));
// }
// }
// just grab the first reference
IndexedFileEntry file = input.getIndexedFile(references[0]);
if (file != null && file.getPath() != null) {
IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
info.addReference(new TypeReference(path, project));
}
}
}
}
private void addSuperTypeReference(IndexInput input, IProject project, IEntryResult entry, String name, String[] enclosingNames, IProgressMonitor monitor) throws InterruptedException, IOException {
QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames);
ITypeInfo info = fTypeCache.getType(ICElement.C_CLASS, qualifiedName);
if (info == null)
info = fTypeCache.getType(ICElement.C_STRUCT, qualifiedName);
if (info == null) {
// add dummy type to cache
info = new TypeInfo(0, qualifiedName);
fTypeCache.insert(info);
}
int[] references = entry.getFileReferences();
if (references != null && references.length > 0) {
for (int i = 0; i < references.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
IndexedFileEntry file = input.getIndexedFile(references[i]);
if (file != null && file.getPath() != null) {
IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
info.addDerivedReference(new TypeReference(path, project));
//
// // get absolute path
// IPath path = new Path(file.getPath());
// IPath projectPath = project.getFullPath();
// if (projectPath.isPrefixOf(path)) {
// path = project.getLocation().append(path.removeFirstSegments(projectPath.segmentCount()));
// }
// info.addDerivedReference(new TypeReference(path, project));
}
}
}
}
}

View file

@ -1,229 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.QualifiedTypeName;
import org.eclipse.cdt.core.browser.TypeInfo;
import org.eclipse.cdt.core.browser.TypeReference;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.IQueryResult;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public class IndexerTypesJob2 extends IndexerJob2 {
private ITypeCache fTypeCache;
public IndexerTypesJob2(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) {
super(indexManager, typeCache.getProject());
fTypeCache = typeCache;
}
protected boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException {
IndexInput input = null;
try {
input = new BlocksIndexInput( fProjectIndex.getIndexFile() );
input.open();
updateNamespaces(input, progressMonitor);
updateTypes(input, progressMonitor);
return true;
} catch (IOException e) {
return false;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// do nothing
}
}
}
}
private void updateNamespaces(IndexInput input, IProgressMonitor monitor)
throws InterruptedException, IOException {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult[] namespaceEntries = fProjectIndex.getEntries( IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION );
IQueryResult[] namespacePaths = fProjectIndex.getPrefix(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION );
// input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.NAMESPACE, IIndex.ANY, IIndex.DECLARATION));
if (namespaceEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < namespaceEntries.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = namespaceEntries[i];
String name = entry.getName();
if (name.length() != 0) {
String[] enclosingNames = entry.getEnclosingNames();
addType(input, entry, namespacePaths[i].getPath(), ICElement.C_NAMESPACE, name, enclosingNames, monitor);
}
}
}
}
private void updateTypes(IndexInput input, IProgressMonitor monitor)
throws InterruptedException, IOException {
if (monitor.isCanceled())
throw new InterruptedException();
for( int counter = 0; counter < 2; ++counter )
{
IEntryResult[] typeEntries = fProjectIndex.getEntries( IIndex.TYPE, IIndex.ANY, ( counter == 0 ) ? IIndex.DECLARATION : IIndex.DEFINITION );
if (typeEntries != null) {
//TODO subprogress monitor
for (int i = 0; i < typeEntries.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = typeEntries[i];
String name = entry.extractSimpleName();
switch (entry.getKind() ) {
case IIndex.TYPE_CLASS :
case IIndex.TYPE_STRUCT :
case IIndex.TYPE_TYPEDEF :
case IIndex.TYPE_ENUM :
case IIndex.TYPE_UNION :
if (counter != 0 && name.length() != 0) { // skip anonymous structs
addType(input, entry, null, index2ICElement( entry.getKind() ), name, entry.getEnclosingNames(), monitor);
}
break;
default:
break;
}
}
}
}
IEntryResult[] typeEntries = fProjectIndex.getEntries( IIndex.TYPE, IIndex.TYPE_DERIVED, IIndex.ANY );
if (typeEntries != null){
for( int j = 0; j < typeEntries.length; ++j )
{
if (monitor.isCanceled())
throw new InterruptedException();
IEntryResult entry = typeEntries[j];
String name = entry.extractSimpleName();
switch( entry.getKind() )
{
case IIndex.TYPE_DERIVED :
if (name.length() != 0) { // skip anonymous structs
addSuperTypeReference(input, entry, name, entry.getEnclosingNames(), monitor);
}
break;
default:
break;
}
}
}
}
private void addType(IndexInput input, IEntryResult entry, String pth, int type, String name, String[] enclosingNames, IProgressMonitor monitor)
throws InterruptedException, IOException {
QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames);
ITypeInfo info = fTypeCache.getType(type, qualifiedName);
if (info == null || info.isUndefinedType()) {
int[] references = entry.getFileReferences();
if (references != null && references.length > 0) {
// add new type to cache
if (info != null) {
info.setCElementType(type);
} else {
info = new TypeInfo(type, qualifiedName);
fTypeCache.insert(info);
}
// for (int i = 0; i < references.length; ++i) {
// if (monitor.isCanceled())
// throw new InterruptedException();
//
// IndexedFile file = input.getIndexedFile(references[i]);
// if (file != null && file.getPath() != null) {
// IPath path = PathUtil.getWorkspaceRelativePath(file.getPath());
// info.addReference(new TypeReference(path, project));
// }
// }
if (pth == null) {
pth = input.getIndexedFile( references[0] ).getPath();
}
final IPath workspaceRelativePath = PathUtil.getWorkspaceRelativePath(pth);
int offset = entry.getOffsets()[0][0];
// int offsetType = Integer.valueOf(String.valueOf(offsets[i][j]).substring(0,1)).intValue();
int offsetType = offset;
int m = 1;
while (offsetType >= 10) {
offsetType = offsetType / 10;
m *= 10;
}
int value = offset - ( offsetType * m );
// int value = Integer.valueOf(String.valueOf(offset).substring(1)).intValue();
TypeReference typeReference = null;
if (offsetType==IIndex.LINE){
typeReference = new TypeReference(workspaceRelativePath, fProject, value, 0 );
typeReference.offsetIsLineNumber = true;
}else if (offsetType==IIndex.OFFSET){
typeReference = new TypeReference(workspaceRelativePath, fProject, value, entry.getOffsetLengths()[0][0] );
}
if( typeReference != null )
info.addReference(typeReference);
}
}
}
private void addSuperTypeReference(IndexInput input, IEntryResult entry, String name, String[] enclosingNames, IProgressMonitor monitor) throws InterruptedException, IOException {
QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames);
ITypeInfo info = fTypeCache.getType(ICElement.C_CLASS, qualifiedName);
if (info == null)
info = fTypeCache.getType(ICElement.C_STRUCT, qualifiedName);
if (info == null) {
// add dummy type to cache
info = new TypeInfo(0, qualifiedName);
fTypeCache.insert(info);
}
int[] references = entry.getFileReferences();
if (references != null && references.length > 0) {
for (int i = 0; i < references.length; ++i) {
if (monitor.isCanceled())
throw new InterruptedException();
String pth = input.getIndexedFile( references[i] ).getPath();
IPath path = PathUtil.getWorkspaceRelativePath(pth);
info.addDerivedReference(new TypeReference(path, fProject));
//
// // get absolute path
// IPath path = new Path(file.getPath());
// IPath projectPath = project.getFullPath();
// if (projectPath.isPrefixOf(path)) {
// path = project.getLocation().append(path.removeFirstSegments(projectPath.segmentCount()));
// }
// info.addDerivedReference(new TypeReference(path, project));
}
}
}
}

View file

@ -1,67 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
public class SubTypeLocatorJob extends BasicJob {
public static final Object FAMILY = new Object();
private ITypeInfo fLocateType;
private ITypeCache fTypeCache;
private IWorkingCopyProvider fWorkingCopyProvider;
public SubTypeLocatorJob(ITypeInfo info, ITypeCache typeCache, IWorkingCopyProvider workingCopyProvider) {
super(TypeCacheMessages.getString("SubTypeLocatorJob.jobName"), FAMILY); //$NON-NLS-1$
fLocateType = info;
fTypeCache = typeCache;
fWorkingCopyProvider= workingCopyProvider;
}
public ITypeInfo getType() {
return fLocateType;
}
protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException {
boolean success = false;
long startTime = System.currentTimeMillis();
trace("SubTypeLocatorJob: started"); //$NON-NLS-1$
try {
monitor.beginTask(TypeCacheMessages.getString("SubTypeLocatorJob.taskName"), 100); //$NON-NLS-1$
if (monitor.isCanceled())
throw new InterruptedException();
TypeParser parser = new TypeParser(fTypeCache, fWorkingCopyProvider);
success = parser.findSubTypes(fLocateType, new SubProgressMonitor(monitor, 100));
if (monitor.isCanceled())
throw new InterruptedException();
} finally {
long executionTime = System.currentTimeMillis() - startTime;
if (success)
trace("SubTypeLocatorJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
else
trace("SubTypeLocatorJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
monitor.done();
}
return Status.OK_STATUS;
}
}

View file

@ -1,895 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.cdt.core.browser.IQualifiedTypeName;
import org.eclipse.cdt.core.browser.ITypeCacheChangedListener;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeInfoVisitor;
import org.eclipse.cdt.core.browser.ITypeReference;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.QualifiedTypeName;
import org.eclipse.cdt.core.browser.TypeInfo;
import org.eclipse.cdt.core.browser.TypeSearchScope;
import org.eclipse.cdt.core.index.ICDTIndexer;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.internal.core.browser.util.ArrayUtil;
import org.eclipse.cdt.internal.core.model.CModelManager;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
public class TypeCache implements ITypeCache {
private static final int INITIAL_TYPE_COUNT = 100;
private final Map fTypeKeyMap = new HashMap(INITIAL_TYPE_COUNT);
final IProject fProject;
private final IWorkingCopyProvider fWorkingCopyProvider;
final Collection fDeltas = new ArrayList();
final ITypeInfo fGlobalNamespace;
private final Map fTypeToSubTypes = new HashMap();
private final Map fTypeToSuperTypes = new HashMap();
ITypeCacheChangedListener fChangeListener = null;
private static final class SuperTypeEntry {
ITypeInfo superType;
ASTAccessVisibility access;
boolean isVirtual;
SuperTypeEntry(ITypeInfo superType, ASTAccessVisibility access, boolean isVirtual) {
this.superType = superType;
this.access = access;
this.isVirtual = isVirtual;
}
}
private SuperTypeEntry findSuperTypeEntry(Collection entryCollection, ITypeInfo superType) {
for (Iterator i = entryCollection.iterator(); i.hasNext(); ) {
SuperTypeEntry e = (SuperTypeEntry) i.next();
if (e.superType.equals(superType)) {
return e;
}
}
return null;
}
private static final int[] ENCLOSING_TYPES = {ICElement.C_NAMESPACE, ICElement.C_CLASS, ICElement.C_STRUCT, 0};
private IJobChangeListener fJobChangeListener = new IJobChangeListener() {
public void aboutToRun(IJobChangeEvent event) {
}
public void awake(IJobChangeEvent event) {
}
public void done(IJobChangeEvent event) {
Job job = event.getJob();
if (job instanceof TypeCacherJob) {
TypeCacherJob deltaJob = (TypeCacherJob)job;
IStatus status = event.getResult();
if (status != null) {
boolean jobFinished = (status.equals(Status.OK_STATUS)
&& !deltaJob.isIndexerBusy());
// remove the completed deltas
synchronized(fDeltas) {
for (Iterator i = fDeltas.iterator(); i.hasNext(); ) {
TypeCacheDelta delta = (TypeCacheDelta) i.next();
if (delta.getJob() != null && delta.getJob().equals(deltaJob)) {
if (jobFinished) {
i.remove();
} else {
delta.assignToJob(null);
}
}
}
}
}
// TODO finer-grained change deltas
if (fChangeListener != null)
fChangeListener.typeCacheChanged(fProject);
}
}
public void running(IJobChangeEvent event) {
}
public void scheduled(IJobChangeEvent event) {
}
public void sleeping(IJobChangeEvent event) {
}
};
private static class GlobalNamespace implements IQualifiedTypeName {
private static final String GLOBAL_NAMESPACE = TypeCacheMessages.getString("TypeCache.globalNamespace"); //$NON-NLS-1$
private static final String[] segments = new String[] { GLOBAL_NAMESPACE };
public GlobalNamespace() {
}
public String getName() {
return GLOBAL_NAMESPACE;
}
public String[] getEnclosingNames() {
return null;
}
public String getFullyQualifiedName() {
return GLOBAL_NAMESPACE;
}
public IQualifiedTypeName getEnclosingTypeName() {
return null;
}
public boolean isEmpty() {
return false;
}
public boolean isGlobal() {
return true;
}
public boolean isQualified() {
return false;
}
public boolean isValidSegment(String segment) {
return false;
}
public int segmentCount() {
return 1;
}
public String[] segments() {
return segments;
}
public String segment(int index) {
if (index > 0)
return null;
return GLOBAL_NAMESPACE;
}
public String lastSegment() {
return GLOBAL_NAMESPACE;
}
public int matchingFirstSegments(IQualifiedTypeName typeName) {
return 1;
}
public boolean isPrefixOf(IQualifiedTypeName typeName) {
return true;
}
public IQualifiedTypeName append(String[] names) {
return new QualifiedTypeName(names);
}
public IQualifiedTypeName append(IQualifiedTypeName typeName) {
return new QualifiedTypeName(typeName);
}
public IQualifiedTypeName append(String qualifiedName) {
return new QualifiedTypeName(qualifiedName);
}
public IQualifiedTypeName removeFirstSegments(int count) {
return this;
}
public IQualifiedTypeName removeLastSegments(int count) {
return this;
}
public boolean isLowLevel() {
return false;
}
public boolean isValid() {
return true;
}
public int hashCode() {
return GLOBAL_NAMESPACE.hashCode();
}
public String toString() {
return getFullyQualifiedName();
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof IQualifiedTypeName)) {
return false;
}
return equals((IQualifiedTypeName)obj);
}
public int compareTo(Object obj) {
if (obj == this) {
return 0;
}
if (!(obj instanceof IQualifiedTypeName)) {
throw new ClassCastException();
}
return compareTo((IQualifiedTypeName)obj);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.IQualifiedTypeName#equals(org.eclipse.cdt.core.browser.IQualifiedTypeName)
*/
public boolean equals(IQualifiedTypeName typeName) {
return (typeName instanceof GlobalNamespace);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.IQualifiedTypeName#equalsIgnoreCase(org.eclipse.cdt.core.browser.IQualifiedTypeName)
*/
public boolean equalsIgnoreCase(IQualifiedTypeName typeName) {
return (typeName instanceof GlobalNamespace);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.IQualifiedTypeName#compareTo(org.eclipse.cdt.core.browser.IQualifiedTypeName)
*/
public int compareTo(IQualifiedTypeName typeName) {
return getFullyQualifiedName().compareTo(typeName.getFullyQualifiedName());
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.IQualifiedTypeName#compareToIgnoreCase(org.eclipse.cdt.core.browser.IQualifiedTypeName)
*/
public int compareToIgnoreCase(IQualifiedTypeName typeName) {
return getFullyQualifiedName().compareToIgnoreCase(typeName.getFullyQualifiedName());
}
}
private static class HashKey {
private IQualifiedTypeName name;
private int type;
public HashKey(IQualifiedTypeName name, int type) {
this.name = name;
this.type = type;
}
public int hashCode() {
return (this.name.hashCode() + this.type);
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof HashKey)) {
return false;
}
HashKey otherKey = (HashKey)obj;
return (this.type == otherKey.type && this.name.equals(otherKey.name));
}
}
public TypeCache(IProject project, IWorkingCopyProvider workingCopyProvider) {
fProject = project;
fWorkingCopyProvider = workingCopyProvider;
fDeltas.add(new TypeCacheDelta(fProject));
fGlobalNamespace = new TypeInfo(ICElement.C_NAMESPACE, new GlobalNamespace());
fGlobalNamespace.setCache(this);
}
public TypeCache(IProject project, IWorkingCopyProvider workingCopyProvider, ITypeCacheChangedListener listener) {
this(project, workingCopyProvider);
fChangeListener = listener;
}
public boolean contains(ISchedulingRule rule) {
if (this == rule)
return true;
if (rule instanceof ITypeCache) {
ITypeCache typeCache = (ITypeCache) rule;
if (fProject.equals(typeCache.getProject()))
return true;
}
return false;
}
public boolean isConflicting(ISchedulingRule rule) {
if (rule instanceof ITypeCache) {
ITypeCache typeCache = (ITypeCache) rule;
if (fProject.equals(typeCache.getProject()))
return true;
}
return false;
}
public IProject getProject() {
return fProject;
}
public synchronized boolean isEmpty() {
return fTypeKeyMap.isEmpty();
}
public synchronized void insert(ITypeInfo newType) {
// check if enclosing types are already in cache
IQualifiedTypeName enclosingName = newType.getQualifiedTypeName().getEnclosingTypeName();
if (enclosingName != null) {
while (!enclosingName.isEmpty()) {
// try namespace, class, struct, then undefined
ITypeInfo enclosingType = null;
for (int i = 0; enclosingType == null && i < ENCLOSING_TYPES.length; ++i) {
enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ENCLOSING_TYPES[i]));
}
if (enclosingType == null) {
// create a dummy type to take this place (type 0 == unknown)
ITypeInfo dummyType = new TypeInfo(0, enclosingName);
dummyType.setCache(this);
fTypeKeyMap.put(new HashKey(enclosingName, 0), dummyType);
}
enclosingName = enclosingName.removeLastSegments(1);
}
}
fTypeKeyMap.put(new HashKey(newType.getQualifiedTypeName(), newType.getCElementType()), newType);
newType.setCache(this);
}
public synchronized void remove(ITypeInfo info) {
fTypeKeyMap.remove(new HashKey(info.getQualifiedTypeName(), info.getCElementType()));
info.setCache(null);
}
public synchronized void flush(ITypeSearchScope scope) {
if (scope.encloses(fProject)) {
flushAll();
} else {
for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) {
Map.Entry entry = (Map.Entry) mapIter.next();
ITypeInfo info = (ITypeInfo) entry.getValue();
if (info.isEnclosed(scope)) {
mapIter.remove();
}
}
}
}
public synchronized void flush(IPath path) {
ITypeSearchScope scope = new TypeSearchScope();
scope.add(path, false, null);
flush(scope);
}
public synchronized void flushAll() {
// flush the entire cache
accept(new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
info.setCache(null);
return true;
}
public boolean shouldContinue() { return true; }
});
fTypeKeyMap.clear();
}
public synchronized void addSupertype(ITypeInfo type, ITypeInfo supertype, ASTAccessVisibility access, boolean isVirtual) {
Collection entryCollection = (Collection) fTypeToSuperTypes.get(type);
if (entryCollection == null) {
entryCollection = new ArrayList();
fTypeToSuperTypes.put(type, entryCollection);
}
if (findSuperTypeEntry(entryCollection, supertype) == null) {
entryCollection.add(new SuperTypeEntry(supertype, access, isVirtual));
supertype.setCache(this);
}
}
public synchronized ITypeInfo[] getSupertypes(ITypeInfo type) {
Collection entryCollection = (Collection) fTypeToSuperTypes.get(type);
if (entryCollection != null && !entryCollection.isEmpty()) {
ITypeInfo[] superTypes = new ITypeInfo[entryCollection.size()];
int count = 0;
for (Iterator i = entryCollection.iterator(); i.hasNext(); ) {
SuperTypeEntry e = (SuperTypeEntry) i.next();
superTypes[count++] = e.superType;
}
return superTypes;
}
return null;
}
public ASTAccessVisibility getSupertypeAccess(ITypeInfo type, ITypeInfo superType) {
Collection entryCollection = (Collection) fTypeToSuperTypes.get(type);
if (entryCollection != null && !entryCollection.isEmpty()) {
SuperTypeEntry e = findSuperTypeEntry(entryCollection, superType);
if (e != null)
return e.access;
}
return null;
}
public synchronized void addSubtype(ITypeInfo type, ITypeInfo subtype) {
Collection typeCollection = (Collection) fTypeToSubTypes.get(type);
if (typeCollection == null) {
typeCollection = new ArrayList();
fTypeToSubTypes.put(type, typeCollection);
}
if (!typeCollection.contains(subtype)) {
typeCollection.add(subtype);
subtype.setCache(this);
}
}
public synchronized ITypeInfo[] getSubtypes(ITypeInfo type) {
Collection typeCollection = (Collection) fTypeToSubTypes.get(type);
if (typeCollection != null && !typeCollection.isEmpty()) {
return (ITypeInfo[]) typeCollection.toArray(new ITypeInfo[typeCollection.size()]);
}
return null;
}
public synchronized void accept(ITypeInfoVisitor visitor) {
for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) {
Map.Entry entry = (Map.Entry) mapIter.next();
ITypeInfo info = (ITypeInfo) entry.getValue();
if (!visitor.shouldContinue())
return; // stop visiting
visitor.visit(info);
}
}
public synchronized IPath[] getPaths(final ITypeSearchScope scope) {
final Set pathSet = new HashSet();
accept(new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
if (scope == null || info.isEnclosed(scope)) {
ITypeReference[] refs = info.getReferences();
if (refs != null) {
for (int i = 0; i < refs.length; ++i) {
IPath path = refs[i].getPath();
if (scope == null || scope.encloses(path))
pathSet.add(path);
}
}
}
return true;
}
public boolean shouldContinue() { return true; }
});
return (IPath[]) pathSet.toArray(new IPath[pathSet.size()]);
}
public synchronized ITypeInfo[] getTypes(final ITypeSearchScope scope) {
final Collection results = new ArrayList();
accept(new ITypeInfoVisitor() {
public boolean visit(ITypeInfo info) {
if (scope == null || info.isEnclosed(scope)) {
results.add(info);
}
return true;
}
public boolean shouldContinue() { return true; }
});
return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]);
}
public synchronized ITypeInfo[] getTypes(IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase) {
Collection results = new ArrayList();
if (!ignoreCase && !matchEnclosed) {
for (int i = 0; i < ITypeInfo.KNOWN_TYPES.length; ++i) {
ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, ITypeInfo.KNOWN_TYPES[i]));
if (info != null) {
results.add(info);
}
}
ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, 0));
if (info != null) {
results.add(info);
}
} else {
// TODO this should probably use a more efficient search algorithm
for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) {
Map.Entry entry = (Map.Entry) mapIter.next();
ITypeInfo info = (ITypeInfo) entry.getValue();
IQualifiedTypeName currName = info.getQualifiedTypeName();
if (ignoreCase) {
if (matchEnclosed && currName.segmentCount() > qualifiedName.segmentCount()
&& currName.lastSegment().equalsIgnoreCase(qualifiedName.lastSegment())) {
currName = currName.removeFirstSegments(currName.segmentCount() - qualifiedName.segmentCount());
}
if (currName.equalsIgnoreCase(qualifiedName)) {
results.add(info);
}
} else {
if (matchEnclosed && currName.segmentCount() > qualifiedName.segmentCount()
&& currName.lastSegment().equals(qualifiedName.lastSegment())) {
currName = currName.removeFirstSegments(currName.segmentCount() - qualifiedName.segmentCount());
}
if (currName.equals(qualifiedName)) {
results.add(info);
}
}
}
}
return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]);
}
public synchronized ITypeInfo getType(int type, IQualifiedTypeName qualifiedName) {
ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, type));
if (info == null && type != 0) {
info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, 0));
}
return info;
}
public synchronized ITypeInfo getEnclosingType(ITypeInfo info, final int[] kinds) {
IQualifiedTypeName enclosingName = info.getQualifiedTypeName().getEnclosingTypeName();
if (enclosingName != null) {
// try namespace, class, struct, then undefined
ITypeInfo enclosingType = null;
for (int i = 0; enclosingType == null && i < ENCLOSING_TYPES.length; ++i) {
if (ArrayUtil.contains(kinds, ENCLOSING_TYPES[i])) {
enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ENCLOSING_TYPES[i]));
}
}
return enclosingType;
}
return null;
}
public synchronized ITypeInfo getEnclosingNamespace(ITypeInfo info, boolean includeGlobalNamespace) {
IQualifiedTypeName enclosingName = info.getQualifiedTypeName().getEnclosingTypeName();
if (enclosingName != null) {
// look for namespace
ITypeInfo enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ICElement.C_NAMESPACE));
if (enclosingType != null) {
return enclosingType;
}
// try class, struct, then undefined
final int[] kinds = {ICElement.C_CLASS, ICElement.C_STRUCT, 0};
for (int i = 0; enclosingType == null && i < kinds.length; ++i) {
enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, kinds[i]));
}
if (enclosingType != null) {
return getEnclosingNamespace(enclosingType, includeGlobalNamespace);
}
}
if (includeGlobalNamespace)
return fGlobalNamespace;
return null;
}
public synchronized ITypeInfo getRootNamespace(ITypeInfo info, boolean includeGlobalNamespace) {
IQualifiedTypeName qualifiedName = info.getQualifiedTypeName();
if (qualifiedName.isGlobal()) {
if (info.getCElementType() == ICElement.C_NAMESPACE)
return info;
if (includeGlobalNamespace)
return fGlobalNamespace;
return null;
}
IQualifiedTypeName namespace = qualifiedName.removeLastSegments(qualifiedName.segmentCount()-1);
// try namespace, then undefined
ITypeInfo namespaceType = (ITypeInfo) fTypeKeyMap.get(new HashKey(namespace, ICElement.C_NAMESPACE));
if (namespaceType == null)
namespaceType = (ITypeInfo) fTypeKeyMap.get(new HashKey(namespace, 0));
return namespaceType;
}
public synchronized boolean hasEnclosedTypes(final ITypeInfo info) {
final IQualifiedTypeName parentName = info.getQualifiedTypeName();
final boolean[] foundTypes = { false };
accept(new ITypeInfoVisitor() {
public boolean visit(ITypeInfo type) {
if (type != info && parentName.isPrefixOf(type.getQualifiedTypeName())) {
foundTypes[0] = true;
}
return true;
}
public boolean shouldContinue() {
return !foundTypes[0];
}
});
return foundTypes[0];
}
public synchronized ITypeInfo[] getEnclosedTypes(final ITypeInfo enclosedBy, final int kinds[]) {
final IQualifiedTypeName parentName = enclosedBy.getQualifiedTypeName();
final Collection results = new ArrayList();
accept(new ITypeInfoVisitor() {
public boolean visit(ITypeInfo type) {
if (ArrayUtil.contains(kinds, type.getCElementType())) {
IQualifiedTypeName enclosingName = type.getQualifiedTypeName().getEnclosingTypeName();
if (enclosedBy == fGlobalNamespace) {
if (enclosingName == null) {
results.add(type);
} else {
// // check if enclosing parent is namespace
// getRootNamespace(type);
}
} else if (parentName.equals(enclosingName)) {
results.add(type);
}
}
return true;
}
public boolean shouldContinue() { return true; }
});
return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]);
}
public ITypeInfo getGlobalNamespace() {
return fGlobalNamespace;
}
public boolean isUpToDate() {
synchronized(fDeltas) {
return fDeltas.isEmpty();
}
}
public void addDelta(TypeCacheDelta delta) {
synchronized(fDeltas) {
fDeltas.add(delta);
}
}
public void reconcile(boolean enableIndexing, int priority, int delay) {
// check if anything needs to be done
if (deltasRemaining() == 0)
return; // nothing to do
// cancel any scheduled or running jobs for this project
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(TypeCacherJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeCacherJob deltaJob = (TypeCacherJob) jobs[i];
if (deltaJob.getCache().equals(this)) {
deltaJob.cancel();
}
}
// check again, in case some jobs finished in the meantime
if (deltasRemaining() == 0)
return; // nothing to do
TypeCacherJob deltaJob = null;
IndexManager indexManager = CModelManager.getDefault().getIndexManager();
ICDTIndexer indexer = indexManager.getIndexerForProject( fProject );
boolean haveIndexer = (indexer != null && indexer.isIndexEnabled( fProject ));
synchronized(fDeltas) {
if( haveIndexer ){
// grab all the remaining deltas
TypeCacheDelta[] jobDeltas = (TypeCacheDelta[]) fDeltas.toArray(new TypeCacheDelta[fDeltas.size()]);
// create a new job
deltaJob = new TypeCacherJob(this, jobDeltas, enableIndexing);
// assign deltas to job
if (jobDeltas != null) {
for (int i = 0; i < jobDeltas.length; ++i) {
jobDeltas[i].assignToJob(deltaJob);
}
}
} else {
//we don't have an indexer, don't create a job to do these deltas, throw them away
fDeltas.clear();
}
}
if( deltaJob != null ){
// schedule the new job
deltaJob.addJobChangeListener(fJobChangeListener);
deltaJob.setPriority(priority);
deltaJob.schedule(delay);
}
}
public void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor) {
reconcile(enableIndexing, priority, 0);
// wait for jobs to complete
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(TypeCacherJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeCacherJob deltaJob = (TypeCacherJob) jobs[i];
if (deltaJob.getCache().equals(this)) {
try {
deltaJob.join(monitor);
} catch (InterruptedException e) {
}
}
}
}
// returns the number of deltas either not assigned to a job,
// or assigned to a job which is not yet running
private int deltasRemaining() {
// count the left-over deltas
synchronized(fDeltas) {
int count = 0;
for (Iterator i = fDeltas.iterator(); i.hasNext(); ) {
TypeCacheDelta delta = (TypeCacheDelta) i.next();
TypeCacherJob job = delta.getJob();
if (job == null || !job.isRunning()) {
++count;
}
}
return count;
}
}
public void cancelJobs() {
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(TypeCacherJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeCacherJob deltaJob = (TypeCacherJob) jobs[i];
if (deltaJob.getCache().equals(this)) {
deltaJob.cancel();
}
}
jobs = jobManager.find(TypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i];
if (locatorJob.getType().getEnclosingProject().equals(fProject)) {
locatorJob.cancel();
}
}
jobs = jobManager.find(SubTypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i];
if (locatorJob.getType().getEnclosingProject().equals(fProject)) {
locatorJob.cancel();
}
}
}
public void locateType(ITypeInfo info, int priority, int delay) {
ITypeReference location = info.getResolvedReference();
if (location != null)
return; // nothing to do
// cancel any scheduled or running jobs for this type
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(TypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i];
if (locatorJob.getType().equals(info)) {
locatorJob.cancel();
}
}
// check again, in case some jobs finished in the meantime
location = info.getResolvedReference();
if (location != null)
return; // nothing to do
// create a new job
TypeLocatorJob locatorJob = new TypeLocatorJob(info, this, fWorkingCopyProvider);
// schedule the new job
locatorJob.setPriority(priority);
locatorJob.schedule(delay);
}
public ITypeReference locateTypeAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) {
locateType(info, priority, 0);
// wait for jobs to complete
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(TypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i];
if (locatorJob.getType().equals(info)) {
try {
locatorJob.join(monitor);
} catch (InterruptedException e) {
}
}
}
return info.getResolvedReference();
}
public void locateSupertypes(ITypeInfo info, int priority, int delay) {
ITypeInfo[] superTypes = getSupertypes(info);
if (superTypes != null)
return; // nothing to do
locateType(info, priority, delay);
}
public ITypeInfo[] locateSupertypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) {
locateSupertypes(info, priority, 0);
// wait for jobs to complete
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i];
if (locatorJob.getType().equals(info)) {
try {
locatorJob.join(monitor);
} catch (InterruptedException e) {
}
}
}
return getSupertypes(info);
}
public void locateSubtypes(ITypeInfo info, int priority, int delay) {
ITypeInfo[] subTypes = getSubtypes(info);
if (subTypes != null)
return; // nothing to do
// cancel any scheduled or running jobs for this type
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i];
if (locatorJob.getType().equals(info)) {
locatorJob.cancel();
}
}
// check again, in case some jobs finished in the meantime
subTypes = getSubtypes(info);
if (subTypes != null)
return; // nothing to do
// create a new job
SubTypeLocatorJob locatorJob = new SubTypeLocatorJob(info, this, fWorkingCopyProvider);
// schedule the new job
locatorJob.setPriority(priority);
locatorJob.schedule(delay);
}
public ITypeInfo[] locateSubtypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) {
locateSubtypes(info, priority, 0);
// wait for jobs to complete
IJobManager jobManager = Platform.getJobManager();
Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY);
for (int i = 0; i < jobs.length; ++i) {
SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i];
if (locatorJob.getType().equals(info)) {
try {
locatorJob.join(monitor);
} catch (InterruptedException e) {
}
}
}
return getSubtypes(info);
}
}

View file

@ -1,60 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.TypeSearchScope;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.core.resources.IProject;
public class TypeCacheDelta {
private IProject fProject = null;
private ICElementDelta fCElementDelta = null;
private ITypeSearchScope fScope = null;
private TypeCacherJob fJob = null;
public TypeCacheDelta(IProject project, ICElementDelta delta) {
fProject = project;
fCElementDelta = delta;
}
public TypeCacheDelta(IProject project, ITypeSearchScope scope) {
fProject = project;
fScope = scope;
}
public TypeCacheDelta(IProject project) {
fProject = project;
fScope = new TypeSearchScope();
fScope.add(project);
}
public IProject getProject() {
return fProject;
}
public ITypeSearchScope getScope() {
return fScope;
}
public ICElementDelta getCElementDelta() {
return fCElementDelta;
}
public void assignToJob(TypeCacherJob job) {
fJob = job;
}
public TypeCacherJob getJob() {
return fJob;
}
}

View file

@ -1,471 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.browser.IQualifiedTypeName;
import org.eclipse.cdt.core.browser.ITypeCacheChangedListener;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeReference;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.TypeSearchScope;
import org.eclipse.cdt.core.browser.TypeUtil;
import org.eclipse.cdt.core.model.ElementChangedEvent;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.cdt.internal.core.model.CModelManager;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.Job;
public class TypeCacheManager implements ITypeCacheChangedListener, IndexManager.IIndexerSelectionListener {
private static final TypeCacheManager fgInstance = new TypeCacheManager();
private Map fCacheMap;
private IWorkingCopyProvider fWorkingCopyProvider;
private ArrayList fChangeListeners = new ArrayList();
private static final int INITIAL_TYPE_MAP_SIZE = 50;
//TODO make this a WeakHashMap or LRUCache
private Map fTypeToElementMap = new HashMap(INITIAL_TYPE_MAP_SIZE);
private Map fElementToTypeMap = new HashMap(INITIAL_TYPE_MAP_SIZE);
private boolean processTypeCacheEvents = true;
private TypeCacheManager() {
fCacheMap = new HashMap();
CModelManager.getDefault().getIndexManager().subscribeForIndexerChangeNotifications( this );
}
public static TypeCacheManager getInstance() {
return fgInstance;
}
protected void finalize() throws Throwable {
CModelManager.getDefault().getIndexManager().unSubscribeForIndexerChangeNotifications( this );
super.finalize();
}
public void setWorkingCopyProvider(IWorkingCopyProvider workingCopyProvider) {
fWorkingCopyProvider = workingCopyProvider;
}
public synchronized void updateProject(IProject project) {
// TODO finer-grained flush needed, for now just flush the whole map
fTypeToElementMap.clear();
fElementToTypeMap.clear();
addCacheDelta(project, null);
}
public synchronized void processElementChanged(ElementChangedEvent event, boolean enableIndexing) {
int deltaCount = processDelta(event.getDelta());
if (deltaCount > 0) {
// TODO finer-grained flush needed, for now just flush the whole map
fTypeToElementMap.clear();
fElementToTypeMap.clear();
reconcile(enableIndexing, Job.BUILD, 0);
}
}
private static final int PATH_ENTRY_FLAGS = ICElementDelta.F_ADDED_PATHENTRY_SOURCE
| ICElementDelta.F_REMOVED_PATHENTRY_SOURCE
| ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE
| ICElementDelta.F_CHANGED_PATHENTRY_MACRO
| ICElementDelta.F_PATHENTRY_REORDER;
private int processDelta(ICElementDelta delta) {
ICElement elem = delta.getElement();
boolean added = (delta.getKind() == ICElementDelta.ADDED);
boolean removed = (delta.getKind() == ICElementDelta.REMOVED);
boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0);
boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0);
boolean openedOrClosed = (((delta.getFlags() & ICElementDelta.F_CLOSED) != 0) || ((delta.getFlags() & ICElementDelta.F_OPENED) != 0));
boolean hasChildren = ((delta.getFlags() & ICElementDelta.F_CHILDREN) != 0);
int deltaCount = 0;
switch (elem.getElementType()) {
case ICElement.C_PROJECT:
case ICElement.C_CCONTAINER: {
ICProject cProject = elem.getCProject();
IProject project = cProject.getProject();
if (added || removed || pathEntryChanged || openedOrClosed) {
addCacheDelta(project, delta);
++deltaCount;
}
}
break;
case ICElement.C_UNIT: {
ICProject cProject = elem.getCProject();
IProject project = cProject.getProject();
ITranslationUnit unit = (ITranslationUnit) elem;
if (unit.isWorkingCopy()) {
deltaCount += processWorkingCopyDelta(delta);
return deltaCount;
}
if (added || removed || pathEntryChanged || contentChanged) {
addCacheDelta(project, delta);
++deltaCount;
}
}
break;
case ICElement.C_INCLUDE:
case ICElement.C_NAMESPACE:
case ICElement.C_TEMPLATE_CLASS:
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
case ICElement.C_UNION:
case ICElement.C_ENUMERATION:
case ICElement.C_TYPEDEF:
{
ICProject cProject = elem.getCProject();
IProject project = cProject.getProject();
if (added || removed) {
addCacheDelta(project, delta);
++deltaCount;
}
}
break;
}
if (hasChildren) {
ICElementDelta[] children = delta.getAffectedChildren();
if (children != null) {
for (int i = 0; i < children.length; ++i) {
deltaCount += processDelta(children[i]);
}
}
}
return deltaCount;
}
private void addCacheDelta(IProject project, ICElementDelta delta) {
if (delta == null) {
getCache(project).addDelta(new TypeCacheDelta(project));
} else {
getCache(project).addDelta(new TypeCacheDelta(project, delta));
}
}
private int processWorkingCopyDelta(ICElementDelta delta) {
// ignore workies copies for now
return 0;
/* ICElement elem = delta.getElement();
boolean added = (delta.getKind() == ICElementDelta.ADDED);
boolean removed = (delta.getKind() == ICElementDelta.REMOVED);
boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0);
boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0);
boolean hasChildren = ((delta.getFlags() & ICElementDelta.F_CHILDREN) != 0);
switch (elem.getElementType()) {
case ICElement.C_UNIT: {
ICProject cProject = elem.getCProject();
IProject project = cProject.getProject();
if (added || removed || pathEntryChanged || contentChanged) {
TypeCacheDelta cacheDelta = new TypeCacheDelta(project, delta);
getCache(project).addDelta(cacheDelta);
}
}
break;
case ICElement.C_INCLUDE:
case ICElement.C_NAMESPACE:
case ICElement.C_TEMPLATE_CLASS:
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
case ICElement.C_UNION:
case ICElement.C_ENUMERATION:
case ICElement.C_TYPEDEF:
{
ICProject cProject = elem.getCProject();
IProject project = cProject.getProject();
if (added || removed) {
TypeCacheDelta cacheDelta = new TypeCacheDelta(project, delta);
getCache(project).addDelta(cacheDelta);
}
}
break;
}
if (hasChildren) {
ICElementDelta[] children = delta.getAffectedChildren();
if (children != null) {
for (int i = 0; i < children.length; ++i) {
processWorkingCopyDelta(children[i]);
}
}
}
*/
}
public synchronized ITypeCache getCache(IProject project) {
synchronized(fCacheMap) {
ITypeCache cache = (ITypeCache) fCacheMap.get(project);
if (cache == null) {
cache = new TypeCache(project, fWorkingCopyProvider, this);
fCacheMap.put(project, cache);
}
return cache;
}
}
public synchronized void reconcile(boolean enableIndexing, int priority, int delay) {
if (!(processTypeCacheEvents))
return;
TypeSearchScope workspaceScope = new TypeSearchScope(true);
IProject[] projects = workspaceScope.getEnclosingProjects();
for (int i = 0; i < projects.length; ++i) {
ITypeCache cache = getCache(projects[i]);
cache.reconcile(enableIndexing, priority, delay);
}
}
public synchronized void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor) {
if (!(processTypeCacheEvents))
return;
TypeSearchScope workspaceScope = new TypeSearchScope(true);
IProject[] projects = workspaceScope.getEnclosingProjects();
for (int i = 0; i < projects.length; ++i) {
ITypeCache cache = getCache(projects[i]);
cache.reconcileAndWait(enableIndexing, priority, monitor);
}
}
public void cancelJobs() {
IJobManager jobManager = Platform.getJobManager();
jobManager.cancel(TypeCacherJob.FAMILY);
jobManager.cancel(TypeLocatorJob.FAMILY);
}
public ITypeInfo[] locateSuperTypesAndWait(ITypeInfo info, boolean enableIndexing, int priority, IProgressMonitor monitor) {
ITypeInfo[] superTypes = info.getSuperTypes();
if (superTypes == null) {
// cancel background jobs
IProject project = info.getEnclosingProject();
getCache(project).cancelJobs();
// start the search job
getCache(project).locateSupertypesAndWait(info, priority, monitor);
superTypes = info.getSuperTypes();
// resume background jobs
reconcile(enableIndexing, Job.BUILD, 0);
}
return superTypes;
}
public ITypeInfo[] locateSubTypesAndWait(ITypeInfo info, boolean enableIndexing, int priority, IProgressMonitor monitor) {
ITypeInfo[] subTypes = info.getSubTypes();
if (subTypes == null) {
// cancel background jobs
IProject project = info.getEnclosingProject();
getCache(project).cancelJobs();
// start the search job
getCache(project).locateSubtypesAndWait(info, priority, monitor);
subTypes = info.getSubTypes();
// resume background jobs
reconcile(enableIndexing, Job.BUILD, 0);
}
return subTypes;
}
public void updateCache(ITypeSearchScope scope, IProgressMonitor monitor) {
// schedule jobs to update cache
IProject[] projects = scope.getEnclosingProjects();
monitor.beginTask(TypeCacheMessages.getString("AllTypesCache.updateCache.taskName"), projects.length); //$NON-NLS-1$
for (int i = 0; i < projects.length; ++i) {
IProject project = projects[i];
// wait for any running jobs to finish
getCache(project).reconcileAndWait(true, Job.SHORT, new SubProgressMonitor(monitor, 1));
}
monitor.done();
}
/**
* Resolves a type location.
*
* @param info the type to search for
* @param monitor the progress monitor
*/
public ITypeReference resolveTypeLocation(ITypeInfo info, IProgressMonitor monitor, boolean enableIndexing) {
ITypeReference location = info.getResolvedReference();
if (location == null) {
// cancel background jobs
IProject project = info.getEnclosingProject();
ITypeCache cache = getCache(project);
cache.cancelJobs();
// start the search job
cache.locateTypeAndWait(info, Job.SHORT, monitor);
// get the newly parsed location
location = info.getResolvedReference();
// resume background jobs
reconcile(enableIndexing, Job.BUILD, 0);
}
return location;
}
public void addTypeCacheChangedListener(ITypeCacheChangedListener listener) {
// add listener only if it is not already present
synchronized(fChangeListeners) {
if (!fChangeListeners.contains(listener)) {
fChangeListeners.add(listener);
}
}
}
public void removeTypeCacheChangedListener(ITypeCacheChangedListener listener) {
synchronized(fChangeListeners) {
fChangeListeners.remove(listener);
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.browser.ITypeCacheChangedListener#typeCacheChanged(org.eclipse.core.resources.IProject)
*/
public synchronized void typeCacheChanged(final IProject project) {
// clone so that a listener cannot have a side-effect on this list when being notified
ArrayList listeners;
synchronized(fChangeListeners) {
listeners = (ArrayList) fChangeListeners.clone();
}
for (Iterator i = listeners.iterator(); i.hasNext(); ) {
final ITypeCacheChangedListener listener = (ITypeCacheChangedListener) i.next();
Platform.run(new ISafeRunnable() {
public void handleException(Throwable e) {
IStatus status = new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, IStatus.ERROR, "Exception occurred in listener of type cache change notification", e); //$NON-NLS-1$
CCorePlugin.log(status);
}
public void run() throws Exception {
listener.typeCacheChanged(project);
}
});
}
}
public ITypeInfo getTypeForElement(ICElement element, boolean forceUpdate, boolean forceResolve, boolean enableIndexing, IProgressMonitor monitor) {
if (element.exists()) {
ITypeInfo cachedInfo = (ITypeInfo) fElementToTypeMap.get(element);
if (cachedInfo != null && cachedInfo.exists())
return cachedInfo;
}
IQualifiedTypeName qualifiedName = TypeUtil.getFullyQualifiedName(element);
if (qualifiedName != null) {
ICProject cProject = element.getCProject();
IProject project = cProject.getProject();
ITypeCache cache = getCache(project);
if (!cache.isUpToDate() && forceUpdate) {
if (monitor == null)
monitor = new NullProgressMonitor();
// wait for any running jobs to finish
cache.reconcileAndWait(true, Job.SHORT, monitor);
}
ITypeInfo info = cache.getType(element.getElementType(), qualifiedName);
if (info != null) {
ITypeReference ref = info.getResolvedReference();
if (ref == null && forceResolve) {
if (monitor == null)
monitor = new NullProgressMonitor();
ref = resolveTypeLocation(info, monitor, enableIndexing);
}
// cache for later use
fElementToTypeMap.put(element, info);
return info;
}
}
return null;
}
public ICElement getElementForType(ITypeInfo type, boolean forceUpdate, boolean forceResolve, boolean enableIndexing, IProgressMonitor monitor) {
if (type.exists()) {
ICElement cachedElem = (ICElement) fTypeToElementMap.get(type);
if (cachedElem != null && cachedElem.exists())
return cachedElem;
}
IProject project = type.getEnclosingProject();
ITypeCache cache = getCache(project);
if (!cache.isUpToDate() && forceUpdate) {
if (monitor == null)
monitor = new NullProgressMonitor();
// wait for any running jobs to finish
cache.reconcileAndWait(true, Job.SHORT, monitor);
//TODO replace type with new type from cache???
}
ITypeReference ref = type.getResolvedReference();
if (ref == null && forceResolve) {
ref = resolveTypeLocation(type, monitor, enableIndexing);
}
if (ref != null) {
ICElement[] elems = ref.getCElements();
if (elems != null && elems.length > 0) {
ICElement foundElem = elems[0];
if (elems.length > 1) {
for (int i = 0; i < elems.length; ++i) {
ICElement elem = elems[i];
if (elem.getElementType() == type.getCElementType() && elem.getElementName().equals(type.getName())) {
//TODO should check fully qualified name
foundElem = elem;
break;
}
}
}
if (foundElem != null) {
// cache for later use
fTypeToElementMap.put(type, foundElem);
return foundElem;
}
}
}
return null;
}
public boolean getProcessTypeCacheEvents() {
return processTypeCacheEvents;
}
public void setProcessTypeCacheEvents(boolean processTypeCacheEvents) {
this.processTypeCacheEvents = processTypeCacheEvents;
}
public void indexerSelectionChanged(IProject project) {
addCacheDelta(project, null );
}
}

View file

@ -1,50 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class TypeCacheMessages {
private static final String RESOURCE_BUNDLE= TypeCacheMessages.class.getName();
private static ResourceBundle fgResourceBundle;
static {
try {
fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
} catch (MissingResourceException x) {
fgResourceBundle = null;
}
}
private TypeCacheMessages() {
}
public static String getString(String key) {
try {
return fgResourceBundle.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
} catch (NullPointerException e) {
return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
public static String getFormattedString(String key, String arg) {
return getFormattedString(key, new String[] { arg });
}
public static String getFormattedString(String key, String[] args) {
return MessageFormat.format(getString(key), args);
}
}

View file

@ -1,23 +0,0 @@
###############################################################################
# Copyright (c) 2000, 2004 QNX Software Systems and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# QNX Software Systems - Initial API and implementation
###############################################################################
AllTypesCache.updateCache.taskName=Updating Type Cache...
TypeCacherJob.defaultJobName=Type Cache
TypeCacherJob.jobName=Type Cache [{0}]
TypeCacherJob.taskName=Updating Type Cache...
TypeLocatorJob.jobName=Type Locator
TypeLocatorJob.taskName=Searching for Type Declaration...
SubTypeLocatorJob.jobName=Subtype Locator
SubTypeLocatorJob.taskName=Searching for Subtypes...
TypeCache.globalNamespace=(global)

View file

@ -1,275 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.TypeSearchScope;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementDelta;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.model.CModelManager;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
/**
* Background job for filling the type cache.
* @see org.eclipse.core.runtime.jobs.Job
* @since 3.0
*/
public class TypeCacherJob extends BasicJob {
public static final Object FAMILY = new Object();
private IndexManager fIndexManager;
private ITypeCache fTypeCache;
private TypeCacheDelta[] fDeltas;
private boolean fEnableIndexing;
private boolean fIndexerIsBusy;
public TypeCacherJob(ITypeCache typeCache, TypeCacheDelta[] deltas, boolean enableIndexing) {
super(TypeCacheMessages.getString("TypeCacherJob.defaultJobName"), FAMILY); //$NON-NLS-1$
fTypeCache = typeCache;
fDeltas = deltas;
fEnableIndexing = enableIndexing;
fIndexerIsBusy = false;
fIndexManager = CModelManager.getDefault().getIndexManager();
setPriority(BUILD);
setSystem(true);
setRule(typeCache);
setName(TypeCacheMessages.getFormattedString("TypeCacherJob.jobName", fTypeCache.getProject().getName())); //$NON-NLS-1$
}
public ITypeCache getCache() {
return fTypeCache;
}
public TypeCacheDelta[] getDeltas() {
return fDeltas;
}
public boolean isIndexerBusy() {
return fIndexerIsBusy;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor)
*/
protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException {
boolean success = false;
long startTime = System.currentTimeMillis();
trace("TypeCacherJob: started"); //$NON-NLS-1$
try {
int totalWork = 100;
monitor.beginTask(TypeCacheMessages.getString("TypeCacherJob.taskName"), totalWork); //$NON-NLS-1$
// figure out what needs to be flushed
TypeSearchScope flushScope = new TypeSearchScope();
if (fDeltas != null) {
for (int i = 0; i < fDeltas.length; ++i) {
TypeCacheDelta delta = fDeltas[i];
prepareToFlush(delta, flushScope);
}
}
if (monitor.isCanceled())
throw new InterruptedException();
// flush the cache
int flushWork = 0;
if (!flushScope.isEmpty()) {
flushWork = totalWork / 4;
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, flushWork);
flush(flushScope, subMonitor);
}
// update the cache
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, totalWork - flushWork);
update(flushScope, subMonitor);
if (monitor.isCanceled())
throw new InterruptedException();
} finally {
long executionTime = System.currentTimeMillis() - startTime;
if (success)
trace("TypeCacherJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
else
trace("TypeCacherJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
monitor.done();
}
return Status.OK_STATUS;
}
private void flush(ITypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException {
// flush the cache
boolean success = true;
IProject project = fTypeCache.getProject();
monitor.beginTask("", 100); //$NON-NLS-1$
fTypeCache.flush(scope);
if (!scope.encloses(project)) {
if (project.exists() && project.isOpen()) {
success = doIndexerJob(new IndexerDependenciesJob(fIndexManager, fTypeCache, scope), monitor);
}
}
if (!success || monitor.isCanceled()) {
throw new InterruptedException();
}
monitor.done();
}
private void update(ITypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException {
boolean success = true;
IProject project = fTypeCache.getProject();
monitor.beginTask("", 100); //$NON-NLS-1$
if (project.exists() && project.isOpen()) {
success = doIndexerJob(new IndexerTypesJob2(fIndexManager, fTypeCache, scope), monitor);
}
if (!success || monitor.isCanceled()) {
throw new InterruptedException();
}
monitor.done();
}
private boolean doIndexerJob(IndexerJob job, IProgressMonitor monitor) {
if (!fEnableIndexing) {
return false;
}
// check if indexer is busy
fIndexerIsBusy = false;
try {
fIndexManager.performConcurrentJob(new DummyIndexerJob(fIndexManager, fTypeCache.getProject()),
ICSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, new NullProgressMonitor(), null);
} catch (OperationCanceledException e) {
fIndexerIsBusy = true;
}
// do an immediate (but possibly incomplete) search
// if fIndexerIsBusy the cache will stay dirty and we'll hit the indexer again next time
return fIndexManager.performConcurrentJob(job,
ICSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor, null);
}
private boolean doIndexerJob(IndexerJob2 job, IProgressMonitor monitor) {
if (!fEnableIndexing) {
return false;
}
// check if indexer is busy
fIndexerIsBusy = false;
try {
fIndexManager.performConcurrentJob(new DummyIndexerJob(fIndexManager, fTypeCache.getProject()),
ICSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, new NullProgressMonitor(), null);
} catch (OperationCanceledException e) {
fIndexerIsBusy = true;
}
// do an immediate (but possibly incomplete) search
// if fIndexerIsBusy the cache will stay dirty and we'll hit the indexer again next time
return fIndexManager.performConcurrentJob(job,
ICSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor, null);
}
private static final int PATH_ENTRY_FLAGS = ICElementDelta.F_ADDED_PATHENTRY_SOURCE
| ICElementDelta.F_REMOVED_PATHENTRY_SOURCE
| ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE
| ICElementDelta.F_CHANGED_PATHENTRY_MACRO
| ICElementDelta.F_PATHENTRY_REORDER;
private void prepareToFlush(TypeCacheDelta cacheDelta, ITypeSearchScope scope) {
ITypeSearchScope deltaScope = cacheDelta.getScope();
if (deltaScope != null)
scope.add(deltaScope);
ICElementDelta delta = cacheDelta.getCElementDelta();
if (delta != null) {
ICElement elem = delta.getElement();
boolean added = (delta.getKind() == ICElementDelta.ADDED);
boolean removed = (delta.getKind() == ICElementDelta.REMOVED);
boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0);
boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0);
switch (elem.getElementType()) {
case ICElement.C_MODEL: {
if (added || removed) {
scope.add(elem);
}
}
break;
case ICElement.C_PROJECT: {
if (added || removed || pathEntryChanged) {
scope.add(elem);
}
}
break;
case ICElement.C_CCONTAINER: {
if (added || removed || pathEntryChanged) {
scope.add(elem);
}
}
break;
case ICElement.C_UNIT: {
if (added || removed || pathEntryChanged || contentChanged) {
scope.add(elem);
}
}
break;
case ICElement.C_INCLUDE:
case ICElement.C_NAMESPACE:
case ICElement.C_TEMPLATE_CLASS:
case ICElement.C_CLASS:
case ICElement.C_STRUCT:
case ICElement.C_UNION:
case ICElement.C_ENUMERATION:
case ICElement.C_TYPEDEF:
{
//TODO handle working copies
if (added || removed) {
scope.add(elem);
}
}
break;
}
}
}
private static final class DummyIndexerJob extends IndexerJob {
public DummyIndexerJob(IndexManager indexManager, IProject project) {
super(indexManager, project);
}
protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) {
return false;
}
}
}

View file

@ -1,67 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
public class TypeLocatorJob extends BasicJob {
public static final Object FAMILY = new Object();
private ITypeInfo fLocateType;
private ITypeCache fTypeCache;
private IWorkingCopyProvider fWorkingCopyProvider;
public TypeLocatorJob(ITypeInfo info, ITypeCache typeCache, IWorkingCopyProvider workingCopyProvider) {
super(TypeCacheMessages.getString("TypeLocatorJob.jobName"), FAMILY); //$NON-NLS-1$
fLocateType = info;
fTypeCache = typeCache;
fWorkingCopyProvider= workingCopyProvider;
}
public ITypeInfo getType() {
return fLocateType;
}
protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException {
boolean success = false;
long startTime = System.currentTimeMillis();
trace("TypeLocatorJob: started"); //$NON-NLS-1$
try {
monitor.beginTask(TypeCacheMessages.getString("TypeLocatorJob.taskName"), 100); //$NON-NLS-1$
if (monitor.isCanceled())
throw new InterruptedException();
TypeParser parser = new TypeParser(fTypeCache, fWorkingCopyProvider);
success = parser.findType(fLocateType, new SubProgressMonitor(monitor, 100));
if (monitor.isCanceled())
throw new InterruptedException();
} finally {
long executionTime = System.currentTimeMillis() - startTime;
if (success)
trace("TypeLocatorJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
else
trace("TypeLocatorJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$
monitor.done();
}
return Status.OK_STATUS;
}
}

View file

@ -1,955 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* QNX Software Systems - adapted for type search
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.cache;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.ITypeReference;
import org.eclipse.cdt.core.browser.ITypeSearchScope;
import org.eclipse.cdt.core.browser.QualifiedTypeName;
import org.eclipse.cdt.core.browser.TypeInfo;
import org.eclipse.cdt.core.browser.TypeReference;
import org.eclipse.cdt.core.browser.TypeSearchScope;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.model.IWorkingCopy;
import org.eclipse.cdt.core.model.IWorkingCopyProvider;
import org.eclipse.cdt.core.parser.CodeReader;
import org.eclipse.cdt.core.parser.DefaultProblemHandler;
import org.eclipse.cdt.core.parser.IParser;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IScannerInfoProvider;
import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate;
import org.eclipse.cdt.core.parser.ISourceElementRequestor;
import org.eclipse.cdt.core.parser.ParseError;
import org.eclipse.cdt.core.parser.ParserFactory;
import org.eclipse.cdt.core.parser.ParserFactoryError;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ParserTimeOut;
import org.eclipse.cdt.core.parser.ParserUtil;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.core.parser.ast.ASTClassKind;
import org.eclipse.cdt.core.parser.ast.ASTNotImplementedException;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTBaseSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTClassReference;
import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTCodeScope;
import org.eclipse.cdt.core.parser.ast.IASTCompilationUnit;
import org.eclipse.cdt.core.parser.ast.IASTDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumerationReference;
import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumeratorReference;
import org.eclipse.cdt.core.parser.ast.IASTField;
import org.eclipse.cdt.core.parser.ast.IASTFieldReference;
import org.eclipse.cdt.core.parser.ast.IASTFunction;
import org.eclipse.cdt.core.parser.ast.IASTFunctionReference;
import org.eclipse.cdt.core.parser.ast.IASTInclusion;
import org.eclipse.cdt.core.parser.ast.IASTLinkageSpecification;
import org.eclipse.cdt.core.parser.ast.IASTMacro;
import org.eclipse.cdt.core.parser.ast.IASTMethod;
import org.eclipse.cdt.core.parser.ast.IASTMethodReference;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceReference;
import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement;
import org.eclipse.cdt.core.parser.ast.IASTParameterReference;
import org.eclipse.cdt.core.parser.ast.IASTQualifiedNameElement;
import org.eclipse.cdt.core.parser.ast.IASTReference;
import org.eclipse.cdt.core.parser.ast.IASTScope;
import org.eclipse.cdt.core.parser.ast.IASTTemplateDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTTemplateInstantiation;
import org.eclipse.cdt.core.parser.ast.IASTTemplateParameterReference;
import org.eclipse.cdt.core.parser.ast.IASTTemplateSpecialization;
import org.eclipse.cdt.core.parser.ast.IASTTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTTypedefReference;
import org.eclipse.cdt.core.parser.ast.IASTUsingDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTUsingDirective;
import org.eclipse.cdt.core.parser.ast.IASTVariable;
import org.eclipse.cdt.core.parser.ast.IASTVariableReference;
import org.eclipse.cdt.internal.core.browser.util.SimpleStack;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
public class TypeParser implements ISourceElementRequestor {
private ITypeCache fTypeCache;
private ITypeSearchScope fScope;
private IProject fProject;
private IWorkingCopyProvider fWorkingCopyProvider;
private IProgressMonitor fProgressMonitor;
ISourceElementCallbackDelegate fLastDeclaration;
private final SimpleStack fScopeStack = new SimpleStack();
private final SimpleStack fResourceStack = new SimpleStack();
private ITypeInfo fTypeToFind;
private ITypeInfo fSuperTypeToFind;
private Set fProcessedTypes = new HashSet();
private boolean fFoundType;
IParser fParser = null;
ParserTimeOut fTimeoutThread = null;
public TypeParser(ITypeCache typeCache, IWorkingCopyProvider provider) {
fTypeCache = typeCache;
fWorkingCopyProvider = provider;
fTimeoutThread = new ParserTimeOut("TypeParser TimeOut Thread"); //$NON-NLS-1$
fTimeoutThread.setThreadPriority(Thread.MAX_PRIORITY);
}
public void parseTypes(TypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException {
if (monitor == null)
monitor = new NullProgressMonitor();
if (monitor.isCanceled())
throw new InterruptedException();
fScope = new TypeSearchScope(scope);
Map workingCopyMap = null;
if (fWorkingCopyProvider != null) {
IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies();
if (workingCopies != null && workingCopies.length > 0) {
workingCopyMap = new HashMap(workingCopies.length);
for (int i = 0; i < workingCopies.length; ++i) {
IWorkingCopy workingCopy = workingCopies[i];
IPath wcPath = workingCopy.getOriginalElement().getPath();
if (fScope.encloses(wcPath)) {
// // always flush working copies from cache?
// fTypeCache.flush(wcPath);
fScope.add(wcPath, false, null);
workingCopyMap.put(wcPath, workingCopy);
}
}
}
}
fProject = fTypeCache.getProject();
IPath[] searchPaths = fTypeCache.getPaths(fScope);
Collection workingCopyPaths = new HashSet();
if (workingCopyMap != null) {
collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths);
//TODO what about working copies outside the workspace?
}
monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$
try {
for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) {
IPath path = (IPath) pathIter.next();
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
}
for (int i = 0; i < searchPaths.length; ++i) {
IPath path = searchPaths[i];
if (!workingCopyPaths.contains(path)) {
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
}
} finally {
monitor.done();
}
}
public boolean findType(ITypeInfo info, IProgressMonitor monitor) throws InterruptedException {
if (monitor == null)
monitor = new NullProgressMonitor();
if (monitor.isCanceled())
throw new InterruptedException();
fScope = new TypeSearchScope();
ITypeReference[] refs = info.getReferences();
if (refs == null || refs.length == 0)
return false; // no source references
fScope.add(refs[0].getPath(), false, null);
// for (int i = 0; i < refs.length; ++i) {
// ITypeReference location = refs[i];
// IPath path = location.getPath();
// fScope.add(path, false, null);
// }
Map workingCopyMap = null;
if (fWorkingCopyProvider != null) {
IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies();
if (workingCopies != null && workingCopies.length > 0) {
workingCopyMap = new HashMap(workingCopies.length);
for (int i = 0; i < workingCopies.length; ++i) {
IWorkingCopy workingCopy = workingCopies[i];
IPath wcPath = workingCopy.getOriginalElement().getPath();
if (fScope.encloses(wcPath)) {
// // always flush working copies from cache?
// fTypeCache.flush(wcPath);
fScope.add(wcPath, false, null);
workingCopyMap.put(wcPath, workingCopy);
}
}
}
}
fProject = fTypeCache.getProject();
IPath[] searchPaths = fTypeCache.getPaths(fScope);
Collection workingCopyPaths = new HashSet();
if (workingCopyMap != null) {
collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths);
//TODO what about working copies outside the workspace?
}
monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$
try {
fTypeToFind = info;
fFoundType = false;
for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) {
IPath path = (IPath) pathIter.next();
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
if (fFoundType)
return true;
}
for (int i = 0; i < searchPaths.length; ++i) {
IPath path = searchPaths[i];
if (!workingCopyPaths.contains(path)) {
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
if (fFoundType)
return true;
}
} finally {
fTypeToFind = null;
fFoundType = false;
monitor.done();
}
return false;
}
public boolean findSubTypes(ITypeInfo info, IProgressMonitor monitor) throws InterruptedException {
if (monitor == null)
monitor = new NullProgressMonitor();
if (monitor.isCanceled())
throw new InterruptedException();
fScope = new TypeSearchScope();
ITypeReference[] refs = info.getDerivedReferences();
if (refs == null || refs.length == 0)
return false; // no source references
for (int i = 0; i < refs.length; ++i) {
ITypeReference location = refs[i];
IPath path = location.getPath();
fScope.add(path, false, null);
}
Map workingCopyMap = null;
if (fWorkingCopyProvider != null) {
IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies();
if (workingCopies != null && workingCopies.length > 0) {
workingCopyMap = new HashMap(workingCopies.length);
for (int i = 0; i < workingCopies.length; ++i) {
IWorkingCopy workingCopy = workingCopies[i];
IPath wcPath = workingCopy.getOriginalElement().getPath();
if (fScope.encloses(wcPath)) {
// // always flush working copies from cache?
// fTypeCache.flush(wcPath);
fScope.add(wcPath, false, null);
workingCopyMap.put(wcPath, workingCopy);
}
}
}
}
fProject = fTypeCache.getProject();
IPath[] searchPaths = fTypeCache.getPaths(fScope);
Collection workingCopyPaths = new HashSet();
if (workingCopyMap != null) {
collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths);
//TODO what about working copies outside the workspace?
}
monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$
try {
fTypeToFind = null;
fSuperTypeToFind = info;
fFoundType = false;
for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) {
IPath path = (IPath) pathIter.next();
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
}
for (int i = 0; i < searchPaths.length; ++i) {
IPath path = searchPaths[i];
if (!workingCopyPaths.contains(path)) {
parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
}
} finally {
fTypeToFind = null;
fFoundType = false;
monitor.done();
}
return false;
}
private void collectWorkingCopiesInProject(Map workingCopyMap, IProject project, Collection workingCopyPaths) {
for (Iterator mapIter = workingCopyMap.entrySet().iterator(); mapIter.hasNext(); ) {
Map.Entry entry = (Map.Entry) mapIter.next();
IPath path = (IPath) entry.getKey();
IWorkingCopy copy = (IWorkingCopy) entry.getValue();
ICProject cProject = copy.getCProject();
if (cProject != null && cProject.getProject().equals(project)) {
workingCopyPaths.add(path);
}
}
}
private void parseSource(IPath path, IProject project, Map workingCopyMap, IProgressMonitor progressMonitor) throws InterruptedException {
if (progressMonitor.isCanceled())
throw new InterruptedException();
// count how many types were indexed for this path
TypeSearchScope pathScope = new TypeSearchScope();
pathScope.add(path, false, project);
int typeCount = fTypeCache.getTypes(pathScope).length;
progressMonitor.beginTask("", typeCount); //$NON-NLS-1$
try {
IWorkingCopy workingCopy = null;
if (workingCopyMap != null) {
workingCopy = (IWorkingCopy) workingCopyMap.get(path);
}
ParserLanguage language = getLanguage(project, workingCopy);
if (language == null) {
return; // not C or C++
}
CodeReader reader = null;
Object stackObject = null;
IResource resource = null;
if (workingCopy != null) {
reader = createWorkingCopyReader(workingCopy);
resource = workingCopy.getResource();
if (resource != null) {
path = resource.getLocation();
}
stackObject = workingCopy;
} else {
IWorkspace workspace = CCorePlugin.getWorkspace();
if (workspace != null) {
IWorkspaceRoot wsRoot = workspace.getRoot();
if (wsRoot != null) {
resource = wsRoot.findMember(path, true);
}
}
if (resource != null) {
reader = createResourceReader(resource);
path = resource.getLocation();
stackObject = resource;
} else {
reader = createFileReader(path);
stackObject = path;
}
}
if (reader != null) {
fResourceStack.clear();
fScopeStack.clear();
fResourceStack.push(stackObject);
parseContents(path, resource, project, reader, language, progressMonitor);
fResourceStack.pop();
}
} finally {
progressMonitor.done();
}
}
private ParserLanguage getLanguage(IProject project, IWorkingCopy workingCopy) {
ParserLanguage projectLanguage = null;
if (project != null) {
if (CoreModel.hasCCNature(project)) {
projectLanguage = ParserLanguage.CPP;
} else if (CoreModel.hasCNature(project)) {
projectLanguage = ParserLanguage.C;
}
}
if (workingCopy != null) {
ParserLanguage workingCopyLanguage = null;
ITranslationUnit unit = workingCopy.getTranslationUnit();
if (unit != null) {
if (unit.isCLanguage()) {
workingCopyLanguage = ParserLanguage.C;
} else if (unit.isCXXLanguage()) {
workingCopyLanguage = ParserLanguage.CPP;
}
}
if (workingCopyLanguage != null) {
if (projectLanguage == null) {
return workingCopyLanguage;
} else if (projectLanguage.equals(ParserLanguage.CPP)) {
// if project is CPP then working copy must be CPP
return projectLanguage;
} else {
return workingCopyLanguage;
}
}
}
return projectLanguage;
}
private CodeReader createWorkingCopyReader(IWorkingCopy workingCopy) {
CodeReader reader = null;
IResource resource = workingCopy.getResource();
if (resource != null && resource.isAccessible()) {
char[] contents = workingCopy.getContents();
if (contents != null)
reader = new CodeReader(resource.getLocation().toOSString(), contents);
}
return reader;
}
private CodeReader createResourceReader(IResource resource) {
CodeReader reader = null;
if (resource.isAccessible() && resource instanceof IFile) {
IFile file = (IFile) resource;
InputStream contents = null;
try {
contents = file.getContents();
if (contents != null)
reader = new CodeReader(resource.getLocation().toOSString(), file.getCharset(), contents);
} catch (CoreException ex) {
ex.printStackTrace();
} catch (IOException e) {
} finally {
if (contents != null) {
try {
contents.close();
} catch (IOException io) {
// ignore
}
}
}
}
return reader;
}
private CodeReader createFileReader(IPath path) {
CodeReader reader = null;
try {
reader = new CodeReader(path.toOSString());
} catch (IOException ex) {
ex.printStackTrace();
}
return reader;
}
private void parseContents(IPath realPath, IResource resource, IProject project, CodeReader reader, ParserLanguage language, IProgressMonitor progressMonitor) throws InterruptedException {
IScannerInfo scanInfo = null;
if (project != null) {
//TODO temporary workaround to catch managed build exceptions
try {
IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project);
if (provider != null) {
IScannerInfo buildScanInfo = provider.getScannerInformation(resource != null ? resource : project);
if (buildScanInfo != null)
scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (scanInfo == null)
scanInfo = new ScannerInfo();
try {
fProgressMonitor = progressMonitor;
IScanner scanner = ParserFactory.createScanner(reader, scanInfo,
ParserMode.STRUCTURAL_PARSE, language, this, ParserUtil.getScannerLogService(), null);
fParser = ParserFactory.createParser(scanner, this, ParserMode.STRUCTURAL_PARSE, language, ParserUtil.getParserLogService());
// start timer
int timeout = getParserTimeout();
if (timeout > 0) {
fTimeoutThread.setTimeout(timeout);
fTimeoutThread.setParser(fParser);
while (!fTimeoutThread.isReadyToRun()){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
fTimeoutThread.startTimer();
}
fParser.parse();
} catch (ParserFactoryError e) {
CCorePlugin.log(e);
} catch (ParseError e) {
// no need to log
// CCorePlugin.log(e);
} catch (OperationCanceledException e) {
throw new InterruptedException();
} catch (Exception e) {
CCorePlugin.log(e);
} finally {
// stop timer
fTimeoutThread.stopTimer();
fTimeoutThread.setParser(null);
fProgressMonitor = null;
fParser = null;
}
}
public boolean acceptProblem(IProblem problem) {
return DefaultProblemHandler.ruleOnProblem(problem, ParserMode.COMPLETE_PARSE);
}
public void acceptUsingDirective(IASTUsingDirective usageDirective) {}
public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) {}
public void acceptASMDefinition(IASTASMDefinition asmDefinition) {}
public void acceptAbstractTypeSpecDeclaration(IASTAbstractTypeSpecifierDeclaration abstractDeclaration) {}
public void enterTemplateDeclaration(IASTTemplateDeclaration declaration) {}
public void enterTemplateSpecialization(IASTTemplateSpecialization specialization) {}
public void enterTemplateInstantiation(IASTTemplateInstantiation instantiation) {}
public void exitTemplateDeclaration(IASTTemplateDeclaration declaration) {}
public void exitTemplateSpecialization(IASTTemplateSpecialization specialization) {}
public void exitTemplateExplicitInstantiation(IASTTemplateInstantiation instantiation) {}
public void acceptParameterReference(IASTParameterReference reference) {}
public void acceptTemplateParameterReference(IASTTemplateParameterReference reference) {}
public void acceptTypedefReference(IASTTypedefReference reference) {}
public void acceptEnumeratorReference(IASTEnumeratorReference reference) {}
public void acceptClassReference(IASTClassReference reference) {}
public void acceptNamespaceReference(IASTNamespaceReference reference) {}
public void acceptVariableReference(IASTVariableReference reference) {}
public void acceptFieldReference(IASTFieldReference reference) {}
public void acceptEnumerationReference(IASTEnumerationReference reference) {}
public void acceptFunctionReference(IASTFunctionReference reference) {}
public void acceptMethodReference(IASTMethodReference reference) {}
public void acceptField(IASTField field) {}
public void acceptMacro(IASTMacro macro) {}
public void acceptVariable(IASTVariable variable) {}
public void acceptFunctionDeclaration(IASTFunction function) {}
public void acceptMethodDeclaration(IASTMethod method) {}
public void enterCodeBlock(IASTCodeScope scope) {}
public void exitCodeBlock(IASTCodeScope scope) {}
public void acceptFriendDeclaration(IASTDeclaration declaration) {}
public void enterLinkageSpecification(IASTLinkageSpecification linkageSpec) {
pushScope(linkageSpec);
}
public void exitLinkageSpecification(IASTLinkageSpecification linkageSpec) {
popScope();
}
public void enterCompilationUnit(IASTCompilationUnit compilationUnit) {
pushScope(compilationUnit);
}
public void exitCompilationUnit(IASTCompilationUnit compilationUnit) {
popScope();
}
public void enterFunctionBody(IASTFunction function) {
pushScope(function);
}
public void exitFunctionBody(IASTFunction function) {
popScope();
}
public void enterMethodBody(IASTMethod method) {
pushScope(method);
}
public void exitMethodBody(IASTMethod method) {
popScope();
}
public void enterNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) {
fLastDeclaration = namespaceDefinition;
acceptType(namespaceDefinition);
pushScope(namespaceDefinition);
}
public void exitNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) {
popScope();
}
public void enterClassSpecifier(IASTClassSpecifier classSpecification) {
fLastDeclaration = classSpecification;
acceptType(classSpecification);
pushScope(classSpecification);
}
public void exitClassSpecifier(IASTClassSpecifier classSpecification) {
popScope();
}
private void pushScope(IASTScope scope) {
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException();
fScopeStack.push(scope);
}
private IASTScope popScope() {
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException();
return (IASTScope) fScopeStack.pop();
}
public void acceptTypedefDeclaration(IASTTypedefDeclaration typedef) {
fLastDeclaration = typedef;
acceptType(typedef);
}
public void acceptEnumerationSpecifier(IASTEnumerationSpecifier enumeration) {
fLastDeclaration = enumeration;
acceptType(enumeration);
}
public void acceptElaboratedForewardDeclaration(IASTElaboratedTypeSpecifier elaboratedType) {
// acceptType(elaboratedType);
}
public void enterInclusion(IASTInclusion inclusion) {
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException();
String includePath = inclusion.getFullFileName();
IPath path = new Path(includePath);
path = PathUtil.getWorkspaceRelativePath(path);
IResource resource = null;
IWorkspace workspace = CCorePlugin.getWorkspace();
if (workspace != null) {
IWorkspaceRoot wsRoot = workspace.getRoot();
if (wsRoot != null) {
resource = wsRoot.findMember(path, true);
}
}
//TODO do inclusions get parsed as working copies?
Object stackObject = path;
if (resource != null)
stackObject = resource;
fResourceStack.push(stackObject);
}
public void exitInclusion(IASTInclusion inclusion) {
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException();
fResourceStack.pop();
}
private class NodeTypeInfo {
int type;
String name;
String[] enclosingNames;
int offset;
int end;
IASTOffsetableNamedElement offsetable;
void init() {
type = 0;
name = null;
enclosingNames = null;
offset = 0;
end = 0;
offsetable = null;
}
boolean parseNodeForTypeInfo(ISourceElementCallbackDelegate node) {
init();
if (node instanceof IASTReference) {
IASTReference reference = (IASTReference) node;
offset = reference.getOffset();
end = offset + reference.getName().length();
} else if (node instanceof IASTOffsetableNamedElement) {
offsetable = (IASTOffsetableNamedElement) node;
offset = offsetable.getNameOffset() != 0 ? offsetable.getNameOffset() : offsetable.getStartingOffset();
end = offsetable.getNameEndOffset();
if (end == 0) {
end = offset + offsetable.getName().length();
}
}
if (node instanceof IASTReference)
node = fLastDeclaration;
if (node instanceof IASTReference) {
offsetable = (IASTOffsetableNamedElement) ((IASTReference) node).getReferencedElement();
name = ((IASTReference) node).getName();
} else if (node instanceof IASTOffsetableNamedElement) {
offsetable = (IASTOffsetableNamedElement) node;
name = offsetable.getName();
} else {
return false;
}
// skip unnamed structs
if (name == null || name.length() == 0)
return false;
// skip unused types
type = getElementType(offsetable);
if (type == 0) {
return false;
}
// collect enclosing names
if (offsetable instanceof IASTQualifiedNameElement) {
String[] names = ((IASTQualifiedNameElement) offsetable).getFullyQualifiedName();
if (names != null && names.length > 1) {
enclosingNames = new String[names.length - 1];
System.arraycopy(names, 0, enclosingNames, 0, names.length - 1);
}
}
return true;
}
}
private void acceptType(ISourceElementCallbackDelegate node) {
if (fProgressMonitor.isCanceled())
throw new OperationCanceledException();
// skip local declarations
IASTScope currentScope = (IASTScope) fScopeStack.top();
if (currentScope instanceof IASTFunction || currentScope instanceof IASTMethod) {
return;
}
NodeTypeInfo nodeInfo = new NodeTypeInfo();
if (nodeInfo.parseNodeForTypeInfo(node)) {
TypeReference originalLocation = null;
Object originalRef = fResourceStack.bottom();
if (originalRef instanceof IWorkingCopy) {
IWorkingCopy workingCopy = (IWorkingCopy) originalRef;
originalLocation = new TypeReference(workingCopy, fProject);
} else if (originalRef instanceof IResource) {
IResource resource = (IResource) originalRef;
originalLocation = new TypeReference(resource, fProject);
} else if (originalRef instanceof IPath) {
IPath path = PathUtil.getProjectRelativePath((IPath)originalRef, fProject);
originalLocation = new TypeReference(path, fProject);
}
TypeReference resolvedLocation = null;
Object resolvedRef = fResourceStack.top();
if (resolvedRef instanceof IWorkingCopy) {
IWorkingCopy workingCopy = (IWorkingCopy) resolvedRef;
resolvedLocation = new TypeReference(workingCopy, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset);
} else if (resolvedRef instanceof IResource) {
IResource resource = (IResource) resolvedRef;
resolvedLocation = new TypeReference(resource, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset);
} else if (resolvedRef instanceof IPath) {
IPath path = PathUtil.getProjectRelativePath((IPath)resolvedRef, fProject);
resolvedLocation = new TypeReference(path, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset);
}
if (fTypeToFind != null) {
if ((fTypeToFind.getCElementType() == nodeInfo.type || fTypeToFind.isUndefinedType()) && nodeInfo.name.equals(fTypeToFind.getName())) {
QualifiedTypeName qualifiedName = new QualifiedTypeName(nodeInfo.name, nodeInfo.enclosingNames);
if (qualifiedName.equals(fTypeToFind.getQualifiedTypeName())) {
// add types to cache
ITypeInfo newType = addType(nodeInfo.type, qualifiedName, originalLocation, resolvedLocation);
if (newType != null && node instanceof IASTClassSpecifier) {
addSuperClasses(newType, (IASTClassSpecifier)node, originalLocation, fProcessedTypes);
}
fProgressMonitor.worked(1);
fFoundType = true;
// terminate the parser
fParser.cancel();
}
}
} else {
// add types to cache
QualifiedTypeName qualifiedName = new QualifiedTypeName(nodeInfo.name, nodeInfo.enclosingNames);
ITypeInfo newType = addType(nodeInfo.type, qualifiedName, originalLocation, resolvedLocation);
if (newType != null && node instanceof IASTClassSpecifier) {
addSuperClasses(newType, (IASTClassSpecifier)node, originalLocation, fProcessedTypes);
}
fProgressMonitor.worked(1);
}
}
}
int getElementType(IASTOffsetableNamedElement offsetable) {
if (offsetable instanceof IASTClassSpecifier || offsetable instanceof IASTElaboratedTypeSpecifier) {
ASTClassKind kind = null;
if (offsetable instanceof IASTClassSpecifier) {
kind = ((IASTClassSpecifier) offsetable).getClassKind();
} else {
kind = ((IASTElaboratedTypeSpecifier) offsetable).getClassKind();
}
if (kind == ASTClassKind.CLASS) {
return ICElement.C_CLASS;
} else if (kind == ASTClassKind.STRUCT) {
return ICElement.C_STRUCT;
} else if (kind == ASTClassKind.UNION) {
return ICElement.C_UNION;
}
} else if (offsetable instanceof IASTNamespaceDefinition) {
return ICElement.C_NAMESPACE;
} else if (offsetable instanceof IASTEnumerationSpecifier) {
return ICElement.C_ENUMERATION;
} else if (offsetable instanceof IASTTypedefDeclaration) {
return ICElement.C_TYPEDEF;
}
return 0;
}
private void addSuperClasses(ITypeInfo type, IASTClassSpecifier classSpec, TypeReference location, Set processedClasses) {
Iterator baseIter = classSpec.getBaseClauses();
if (baseIter != null) {
while (baseIter.hasNext()) {
IASTBaseSpecifier baseSpec = (IASTBaseSpecifier) baseIter.next();
try {
ASTAccessVisibility baseAccess = baseSpec.getAccess();
IASTClassSpecifier parentClass = null;
IASTTypeSpecifier parentSpec = baseSpec.getParentClassSpecifier();
if (parentSpec instanceof IASTClassSpecifier)
parentClass = (IASTClassSpecifier) parentSpec;
if (parentClass != null) {
NodeTypeInfo nodeInfo = new NodeTypeInfo();
if (nodeInfo.parseNodeForTypeInfo(parentClass)) {
// add type to cache
ITypeInfo superType = addSuperType(type, nodeInfo.type, nodeInfo.name, nodeInfo.enclosingNames, location, baseAccess, baseSpec.isVirtual());
// recursively process super super classes
if (!processedClasses.contains(parentClass)) {
processedClasses.add(parentClass);
addSuperClasses(superType, parentClass, location, processedClasses);
}
}
}
} catch (ASTNotImplementedException e) {
}
}
}
}
private ITypeInfo addType(int type, QualifiedTypeName qualifiedName, TypeReference originalLocation, TypeReference resolvedLocation) {
ITypeInfo info = fTypeCache.getType(type, qualifiedName);
if (info == null || info.isUndefinedType()) {
// add new type to cache
if (info != null) {
info.setCElementType(type);
} else {
info = new TypeInfo(type, qualifiedName);
fTypeCache.insert(info);
}
info.addReference(originalLocation);
}
info.addReference(resolvedLocation);
return info;
}
private ITypeInfo addSuperType(ITypeInfo addToType, int type, String name, String[] enclosingNames, TypeReference location, ASTAccessVisibility access, boolean isVirtual) {
QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames);
ITypeInfo superType = fTypeCache.getType(type, qualifiedName);
if (superType == null || superType.isUndefinedType()) {
if (superType != null) {
// merge with existing type
superType.setCElementType(type);
} else {
// add new type to cache
superType = new TypeInfo(type, qualifiedName);
fTypeCache.insert(superType);
}
}
superType.addDerivedReference(location);
if (fSuperTypeToFind != null && fSuperTypeToFind.equals(superType)) {
//TODO don't need to do anything here?
}
fTypeCache.addSupertype(addToType, superType, access, isVirtual);
fTypeCache.addSubtype(superType, addToType);
return superType;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ISourceElementRequestor#createReader(java.lang.String)
*/
public CodeReader createReader(String finalPath, Iterator workingCopies) {
return ParserUtil.createReader(finalPath, workingCopies);
}
private static final int DEFAULT_PARSER_TIMEOUT = 30;
public int getParserTimeout() {
//TODO we shouldn't be trying to access the indexer prefs
//TODO clean this up
int timeout = 0;
try {
// here we just reuse the indexer timeout
String str = CCorePlugin.getDefault().getPluginPreferences().getString("CDT_INDEXER_TIMEOUT"); //$NON-NLS-1$
if (str != null && str.length() > 0) {
int val = Integer.valueOf(str).intValue();
if (val > 0) {
timeout = val;
}
}
} catch (NumberFormatException e) {
// do nothing
}
if (timeout == 0) {
timeout = DEFAULT_PARSER_TIMEOUT;
}
return timeout;
}
}

View file

@ -1,53 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.util;
/**
* A helper class which allows you to perform some
* simple set operations on int arrays.
*/
public class ArrayUtil {
private ArrayUtil() {
}
// returns true if set contains elem
public static boolean contains(int[] set, int elem) {
if (set == null)
return false;
for (int i= 0; i < set.length; ++i) {
if (set[i] == elem)
return true;
}
return false;
}
// returns true if set contains all of subset
public static boolean containsAll(int[] set, int[] subset) {
if (set == null || subset == null)
return false;
for (int i= 0; i < subset.length; ++i) {
if (!contains(set, subset[i]))
return false;
}
return true;
}
// return a copy of fromSet
public static int[] clone(int[] fromSet) {
if (fromSet == null)
return null;
int[] newSet= new int[fromSet.length];
for (int i= 0; i < fromSet.length; ++i) {
newSet[i]= fromSet[i];
}
return newSet;
}
}

View file

@ -1,249 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.util;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IProgressMonitorWithBlocking;
import org.eclipse.core.runtime.IStatus;
/**
* A wrapper around one or more progress monitors. Forwards
* <code>IProgressMonitor</code> and <code>IProgressMonitorWithBlocking</code>
* methods to the delegate monitors.
*/
public class DelegatedProgressMonitor implements IProgressMonitor, IProgressMonitorWithBlocking {
private static int INITIAL_DELEGATE_COUNT = 2;
private final ArrayList fDelegateList = new ArrayList(INITIAL_DELEGATE_COUNT);
String fTaskName;
String fSubTask;
int fTotalWork;
private double fWorked;
private boolean fIsBlocked;
boolean fIsCanceled;
/**
* Creates a new delegated monitor.
*/
public DelegatedProgressMonitor() {
init();
}
/**
* Creates a new delegated monitor, and adds a delegate.
*/
public DelegatedProgressMonitor(IProgressMonitor delegate) {
init();
addDelegate(delegate);
}
/**
* Resets delegated monitor to initial state.
*/
public synchronized void init() {
fTaskName= null;
fSubTask= null;
fTotalWork= IProgressMonitor.UNKNOWN;
fWorked= 0.0f;
fIsBlocked= false;
fIsCanceled= false;
}
/*
* @see IProgressMonitor#beginTask
*/
public synchronized void beginTask(String name, int totalWork) {
fTaskName = name;
fTotalWork = totalWork;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.beginTask(fTaskName, fTotalWork);
}
});
}
/*
* @see IProgressMonitor#done
*/
public synchronized void done() {
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.done();
}
});
}
/*
* @see IProgressMonitor#setTaskName
*/
public synchronized void setTaskName(String name) {
fTaskName = name;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.setTaskName(fTaskName);
}
});
}
/*
* @see IProgressMonitor#subTask
*/
public synchronized void subTask(String name) {
fSubTask = name;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.subTask(fSubTask);
}
});
}
/*
* @see IProgressMonitor#worked
*/
public void worked(int work) {
internalWorked(work);
}
/*
* @see IProgressMonitor#internalWorked
*/
public synchronized void internalWorked(double internalWork) {
fWorked += internalWork;
final double fInternalWork = internalWork;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.internalWorked(fInternalWork);
}
});
}
/*
* @see IProgressMonitor#isCanceled
*/
public synchronized boolean isCanceled() {
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
fIsCanceled |= delegate.isCanceled();
}
});
return fIsCanceled;
}
/*
* @see IProgressMonitor#setCanceled
*/
public synchronized void setCanceled(boolean canceled) {
fIsCanceled = canceled;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
delegate.setCanceled(fIsCanceled);
}
});
}
/*
* @see IProgressMonitor#setBlocked
*/
public synchronized void setBlocked(IStatus reason) {
fIsBlocked = true;
final IStatus fReason = reason;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
if (delegate instanceof IProgressMonitorWithBlocking)
((IProgressMonitorWithBlocking) delegate).setBlocked(fReason);
}
});
}
/*
* @see IProgressMonitor#clearBlocked
*/
public synchronized void clearBlocked() {
fIsBlocked = false;
visitDelegates(new IDelegateVisitor() {
public void visit(IProgressMonitor delegate) {
if (delegate instanceof IProgressMonitorWithBlocking)
((IProgressMonitorWithBlocking) delegate).clearBlocked();
}
});
}
/**
* Adds a delegate.
*/
public synchronized void addDelegate(IProgressMonitor delegate) {
if (fDelegateList.indexOf(delegate) == -1) {
if (fTaskName != null)
syncUp(delegate);
fDelegateList.add(delegate);
}
}
/**
* Brings delegate in sync with current progress.
*/
private void syncUp(IProgressMonitor delegate) {
delegate.beginTask(fTaskName, fTotalWork);
delegate.internalWorked(fWorked);
if (fSubTask != null && fSubTask.length() > 0)
delegate.subTask(fSubTask);
if (fIsBlocked && delegate instanceof IProgressMonitorWithBlocking)
((IProgressMonitorWithBlocking) delegate).setBlocked(null);
}
/**
* Removes a delegate.
*/
public synchronized void removeDelegate(IProgressMonitor delegate) {
int index = fDelegateList.indexOf(delegate);
if (index != -1) {
fDelegateList.remove(index);
}
}
/**
* Removes all delegates.
*/
public synchronized void removeAllDelegates() {
fDelegateList.clear();
}
/**
* Returns the delegate list.
*
* @return An array of progress monitors added using <code>addDelegate()</code>.
*/
public synchronized IProgressMonitor[] getDelegates() {
return (IProgressMonitor[]) fDelegateList.toArray();
}
/**
* Defines a delegate visitor.
*/
private static interface IDelegateVisitor {
public void visit(IProgressMonitor delegate);
}
/**
* Visits each delegate in the delegates list.
*/
private void visitDelegates(IDelegateVisitor visitor) {
// Clone the delegates since they could remove themselves when called
ArrayList delegatesList = (ArrayList) fDelegateList.clone();
for (Iterator i = delegatesList.iterator(); i.hasNext(); ) {
IProgressMonitor delegate = (IProgressMonitor) i.next();
visitor.visit(delegate);
}
}
}

View file

@ -1,84 +0,0 @@
/*******************************************************************************
* Copyright (c) 2004 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.browser.util;
import java.util.ArrayList;
/**
* A helper class which allows you to perform some simple
* stack operations. Avoids the extra overhead of
* synchronization in Java.Util.Stack.
*/
public class SimpleStack {
private static int INITIAL_STACK_SIZE = 10;
private ArrayList items;
private static boolean VERBOSE = false;
public SimpleStack() {
items = new ArrayList(INITIAL_STACK_SIZE);
}
public SimpleStack(int initialSize) {
items = new ArrayList(initialSize);
}
public void clear() {
items.clear();
}
public Object push(Object item) {
items.add(item);
if (VERBOSE)
trace("push on stack: " + item); //$NON-NLS-1$
return item;
}
public Object pop() {
int top = items.size()-1;
if (top < 0)
return null;
Object item = items.get(top);
items.remove(top);
if (VERBOSE)
trace("pop from stack: " + item); //$NON-NLS-1$
return item;
}
public Object top() {
int top = items.size()-1;
if (top < 0)
return null;
return items.get(top);
}
public Object bottom() {
if (items.size() == 0)
return null;
return items.get(0);
}
public boolean isEmpty() {
return (items.size() == 0);
}
public Object[] toArray() {
return items.toArray();
}
public Object[] toArray(Object a[]) {
return items.toArray(a);
}
private static void trace(String msg) {
System.out.println("(" + Thread.currentThread() + ") " + msg); //$NON-NLS-1$ //$NON-NLS-2$
}
}

View file

@ -1,74 +0,0 @@
2005-03-12 Bogdan Gheorghe
- Updated references from IndexManager to SourceIndexer due to new indexer framework
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyQueryJob.java
* src/org/eclipse/cdt/internal/core/sourcedependency/UpdateDependency.java
2004-02-25 Bogdan Gheorghe
- Check to see if the resource has a location before using it in
UpdateDependency
2003-11-10 Bogdan Gheorghe
- Added a null resource check in UpdateDependency to fix up
a potential NPE in the test suite
2003-10-23 Bogdan Gheorghe
- Added UpdateDependency job
2003-09-25 Bogdan Gheorghe
- As a result of folding the dependency service into the indexer
have removed the following files:
* src/org/eclipse/cdt/internal/core/sourcedependency/AddFileToDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyManager.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequest.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequestor.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencySelector.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/EntireProjectDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/IDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/IPreprocessorOutput.java
* src/org/eclipse/cdt/internal/core/sourcedependency/ISourceDependency.java
* src/org/eclipse/cdt/internal/core/sourcedependency/PreprocessorOutput.java
* src/org/eclipse/cdt/internal/core/sourcedependency/RemoveFromDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntry.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntryHashedArray.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/InMemoryTree.java
2003-09-22 Bogdan Gheorghe
- Took out enable section for DependencyManager
2003-09-11 Bogdan Gheorghe
- Added null guard to DependencyManager.getDependencyTree(),
DependencyTree.getFileDependencies()
2003-09-08 Andrew Niefer
- Modified calls to ParserFactory to specify which language to use
- Modified IDependencyTree.add to take ParserLanguage as a parameter so that it can
be passed on when creating the preprocessor
2003-07-23 Bogdan Gheorghe
Added initial dependency implementation
* src/org/eclipse/cdt/internal/core/sourcedependency/AddFileToDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyManager.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DenpendencyQueryJob.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequest.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequestor.java
* src/org/eclipse/cdt/internal/core/sourcedependency/DependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/EntireProjectDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/IDependencyTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/IPreprocessorOutput.java
* src/org/eclipse/cdt/internal/core/sourcedependency/ISourceDependency.java
* src/org/eclipse/cdt/internal/core/sourcedependency/PreprocessorOutput.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntry.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntryHashedArray.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/InMemoryTree.java
* src/org/eclipse/cdt/internal/core/sourcedependency/impl/Node.java
-

View file

@ -1,205 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.sourcedependency;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.search.IndexSelector;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.cdt.internal.core.search.processing.JobManager;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
/**
* @author bgheorgh
*/
public class DependencyQueryJob implements IIndexJob {
IProject project;
IFile file;
ArrayList includeFiles;
DOMSourceIndexer indexer;
IndexManager indexManager;
protected IndexSelector indexSelector;
protected long executionTime = 0;
public DependencyQueryJob(IProject project, IFile file, DOMSourceIndexer indexer, List includeFiles) {
this.project = project;
this.file = file;
this.indexer = indexer;
this.includeFiles = (ArrayList) includeFiles;
this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#belongsTo(java.lang.String)
*/
public boolean belongsTo(String jobFamily) {
// TODO Auto-generated method stub
return true;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#cancel()
*/
public void cancel() {}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#execute(org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean execute(IProgressMonitor progressMonitor) {
if ((project == null) ||(file == null)) return false;
//
if (progressMonitor != null && progressMonitor.isCanceled())
throw new OperationCanceledException();
boolean isComplete = COMPLETE;
executionTime = 0;
if (this.indexSelector == null) {
this.indexSelector =
new IndexSelector(SearchEngine.createWorkspaceScope(), null, false, indexManager);
}
IIndex[] searchIndexes = this.indexSelector.getIndexes();
try {
int max = searchIndexes.length;
int min=0;
if (progressMonitor != null) {
progressMonitor.beginTask("", max); //$NON-NLS-1$
}
for (int i = 0; i < max; i++) {
isComplete &= getFileDeps(searchIndexes[i], progressMonitor);
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
throw new OperationCanceledException();
} else {
progressMonitor.worked(1);
}
}
}
if (JobManager.VERBOSE) {
JobManager.verbose("-> execution time: " + executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$
}
return isComplete;
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
/**
* @param index
* @param progressMonitor
* @return
*/
public boolean getFileDeps(IIndex index, IProgressMonitor progressMonitor){
if (progressMonitor != null && progressMonitor.isCanceled())
throw new OperationCanceledException();
if (index == null)
return COMPLETE;
if (!(indexer instanceof DOMSourceIndexer))
return FAILED;
DOMSourceIndexer sourceIndexer = (DOMSourceIndexer)indexer;
ReadWriteMonitor monitor = sourceIndexer.getMonitorFor(index);
if (monitor == null)
return COMPLETE; // index got deleted since acquired
try {
monitor.enterRead(); // ask permission to read
/* if index has changed, commit these before querying */
if (index.hasChanged()) {
try {
monitor.exitRead(); // free read lock
monitor.enterWrite(); // ask permission to write
sourceIndexer.saveIndex(index);
} catch (IOException e) {
return FAILED;
} finally {
monitor.exitWriteEnterRead(); // finished writing and reacquire read permission
}
}
long start = System.currentTimeMillis();
//
IndexInput input = new BlocksIndexInput(index.getIndexFile());
try {
input.open();
findDep(input);
} finally {
input.close();
}
executionTime += System.currentTimeMillis() - start;
return COMPLETE;
}
catch (IOException e){
return FAILED;
}
finally {
monitor.exitRead(); // finished reading
}
}
/**
* @param input
* @param includeFiles
*/
private void findDep(IndexInput input) throws IOException {
IndexedFileEntry indexedFile = input.getIndexedFile(file.getFullPath().toString());
if (indexedFile == null) return;
int fileNum =indexedFile.getFileID();
IncludeEntry[] tempEntries = input.queryIncludeEntries(fileNum);
if (tempEntries != null){
for (int r=0; r<tempEntries.length; r++){
char[] tempFile = tempEntries[r].getFile();
StringBuffer tempString = new StringBuffer();
tempString.append(tempFile);
includeFiles.add(tempString.toString());
}
}
}
public String toString() {
return "searching for the dependencies of" + file.getName(); //$NON-NLS-1$
}
public boolean isReadyToRun() {
if (this.indexSelector == null) { // only check once. As long as this job is used, it will keep the same index picture
this.indexSelector = new IndexSelector(SearchEngine.createWorkspaceScope(), null, false, indexManager);
this.indexSelector.getIndexes(); // will only cache answer if all indexes were available originally
}
return true;
}
}

View file

@ -1,45 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.sourcedependency;
/**
* @author bgheorgh
*/
public class Node {
int fileRef;
int nodeId;
public Node(int file, int id){
this.fileRef = file;
this.nodeId = id;
}
public int getFileRef(){
return fileRef;
}
public int getNodeId(){
return nodeId;
}
public String toString() {
StringBuffer tempBuffer = new StringBuffer();
tempBuffer.append("[FileRef: "); //$NON-NLS-1$
tempBuffer.append(fileRef);
tempBuffer.append(", Id: "); //$NON-NLS-1$
tempBuffer.append(nodeId);
tempBuffer.append("]"); //$NON-NLS-1$
return tempBuffer.toString();
}
}

View file

@ -1,129 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on Oct 13, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.cdt.internal.core.sourcedependency;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.ICSearchScope;
import org.eclipse.cdt.core.search.SearchEngine;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer;
import org.eclipse.cdt.internal.core.search.PathCollector;
import org.eclipse.cdt.internal.core.search.PatternSearchJob;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.matching.CSearchPattern;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
/**
* @author bgheorgh
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class UpdateDependency implements IIndexJob {
PathCollector pathCollector;
IFile resource=null;
DOMSourceIndexer indexer;
/**
* @param resource
*/
public UpdateDependency(IResource resource, DOMSourceIndexer indexer) {
if (resource instanceof IFile)
this.resource = (IFile) resource;
this.indexer = indexer;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#belongsTo(java.lang.String)
*/
public boolean belongsTo(String jobFamily) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#cancel()
*/
public void cancel() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#execute(org.eclipse.core.runtime.IProgressMonitor)
*/
public boolean execute(IProgressMonitor progress) {
if (resource == null) return false;
IPath location = resource.getLocation();
if (location == null) return false;
PathCollector pathCollector = new PathCollector();
//SubProgressMonitor subMonitor = (progressMonitor == null ) ? null : new SubProgressMonitor( progressMonitor, 5 );
ICSearchScope scope = SearchEngine.createWorkspaceScope();
CSearchPattern pattern = CSearchPattern.createPattern(location.toOSString(),ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES,ICSearchConstants.EXACT_MATCH,true);
IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
indexManager.performConcurrentJob(
new PatternSearchJob(
pattern,
scope,
pathCollector,
indexManager
),
ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
null,
this );
String[] iPath = pathCollector.getPaths();
if (iPath.length > 0){
//If we found any dependents on this header file, indexing them will also index the header
for (int i=0;i<iPath.length; i++){
IPath pathToReindex = new Path(iPath[i]);
IWorkspaceRoot workRoot = resource.getWorkspace().getRoot();
IFile fileToReindex = workRoot.getFile(pathToReindex);
if (fileToReindex!=null && fileToReindex.exists() ) {
// if (VERBOSE)
// System.out.println("Going to reindex " + fileToReindex.getName());
indexer.addSource(fileToReindex,fileToReindex.getProject().getFullPath());
}
}
}
else {
//No dependents found, just index the stand alone header
indexer.addSource(resource,resource.getProject().getFullPath());
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.search.processing.IJob#isReadyToRun()
*/
public boolean isReadyToRun() {
return true;
}
}

View file

@ -1,587 +0,0 @@
2005-04-04 Bogdan Gheorghe
Got rid of IDocument and replaced it with IFile resources throughout all
indexing framework. Got rid of index flags and put in a new mechanism for
indexers to add files to the index directly.
2005-03-30 Bogdan Gheorghe
Modified IndexManger to get rid of an exisiting index for a project when an
indexer gets changed. This is needed in the case where two indexers share the same
storage (which is the current case for all indexers) to avoid them treading
on each other.
2005-03-29 Bogdan Gheorghe
Changed indexer change notification to run as a job.
Some additiional ICDTIndexer changes.
2005-03-29 Bogdan Gheorghe
Added cumulative timer to SouceIndexer/DOMIndexer.
Purge any existing jobs from job queue on indexer change event.
Put in an indexer change nofication event that the IndexManager sends to the
newly selected indexer to allow it to react to being selected.
2005-03-28 Bogdan Gheorghe
NPE Fix for CTagsConsoleParser
2005-03-28 Bogdan Gheorghe
Initial CTags Indexer contribution
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsEntry.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsAddCompilationUnitToIndex.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsAddFileToIndex.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsFileReader.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsHeader.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexAll.jav
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexer.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexeRequest.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsRemoveFromIndex.java
* index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsSaveIndex.java
Added timing option to all three indexers
* index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexerRunner.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SourceIndexerRunner.java
Modified event notification for all indexers to make use of ICDTIndexer constants as opposed to ICElements, in
order to allow indexers to request additional jobs without having to create or retrieve an ICElement
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SourceIndexer.java
* index/org/eclipse/cdt/core/index/ICDTIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
2005-03-18 Alain Magloire
Move more code in the try/finally as a precaution. Bad things
where happening (i.e. NPE) but the monitor was not decremented
* index/org/eclipse/cdt/internal/core/indexing/IndexManager.java
2005-03-15 Bogdan Gheorghe
Added a check for closed projects to update code
2005-03-14 Bogdan Gheorghe
Added update code for old indexer projects
2005-03-12 Bogdan Gheorghe
Restructured indexer framework to allow for multiple indexers in a workspace.
* index/org/eclipse/cdt/core/index/ICDTIndexer.java
* index/org/eclipse/cdt/core/index/IIndexStorage.java
* index/org/eclipse/cdt/core/index/Indexer.java
* index/org/eclipse/cdt/core/index/IndexManager.java
* index/org/eclipse/cdt/internal/core/index/IIndexer.java
* index/org/eclipse/cdt/internal/core/index/impl/Index.java
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java
Moved following classes to new source indexer folder:
* index/org/eclipse/cdt/internal/core/index/sourceindexer/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/AddCompilationUnit.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/AddFileToIndex.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/AddFolderToIndex.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/CIndexStorage.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/CleanEncounteredHeaders.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/IndexAllProject.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/IndexRequest.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/RemoveFolderFromIndex.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/RemoveFromIndex.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SaveIndex.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SourceIndexerRequestor.java
* index/org/eclipse/cdt/internal/core/index/sourceindexer/SourceIndexerRunner.java
2004-11-17 Bogdan Gheorghe
Fix for Bug 78678: Indexer stops reindexing file after repeated saves
* index/org/eclipse/cdt/internal/core/search/processing/JobManager.java
2004-11-12 Bogdan Gheorghe
Fix for Bug 78414: IProblem count increased through indexing header files stand-alone
* index/org/eclipse/cdt/internal/core/search/indexing/IndexAllProject.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFileToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFolderToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/CleanEncounteredHeaders.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
* parser/org/eclipse/cdt/internal/core/parser/problem/Problem.java
2004-11-02 Bogdan Gheorghe
Fixed a bug in the index merge.
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
2004-11-02 Bogdan Gheorghe
Partial Fix for Bug 74427: Indexer needs to store more info
* index/org/eclipse/cdt/core/index/IIndexDelta.java
* index/org/eclipse/cdt/internal/core/index/IEntryResult.java
* index/org/eclipse/cdt/internal/core/index/IIndexerOutput.java
* index/org/eclipse/cdt/internal/core/index/impl/BlocksIndexInput.java
* index/org/eclipse/cdt/internal/core/index/impl/EntryResult.java
* index/org/eclipse/cdt/internal/core/index/impl/GammaCompressedIndexBlock.java
* index/org/eclipse/cdt/internal/core/index/impl/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/index/impl/IncludeEntry.java
* index/org/eclipse/cdt/internal/core/index/impl/Index.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexDelta.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexedFileHashedArray.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexerOutput.java
* index/org/eclipse/cdt/internal/core/index/impl/InMemoryIndex.java
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
* index/org/eclipse/cdt/internal/core/index/impl/Util.java
* index/org/eclipse/cdt/internal/core/index/impl/WordEntry.java
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFileToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFolderToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/CleanEncounteredHeaders.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
* dependency/org/eclipse/cdt/internal/core/sourcedependency/UpdateDependency.java
* model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java
2004-08-19 Bogdan Gheorghe
Fix for Bug 71500: [Indexer] all headers get indexed on project open
* index/org/eclipse/cdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFileToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFolderToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/CleanEncounteredHeaders.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
* dependency/org/eclipse/cdt/internal/core/sourcedependency/UpdateDependency.java
* model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java
2004-08-11 Bogdan Gheorghe
Fix for Bug 59493: need to refine index query for open-type
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
2004-07-12 Bogdan Gheorghe
Fix for Bug 69166: NPE in IndexerModelListener.processDelta
* index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java
2004-07-06 Bogdan Gheorghe
Added timing for merge operations - controlled by Indexer tracing option
Modified removeSourceFolderFromIndex in IndexManager to take an IProject
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
2004-06-28 Bogdan Gheorghe
Fix for Bug 60948: indexer should pick up all headers in include path
2004-06-25 Bogdan Gheorghe
Indirect fix for Bug 65551: [Search] Search for Variable references should not include parameters
Instead of excluding parameter references from searches, added parm declarations to the index (for
both functions and methods)
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
2004-06-22 Alain Magloire
Part of PR 68246.
Close the inputstream to release resource handle
when we done with it, we can not rely on the GC to do it for us.
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
2004-06-21 Andrew Niefer
enable reporting of semantic problems:
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
2004-06-21 Alain Magloire
IndexManager, call CCorePlugin.getCDescriptor(.., false).
The boolean says to the DescriptorManager to not create the file
if it does not exists.
2004-06-18 Alain Magloire
- The call CCorePlugin.getCDescriptor(..) seems to return null.
This should be fix but meanwhile give the indexer a break by catching it.
2004-06-18 Andrew Niefer
- call InderManager.jobFinishedNotification( this ) from IndexRequest.cancel() so that the IndexManager's jobSet doesn't
become stale.
- in JobManager.discardJobs, move getting the old enabledState into the synchronized block so that we can be sure its
reset correctly
2004-06-16 Bogdan Gheorghe
- Removed reporting index failed messages from log
2004-06-14 Andrew Niefer
- Bugs 66799, 66981 : don't process indexer jobs if the indexer for that project is disabled.
- also fix warnings about deprecated calls and unnecessary else statements
2004-06-13 Bogdan Gheorghe
Fix for Bug 63275 - Ensured that only declarations and references are found for enumerations/enumerators
2004-05-28 Bogdan Gheorghe
Fix for Bug 63831 - Ability to determine when the index is incomplete
Provided a way for external clients to query the index state of a project
2004-05-28 Bogdan Gheorghe
Fix for Bug 60946 - [Indexer] indexer should provide notification whenever index changes
Provide a notification to the listener of index events
Fix for Bug 44926 - add extensibility to gracefully handle preprocessor exceptions
Added an IndexProblemHandler to handle parser IProblem callbacks
2004-05-27 Bogdan Gheorghe
Fix for Bug 58716 - [Refactoring] Subdirectories confuse refactoring
Added a listener to path change events from the core model; retrigger
indexing based on the granularity of the change event
2004-05-27 Bogdan Gheorghe
Fix for Bug 62015 - Indexer to not rely on file extension for translation Unit
Changed all indexer file type checking to use the CoreModel file resolution services.
2004-05-21 Andrew Niefer
Indexer problem reporting
* index/org/eclipse/cdt/internal/core/messages.properties
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
2004-05-18 Bogdan Gheorghe
IndexAllProject - restored the save request.
2004-05-18 Bogdan Gheorghe
First go at putting in source folder indexing. Index All events will index
source folders (still need to put in includes indexing). DeltaProcessor only
forwards events for source files so individual indexing doesn't need to be
altered.
2004-05-16 Bogdan Gheorghe
Fix for bug 61332 - make sure that the timer is ready to go before starting
a new index
2004-05-07 Bogdan Gheorghe
Modified indexer friend encoding to encode IASTElaboratedTypeSpecifier
2004-05-06 Bogdan Gheorghe
Modified AbstractIndexer to encode friends, add friends constant to IIndexConstants,
modified SourceIndexerRequestor to add class specifier on exit instead of enter in order
to be able to encode friends.
2004-05-05 Bogdan Gheorghe
Added code to load and store index enablement setting from a project's descriptor
2004-05-03 Bogdan Gheorghe
Added index enablement checking to index manager
2004-04-20 Bogdan Gheorghe
Fix for Bug 54155
2004-04-12 Bogdan Gheorghe
Added Indexer watchdog
2004-04-12 Bogdan Gheorghe
Added Enumerator and Derived types to index
2004-03-31 Bogdan Gheorghe
Added a check to SourceIndexRequestor.removeMarkers to prevent hang.
2004-03-31 Bogdan Gheorghe
Modified SourceIndexer and SourceIndexerRequestor to place IProblem markers
on resources.
2004-03-15 Andrew Niefer
updated SourceIndexerRequestor with acceptTemplateParameterReference
2004-03-04 Bogdan Gheorghe
Modified SourceIndexer to use BufferedReaders instead of passing in a char array.
2004-02-13 Bogdan Gheorghe
PR 51232
- Added mapping range checking to IncludeEntry to avoid out of bounds exceptions
- Added error handling to MergeFactory to handle problems during the save operation
- Added source file name filtering for the recreate an already existing index scenario in
IndexAllProject.
- Added more robust error handling to SourceIndexer
- Added error handling routine to Util.getFileCharContent() to deal with potential out of
memory crash
* index/org/eclipse/cdt/internal/core/index/impl/IncludeEntry.java
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
* index/org/eclipse/cdt/internal/core/index/search/Util.java
* index/org/eclipse/cdt/internal/core/index/search/indexing/IndexAllProject.java
* index/org/eclipse/cdt/internal/core/index/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/index/search/indexing/AddFolderToIndex.java
2004-02-10 Bogdan Gheorghe
- Modified some of the stored index block reading routines to use separate
counters, thus avoiding potential EOF exceptions.
* index/org/eclipse/cdt/internal/core/index/impl/BlocksIndexInput.java
2004-02-03 Alain Magloire
PR 51106
Patches from Thomas Fletcher dealing with the indexer.
- Remove assumed throw/catch of an exception to be a regular occurance
and replace with explicit test and return for bounds access to the
particular array.
- Consider references outside of the mapping range the same as no longer
valid mappings (ie -1 entries) and avoid array range exceptions.
* index/org/eclipse/cdt/internal/core/index/impl/WordEntry.java
* index/org/eclipse/cdt/internal/core/index/impl/FileListBlock.java
2004-01-26 John Camelon
Updated clients to use new Scanner logging service.
2003-10-22 Bogdan Gheorghe
Added updateDependencies() to the IndexManager to request
a new UpdateDependency job.
2003-10-01 Bogdan Gheorghe
- Modified BlockIndexOutput.addInclude to properly flush an
include block once it's full.
- Flushing the CDT log after every merge
- Logging I/O Exceptions in AddFileToIndex
- Changed valid source file extensions in SourceIndexer to
use CModelManager file extensions
2003-09-30 Bogdan Gheorghe
Changed logging for SourceIndexer to log file in cdt.core
2003-09-25 Bogdan Gheorghe
Integrated the dependency service into the indexer. Changes
as follows:
org.eclipse.cdt.internal.core.index.impl:
* IIndex - added getFileDependencies methods
* IIndexerOutput - modified to allow dep inputs into the index
* BlocksIndexInput - modified to allow the reading of the new index (which includes dep entries)
* BlocksIndexOutput - added facilities to write includes to the index
* GammaCompressedIndexBlock - modified with addIncludeEntry() and nextEntry()
* IncludeEntry - new file
* IncludeEntryHashedArray - new file
* Index - Added getFileDepenendencies to query includeEntries from the index
* IndexBlock - modified to reflect changes in GammaCompressedIndexBlock
* IndexerOutput - added new methods from IIndexerOutput
* IndexInput - modified to allow reading of includes from index files
* IndexSummary - modified to save/read new format which contains include info
* InMemoryIndex - modified InMemoryIndex to keep track of includes
* MergeFactory - modified MergeFactory to accomodate new index file format
* SimpleIndexInput - modified to use the new functions for includes in InMemoryIndex
* Util - Added a quickSort for includeEntry[]
org.eclipse.cdt.internal.core.search.indexing:
* AbstractIndexer - modified to getResourceFile being indexed, added bestIncludePrefix
to find include table entries, addInclude() which accepts IASTInclusion node and adds it
to the index
* IIndexConstants - added includeRef constant
* IndexManager - got rid of all dependency table references
* SourceIndexer - modified to return resource being indexed
* SourceIndexerRequestor - Added inclusion handling code; stack for includes
2003-09-22 Bogdan Gheorghe
Took out the old CTags Indexer. Modified IndexAllProject to get
the project path straight from the resource (bypassing the CModelManager).
Commented out the enable section in IndexManager.
Modified
* org.eclipse.cdt.internal.core.search.indexing.IndexAllProject
* org.eclipse.cdt.internal.core.search.indexing.IndexManager
Deleted
* org.eclipse.cdt.core.index.IndexModel
* org.eclipse.cdt.core.index.ITagEntry
* org.eclipse.cdt.core.index.TagFlags
* org.eclipse.cdt.internal.core.index.CTagsCmd
* org.eclipse.cdt.internal.core.index.CTagsEntry
* org.eclipse.cdt.internal.core.index.CTagsFileReader
* org.eclipse.cdt.internal.core.index.CTagsFileWriter
* org.eclipse.cdt.internal.core.index.CTagsHeader
* org.eclipse.cdt.internal.core.index.CTagsRunner
* org.eclipse.cdt.internal.core.index.IndexManager
* org.eclipse.cdt.internal.core.index.RequestList
2003-09-16 Andrew Niefer
- add parameter references to index
- modify CharOperation.match to allow escaping wildcards (bug43063)
- modify AbstractIndexer.bestPrefix to handle wildcard escaping in name (bug43063)
2003-09-13 Andrew Niefer
- add Typedefs to index as Types with suffix T (bug42902)
- added addTypedefReference to AbstractIndexer
- modified bestTypePrefix in AbstractIndexer
- added TYPEDEF_DECL, TYPEDEF_SUFFIX to IIndexConstants
- modified acceptTypedefReference in SourceIndexerRequestor
2003-09-09 Andrew Niefer
Enumerator references
- Added createEnumeratorFullyQualifiedName in AbstractIndexer
- Added addEnumeratorReference in AbstractIndexer
- implemented acceptEnumeratorReference in SourceIndexerRequestor
2003-09-08 Andrew Niefer
- Modified calls to ParserFactory to specify which language to use
2003-09-05 Andrew Niefer
- Modified how AbstractIndexer creates the fully qualified name for an enumerator (spec 7.2-10)
2003-08-26 Bogdan Gheorghe
- Removed header file extensions from being indexed (they
will be indexed via inclusion)
2003-08-20 Bogdan Gheorghe
- Added debug tracing in AbstractIndexer
- Added additional file extensions to supported indexed files
- Changed the parser instantiation to pass in retrieved build
info
- Added function decl index entry based on enterFunctionBody
- Added method decl index entry based on enterMethodBody
- Added forward decl refs
2003-08-14 Bogdan Gheorghe
- Added forward declarations to index
2003-08-12 Bogdan Gheorghe
- Changed var prefix in AbstractIndexer to pass in fully
qualified names
2003-08-11 Bogdan Gheorghe
- Added macro declarations to the index
- Added macro prefix to AbstractIndexer
2003-08-07 Bogdan Gheorghe
- Added shutdown cleanup routine in IndexManager
2003-07-28 Andrew Niefer
- added support for '?' wildcards in AbstractIndexer.bestPrefix
2003-07-25 Bogdan Gheorghe
- Changed parser to COMPLETE mode
- Added functionRef, methodRef, typeRef, namespaceRef, fieldRef
Modified:
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
2003-07-24 Andrew Niefer
- added TYPE_ALL, FUNCTION_ALL, METHOD_ALL, NAMESPACE_ALL, FIELD_ALL constants to IIndexConstants
- modified AbstractIndexer prefix functions to properly handle searching for all occurences
2003-07-23 Andrew Niefer
Modified
*index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
-changed so that the index prefixes contain the qualified names of the
elements in reverse order.
-Added functions:
bestVariablePrefix
bestNamespacePrefix
bestFieldPrefix
bestFunctionPrefix
bestMethodPrefix
2003-07-21 Bogdan Gheorghe
Added additional declarations to index: enums, enumerators, namespace,
functions, vars, methods, fields, typedefs.
Fixed IndexManager to prevent individually added files from
being added to the index if indexing is not enabled for the project
Modified:
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java
2003-07-10 Bogdan Gheorghe
Added bestTypeDeclarationPrefix to AbstractIndexer to allow the
search engine to create a query string for the index.
Changed encoding in AbstractIndexer to encode fully qualified names.
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
2003-07-03 Bogdan Gheorghe
Updated copyright notices.
2003-06-25 Bogdan Gheorghe
Added new Indexer framework:
* index/org/eclipse/cdt/internal/core/index/IDocument.java
* index/org/eclipse/cdt/internal/core/index/IEntryResult.java
* index/org/eclipse/cdt/internal/core/index/IIndex.java
* index/org/eclipse/cdt/internal/core/index/IIndexer.java
* index/org/eclipse/cdt/internal/core/index/IIndexerOutput.java
* index/org/eclipse/cdt/internal/core/index/IQueryResult.java
* index/org/eclipse/cdt/internal/core/index/impl/Block.java
* index/org/eclipse/cdt/internal/core/index/impl/BlocksIndexInput.java
* index/org/eclipse/cdt/internal/core/index/impl/BlocksIndexOutput.java
* index/org/eclipse/cdt/internal/core/index/impl/CodeByteStream.java
* index/org/eclipse/cdt/internal/core/index/impl/EntryResult.java
* index/org/eclipse/cdt/internal/core/index/impl/Field.java
* index/org/eclipse/cdt/internal/core/index/impl/GammaCompressedIndexBlock.java
* index/org/eclipse/cdt/internal/core/index/impl/IFileDocument.java
* index/org/eclipse/cdt/internal/core/index/impl/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/index/impl/Index.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexBlock.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexedFile.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexedFileHashedArray.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexerOutput.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexInput.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexOutput.java
* index/org/eclipse/cdt/internal/core/index/impl/IndexSummary.java
* index/org/eclipse/cdt/internal/core/index/impl/InMemoryIndex.java
* index/org/eclipse/cdt/internal/core/index/impl/Int.java
* index/org/eclipse/cdt/internal/core/index/impl/MergeFactory.java
* index/org/eclipse/cdt/internal/core/index/impl/PropertyDocument.java
* index/org/eclipse/cdt/internal/core/index/impl/SafeRandomAccessFile.java
* index/org/eclipse/cdt/internal/core/index/impl/SimpleIndexInput.java
* index/org/eclipse/cdt/internal/core/index/impl/Util.java
* index/org/eclipse/cdt/internal/core/index/impl/WordEntry.java
* index/org/eclipse/cdt/internal/core/index/impl/WordEntryHashedArray.java
* index/org/eclipse/cdt/internal/core/search/CharOperation.java
* index/org/eclipse/cdt/internal/core/search/HashtableOfInt.java
* index/org/eclipse/cdt/internal/core/search/SimpleLookupTable.java
* index/org/eclipse/cdt/internal/core/search/Util.java
* index/org/eclipse/cdt/internal/core/search/message.properties
* index/org/eclipse/cdt/internal/core/search/indexing/AbstractIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFileToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/AddFolderToIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/IIndexConstants.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexAllProject.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java
* index/org/eclipse/cdt/internal/core/search/indexing/IndexRequest.java
* index/org/eclipse/cdt/internal/core/search/indexing/ReadWriteMonitor.java
* index/org/eclipse/cdt/internal/core/search/indexing/RemoveFolderFromIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/RemoveFromIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/SaveIndex.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexer.java
* index/org/eclipse/cdt/internal/core/search/indexing/SourceIndexerRequestor.java

View file

@ -1,184 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.index;
import java.io.IOException;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.impl.IndexDelta;
import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.IPath;
/**
* @author Bogdan Gheorghe
*/
/**
* An <code>ICDTIndexer</code> indexes ONE document at each time. It adds the document names and
* the words references to an IIndex. Each IIndexer can index certain types of document, and should
* not index the other files.
*
* Warning: This interface is still under development - API may change.
* @since 3.0
*/
public interface ICDTIndexer {
/**
* Indexer Support bit flags
*/
static public final int _DECLARATIONS = 1;
static public final int _DEFINITIONS = 2;
static public final int _REFERENCES = 4;
static public final int _LINENUMBERS = 8;
static public final int _OFFSETINFO = 16;
static public final int _CPP = 32;
static public final int _C = 64;
/**
* Indexer Policy bit flags
*/
static public final int _NORMAL= 1;
static public final int _POSTBUILD = 2;
static public final int _MANUAL = 4;
static public final int _STATIC = 8;
static public final int _DELAYUNTILBUILDINFO = 16;
/***
* Indexable units
*/
static public final int PROJECT = 1;
static public final int FOLDER = 2;
static public final int COMPILATION_UNIT = 4;
/**
* Returns what features this <code>ICDTIndexer</code> provides.
*/
public int getIndexerFeatures();
/**
* The <code>IndexManager</code> calls addRequest when it receives an event from the <code>DeltaProcessor</code>.
* The <code>IResourcDelta</code> and (TODO: <code>IResourceChangeEvent</code> are provided for indexers
* to decide how to schedule this event).
*/
public void addRequest(IProject project, IResourceDelta delta, int kind);
/**
* The <code>IndexManager</code> calls addRequest when it receives an event from the <code>DeltaProcessor</code>.
* The <code>IResourcDelta</code> and (TODO:<code>IResourceChangeEvent</code> are provided for the indexder
* to decide how to schedule this event).
*/
public void removeRequest(IProject project, IResourceDelta delta, int kind);
/**
* Adds the given resource to the IProject's index
*/
public void addResource(IProject project, IResource resource);
/**
* Removes the given resource from the IProject's index
*/
public void removeResource(IProject project, IResource resource);
/**
* Attempts to add the resource type specified by the path to the project's index
*/
public void addResourceByPath(IProject project, IPath path, int resourceType);
/**
* The <code>IndexManager</code> will send out a jobFinishedEvent to the indexer that
* had scheduled the previous runnign job to give that indexer a chance to update its
* state info.
*/
public void indexJobFinishedNotification(IIndexJob job);
/**
* The <code>IndexManager</code> will notify all indexers of impending shutdown events
* in order to allow indexers to perform whatever clean up they need to do.
*/
public void shutdown();
/**
* Called by the index manager when there are no index jobs queued up - can be
* used by the indexer to save indexes etc.
* @param idlingTime
*/
public void notifyIdle(long idlingTime);
/**
* Called by the index manager when a project has switched indexers to this
* type of indexer - can be used by the indexer to schedule initial jobs
* @param project - the project that has changed indexers
*/
public void notifyIndexerChange(IProject project);
/**
* Called by the index manager when a project has switched indexers to this
* type of indexer - can be used by the indexer to schedule initial jobs
* @param project - the project that has changed indexers
*/
public void notifyListeners(IndexDelta indexDelta);
/**
* Returns if this indexer is enabled
* @param project
* @return
*/
public boolean isIndexEnabled(IProject project);
/**
* Returns the storage used by this indexer.
* @return
*/
public IIndexStorage getIndexStorage();
/**
* Returns the index for the given path.
*
* @param path
* @param reuseExistingFile
* @param createIfMissing
* @return
*/
public IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing);
/**
* Called by the index manager when this indexer is about to be removed from a project.
* @param project
*/
public void indexerRemoved(IProject project);
/**
* Don't ask.
*
* @param index
* @return
*/
public ReadWriteMonitor getMonitorFor(IIndex index);
/**
* Don't tell.
*
* @param index
*/
public void saveIndex(IIndex index) throws IOException;
/**
* Associate a project with indexer
*
* @param project
*/
public void setIndexerProject(IProject project);
}

View file

@ -1,19 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.index;
public interface IIndexChangeListener {
/**
* @param event the change event
*/
public void indexChanged(IndexChangeEvent event);
}

View file

@ -1,46 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.index;
import java.util.List;
import org.eclipse.core.resources.IProject;
public interface IIndexDelta {
public class IndexDeltaType {
private IndexDeltaType( int value )
{
this.value = value;
}
private final int value;
}
public static final IndexDeltaType MERGE_DELTA = new IndexDeltaType( 0 );
public static final IndexDeltaType INDEX_FINISHED_DELTA = new IndexDeltaType( 1 );
/**
* @return Returns the files.
*/
public List getFiles();
/**
* @return Returns the project.
*/
public IProject getProject();
/**
* @return Returns the delta type.
*/
public IndexDeltaType getDeltaType();
}

View file

@ -1,30 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.index;
/**
* @author Bogdan Gheorghe
*
* IIndexStorage must be implemented by all indexStorage providers
*/
public interface IIndexStorage {
//Indexer that use this indexer storage
public ICDTIndexer[] getIndexers();
//Get path variables that are used
public String[] getPathVariables();
public void resolvePathVariables();
//Merge functionality for the storage
public void merge();
public boolean canMergeWith(IIndexStorage storage);
}

View file

@ -1,33 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.index;
import java.util.EventObject;
public class IndexChangeEvent extends EventObject {
/**
* @param source
*/
public IndexChangeEvent(IIndexDelta delta) {
super(delta);
}
/**
* Returns the delta describing the change.
*
*/
public IIndexDelta getDelta() {
return (IIndexDelta) source;
}
}

View file

@ -1,70 +0,0 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on May 28, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.eclipse.cdt.core.index;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.internal.core.index.nullindexer.NullIndexer;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.core.resources.IProject;
/**
* @author bgheorgh
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Indexer {
private static Indexer indexer = null;
private static IndexManager manager= CCorePlugin.getDefault().getCoreModel().getIndexManager();
public static boolean indexEnabledOnAllProjects(){
IProject[] projects= CCorePlugin.getWorkspace().getRoot().getProjects();
boolean allEnabled = true;
for (int i=0; i<projects.length; i++){
if (!indexEnabledOnProject(projects[i])){
allEnabled=false;
break;
}
}
return allEnabled;
}
public static boolean indexEnabledOnAnyProjects(){
IProject[] projects= CCorePlugin.getWorkspace().getRoot().getProjects();
boolean allEnabled = false;
for (int i=0; i<projects.length; i++){
if (!projects[i].isOpen())
continue;
if (indexEnabledOnProject(projects[i])){
allEnabled=true;
break;
}
}
return allEnabled;
}
public static boolean indexEnabledOnProject(IProject project){
ICDTIndexer _indexer = manager.getIndexerForProject(project);
if (_indexer instanceof NullIndexer)
return false;
return true;
}
}

View file

@ -1,95 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public abstract class CIndexStorageEntry implements ICIndexStorageEntry {
int meta_kind;
int entry_type;
int nameOffset;
int nameOffsetLength;
int nameOffsetType;
int elementOffset;
int elementOffsetLength;
int elementOffsetType;
int fileNumber;
public CIndexStorageEntry(int meta_kind, int entry_type, int fileNumber){
this.meta_kind = meta_kind;
this.entry_type = entry_type;
this.fileNumber = fileNumber;
}
public int getMetaKind() {
return meta_kind;
}
public int getEntryType() {
return entry_type;
}
public int getFileNumber(){
return fileNumber;
}
public int getNameOffset(){
return nameOffset;
}
public int getNameLength(){
return nameOffsetLength;
}
public int getNameOffsetType(){
return nameOffsetType;
}
public int getElementOffset(){
return elementOffset;
}
public int getElementLength(){
return elementOffsetLength;
}
public int getElementOffsetType(){
return elementOffsetType;
}
/**
* Sets the name offset
* @param offsetStart - the start of the name offset
* @param offsetLength - the length of the name offset
* @param offsetType - IIndex.LINE or IIndex.OFFSET
*/
public void setNameOffset(int offsetStart, int offsetLength, int offsetType){
this.nameOffset = offsetStart;
this.nameOffsetLength = offsetLength;
this.nameOffsetType = offsetType;
}
/**
* Sets the element offset
* @param offsetStart - the start of the name offset
* @param offsetLength - the length of the name offset
* @param offsetType - IIndex.LINE or IIndex.OFFSET
*/
public void setElementOffset(int offsetStart, int offsetLength, int offsetType){
this.elementOffset = offsetStart;
this.elementOffsetLength = offsetLength;
this.elementOffsetType = offsetType;
}
}

View file

@ -1,51 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public class FunctionEntry extends NamedEntry implements IFunctionEntry {
char[][] signature;
char[] returnString;
public FunctionEntry(int metakind, int entry_type, char[][] fullName, int modifiers,int fileNumber){
super(metakind,entry_type,fullName, modifiers, fileNumber);
}
public void setSignature(char[][] signature) {
this.signature = signature;
}
public char[][] getSignature() {
return signature;
}
public void setReturnType(char[] returnType) {
this.returnString = returnType;
}
public char[] getReturnType() {
return returnString;
}
public void serialize(IIndexerOutput output) {
output.addIndexEntry(this);
}
/* BugZilla ID#124618 */
public void setFunctionEntry(int meta_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber) {
setNamedEntry(meta_kind, entry_type, fullName, modifiers, fileNumber);
// since we reuse FunctionEntry instance,
// the following vars should be cleared.
this.signature = null;
this.returnString = null;
}
}

View file

@ -1,48 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public interface ICIndexStorageEntry {
/**
* @return Returns the metakind of this entry as defined in IIndex
*/
public int getMetaKind();
/**
* @return Returns the file number associated with this particular entry or 0 if file number has not been set
*/
public int getFileNumber();
/**
* @return Returns the starting offset for the name of this entry or 0 if the offset has not been set
*/
public int getNameOffset();
/**
* @return Returns the length of the name of this entry or 0 if the offset has not been set
*/
public int getNameLength();
/**
* @returns Returns the offset type for the name offset - IIndex.LINE or IIndex.OFFSET
*/
public int getNameOffsetType();
/**
* @return Returns the starting offset for the entry
*/
public int getElementOffset();
/**
* @returns Returns the length of this entry
*/
public int getElementLength();
/**
* @returns Returns the offset type for this element offset - IIndex.LINE or IIndex.OFFSET
*/
public int getElementOffsetType();
}

View file

@ -1,58 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
/**
* IEntryResult is the interface used to represent individual index
* entries for the purpose of client queries.
*/
public interface IEntryResult {
/**
* Returns the unique file numbers of files that have a
* reference to this entry.
*/
public int[] getFileReferences();
/**
* Returns the encoded word of this entry
*/
public int getMetaKind();
public int getKind();
public int getRefKind();
public String getName();
public String getDisplayString();
public String getStringMetaKind();
public String getStringKind();
public String getStringRefKind();
/**
* Returns the offsets for this entry - offsets are in the same position
* as the file references (ex. the first offset array belongs to the first
* file reference etc.)
*/
public int[][] getOffsets();
/**
* Returns the offset lengths for this entry - offset lengths map to the offset in the
* offset array
*/
public int[][] getOffsetLengths();
/**
* Returns the simple name for this IEntryResult.
*
* ex:
* typeDecl/V/foo/namespace returns "foo"
*/
public String extractSimpleName();
public String[] getEnclosingNames();
}

View file

@ -1,19 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public interface IFunctionEntry extends INamedEntry {
public char[][] getSignature();
public char[] getReturnType();
}

View file

@ -1,146 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
/**
* An IIndex is the interface used to generate an index file, and to make queries on
* this index.
*/
public interface IIndex {
//Used for offsets LINE = line based, while OFFSET = character offset
final static int LINE=1;
final static int OFFSET=2;
// Constants used to refer to index items
final static int ANY = 0;
// All index elements can be described as a triple (meta_kind, kind, type)
// meta_kind
final static int TYPE = 1;
final static int FUNCTION = 2;
final static int METHOD = 3;
final static int FIELD = 4;
final static int MACRO = 5;
final static int NAMESPACE = 6;
final static int ENUMTOR = 7;
final static int INCLUDE = 8;
final static int VAR = 9;
// kind
final static int TYPE_CLASS = 1;
final static int TYPE_STRUCT = 2;
final static int TYPE_UNION = 3;
final static int TYPE_ENUM = 4;
final static int TYPE_TYPEDEF = 5;
final static int TYPE_DERIVED = 6;
final static int TYPE_FRIEND = 7;
// type
final static int UNKNOWN = 0;
final static int DECLARATION = 1;
final static int REFERENCE = 2;
final static int DEFINITION = 3;
// modifiers
final static int privateAccessSpecifier = 1;
final static int publicAccessSpecifier = 2;
final static int protectedAccessSpecifier = 4;
final static int constQualifier = 8;
final static int volatileQualifier = 16;
final static int staticSpecifier = 32;
final static int externSpecifier = 64;
final static int inlineSpecifier = 128;
final static int virtualSpecifier = 256;
final static int pureVirtualSpecifier = 512;
final static int explicitSpecifier = 1024;
final static int autoSpecifier = 2048;
final static int registerSpecifier = 4096;
final static int mutableSpecifier = 8192;
/**
* Adds the given file to the index.
*/
void add(IFile file, IIndexerRunner indexer) throws IOException;
/**
* Empties the index.
*/
void empty() throws IOException;
/**
* Returns the index file on the disk.
*/
File getIndexFile();
/**
* Returns the number of documents indexed.
*/
String [] getDocumentList() throws IOException;
int getNumDocuments() throws IOException;
/**
* Returns the number of unique words indexed.
*/
int getNumWords() throws IOException;
/**
* Returns the path corresponding to a given document number
*/
String getPath(int documentNumber) throws IOException;
/**
* Ansers true if has some changes to save.
*/
boolean hasChanged();
/**
* Returns all entries for a given pattern.
*/
IEntryResult[] getEntries(int meta_kind, int kind, int ref, String name) throws IOException;
IEntryResult[] getEntries(int meta_kind, int kind, int ref) throws IOException;
/**
* Returns the paths of the documents whose names contain the given word.
*/
IQueryResult[] queryInDocumentNames(String word) throws IOException;
/**
* Returns the paths of the documents containing the given word prefix.
*/
IQueryResult[] getPrefix(int meta_kind, int kind, int ref, String name) throws IOException;
IQueryResult[] getPrefix(int meta_kind, int kind, int ref) throws IOException;
/**
* Removes the corresponding document from the index.
*/
void remove(String documentName) throws IOException;
/**
* Saves the index on the disk.
*/
void save() throws IOException;
/**
* @param path
* @return
*/
String[] getFileDependencies(IPath path) throws IOException;
String[] getFileDependencies(IFile file) throws IOException;
}

View file

@ -1,27 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public interface IIndexEntry {
/**
* Returns the type for this index entry.
* @return IIndex.DECLARATION, IIndex.DEFINITION or IIndex.REFERENCE
*/
public int getEntryType();
/**
* Write the entry to the passed in indexer output
* @param output
*/
public void serialize(IIndexerOutput output);
}

View file

@ -1,93 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
/**
* Generic indexer query interface to allow for queries of any existing indexer storage mechanism
* To be considered in development - not currently hooked up, but as a placeholder for future clients.
* See Bugzilla # 96775 for more details.
* @author bgheorgh
* @since 3.0
*/
public interface IIndexQuery {
/**
* Metakind bit field constants
*/
final static int CLASS = 1;
final static int STRUCT = 2;
final static int UNION = 4;
final static int ENUM = 8;
final static int VAR = 16;
final static int TYPEDEF = 32;
final static int FUNCTION = 64;
final static int METHOD = 128;
final static int FIELD = 256;
final static int MACRO = 512;
final static int NAMESPACE = 1024;
final static int ENUMTOR = 2048;
final static int INCLUDE = 4096;
/**
* Type bit field
*/
final static int DECLARATION = 1;
final static int DEFINITION = 2;
final static int REFERENCE= 4;
/**
* Returns the entries in the index corresponding to the passed in:
*
* @param metakind - bit field that indicates the kinds to retrieve
* @param type - bit field that indiciates what type of kinds to look for
* @param pattern - String array that contains the elements of a pattern;
* the interpretation of this array is left up to the implementor; can be left null
* in which case a match is attempted based on the metakind and type fields
* @param path - an IPath array that is used to limit the query; can be null to indicate
* entire workspace
*
* @return IIndexEntry
*/
IIndexEntry[] getIndexEntries(int metakind, int type, String[] pattern, IPath[] paths);
/**
* Returns the entries in the index corresponding to the passed in:
*
* @param metakind - bit field that indicates the kinds to retrieve
* @param type - bit field that indiciates what type of kinds to look for
* @param pattern - String array that contains the elements of a pattern;
* the interpretation of this array is left up to the implementor; can be left null
* in which case a match is attempted based on the metakind and type fields
* @param projects - an IProject array that contains the projects that are to be queried
*
* @return IIndexEntry
*/
IIndexEntry[] getIndexEntries(int metakind, int type, String[] pattern, IProject[] projects);
/**
* Returns the entries in the index corresponding to the passed in:
*
* @param metakind - bit field that indicates the kinds to retrieve
* @param type - bit field that indiciates what type of kinds to look for
* @param pattern - String array that contains the elements of a pattern;
* the interpretation of this array is left up to the implementor; can be left null
* in which case a match is attempted based on the metakind and type fields
* @param projects - an IProject array that contains the projects that are to be queried
* @param additionalPaths - an array for additional paths to query
*
* @return IIndexEntry
*/
IIndexEntry[] getIndexEntries(int metakind, int type, String[] pattern, IProject[] projects, IPath[] additionalPaths);
}

View file

@ -1,36 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexEntryNotSupportedException;
import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry;
/**
* This class represents the output from an indexer to an index
* for a single document.
*/
public interface IIndexerOutput {
public void addIndexEntry(IIndexEntry indexEntry) throws IndexEntryNotSupportedException;
public void addIndexEntry(ITypeEntry indexEntry);
public void addIndexEntry(INamedEntry indexEntry);
public void addIndexEntry(IFunctionEntry indexEntry);
public IndexedFileEntry getIndexedFile(String path);
public IndexedFileEntry addIndexedFile(String path);
//For Dep Tree
public void addIncludeRef(int indexedFileNumber, char [][] name, int offset, int offsetLength, int offsetType);
public void addIncludeRef(int indexedFileNumber, String word);
public void addRelatives(int indexedFileNumber, String inclusion, String parent);
}

View file

@ -1,35 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
import org.eclipse.core.resources.IFile;
/**
* An <code>IIndexer</code> indexes ONE document at each time. It adds the document names and
* the words references to an IIndex. Each IIndexer can index certain types of document, and should
* not index the other files.
*/
public interface IIndexerRunner {
/**
* Indexes the given file, adding the file name and the word references
* to this document to the given <code>IIndex</code>.The caller should use
* <code>shouldIndex()</code> first to determine whether this indexer handles
* the given type of file, and only call this method if so.
*/
void index(IFile document, IIndexerOutput output) throws java.io.IOException;
/**
* Returns whether the <code>IIndexer</code> can index the given IFile or not.
*/
public boolean shouldIndex(IFile file);
}

View file

@ -1,23 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public interface INamedEntry extends IIndexEntry, ICIndexStorageEntry {
/**
* @return Returns the fully qualified name of this entry
*/
public char[][] getFullName();
/**
* @return Returns the modifier bit field
*/
public int getModifiers();
}

View file

@ -1,16 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public interface IQueryResult {
String getPath();
int getFileID();
}

View file

@ -1,50 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
/**
* Interface used to encode type entries for the CIndexStorgage format
* Type entry constants are defined in IIndex. The list of types are:
*
* TYPE_CLASS
* TYPE_STRUCT
* TYPE_UNION
* TYPE_ENUM
* TYPE_VAR
* TYPE_TYPEDEF
* TYPE_DERIVED
* TYPE_FRIEND
* TYPE_FWD_CLASS
* TYPE_FWD_STRUCT
* TYPE_FWD_UNION
*
* @author bgheorgh
* @since 3.0
*/
public interface ITypeEntry extends INamedEntry {
/**
* Returns the kind of this type entry
* @return int representing type kind defined in IIndex.
*/
public int getTypeKind();
/**
* Returns the types that are inherited
* @return an array of index entries - each representing a separate type that this entry inherits from
*/
public IIndexEntry[] getBaseTypes();
/**
* Return friend types
* @return an array of index entries - each representing a friend to this type
*/
public IIndexEntry[] getFriends();
}

View file

@ -1,37 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.core.runtime.IPath;
public abstract class IndexRequest implements IIndexJob {
protected boolean isCancelled = false;
protected IPath indexPath = null;
public IndexRequest(IPath indexPath) {
this.indexPath = indexPath;
}
public boolean belongsTo(String projectName) {
return projectName.equals(this.indexPath.segment(0));
}
protected Integer updatedIndexState() {
return CIndexStorage.UPDATING_STATE;
}
public IPath getIndexPath(){
return indexPath;
}
}

View file

@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public class NamedEntry extends CIndexStorageEntry implements INamedEntry {
char[][] fullName;
int modifiers;
public NamedEntry(int meta_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber){
super(meta_kind, entry_type, fileNumber);
this.fullName = fullName;
this.modifiers = modifiers;
}
public NamedEntry(int meta_kind, int entry_type, String simpleName, int modifiers, int fileNumber){
super(meta_kind, entry_type, fileNumber);
this.fullName = new char[][]{simpleName.toCharArray()};
this.modifiers = modifiers;
}
public char[][] getFullName(){
return fullName;
}
public int getModifiers(){
return modifiers;
}
public void serialize(IIndexerOutput output) {
output.addIndexEntry(this);
}
/* BugZilla ID#124618 */
public void setNamedEntry(int meta_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber) {
this.entry_type = entry_type;
this.fileNumber = fileNumber;
this.fullName = fullName;
this.modifiers = modifiers;
}
}

View file

@ -1,395 +0,0 @@
package org.eclipse.cdt.internal.core.index;
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
import java.util.Vector;
public class StringMatcher {
protected String fPattern;
protected int fLength; // pattern length
protected boolean fIgnoreWildCards;
protected boolean fIgnoreCase;
protected boolean fHasLeadingStar;
protected boolean fHasTrailingStar;
protected String fSegments[]; //the given pattern is split into * separated segments
/* boundary value beyond which we don't need to search in the text */
protected int fBound= 0;
protected static final char fSingleWildCard= '\u0000';
public static class Position {
int start; //inclusive
int end; //exclusive
public Position(int start, int end) {
this.start= start;
this.end= end;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
}
/**
* Find the first occurrence of the pattern between <code>start</code)(inclusive)
* and <code>end</code>(exclusive).
* @param <code>text</code>, the String object to search in
* @param <code>start</code>, the starting index of the search range, inclusive
* @param <code>end</code>, the ending index of the search range, exclusive
* @return an <code>StringMatcher.Position</code> object that keeps the starting
* (inclusive) and ending positions (exclusive) of the first occurrence of the
* pattern in the specified range of the text; return null if not found or subtext
* is empty (start==end). A pair of zeros is returned if pattern is empty string
* Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
* is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
*/
public StringMatcher.Position find(String text, int start, int end) {
if (fPattern == null || text == null)
throw new IllegalArgumentException();
int tlen= text.length();
if (start < 0)
start= 0;
if (end > tlen)
end= tlen;
if (end < 0 || start >= end)
return null;
if (fLength == 0)
return new Position(start, start);
if (fIgnoreWildCards) {
int x= posIn(text, start, end);
if (x < 0)
return null;
return new Position(x, x + fLength);
}
int segCount= fSegments.length;
if (segCount == 0) //pattern contains only '*'(s)
return new Position(start, end);
int curPos= start;
int matchStart= -1;
for (int i= 0; i < segCount && curPos < end; ++i) {
String current= fSegments[i];
int nextMatch= regExpPosIn(text, curPos, end, current);
if (nextMatch < 0)
return null;
if (i == 0)
matchStart= nextMatch;
curPos= nextMatch + current.length();
}
return new Position(matchStart, curPos);
}
/**
* StringMatcher constructor takes in a String object that is a simple
* pattern which may contain *  for 0 and many characters and
* ?  for exactly one character. Also takes as parameter a boolean object
* specifying if case should be ignored
* @deprecated Use StringMatcher(pattern, ignoreCase, ignoreWildCards).
*/
public StringMatcher(String aPattern, boolean ignoreCase) {
this(aPattern, ignoreCase, false);
}
/**
* StringMatcher constructor takes in a String object that is a simple
* pattern which may contain *  for 0 and many characters and
* ?  for exactly one character.
*
* Literal '*' and '?' characters must be escaped in the pattern
* e.g., "\*" means literal "*", etc.
*
* Escaping any other character (including the escape character itself),
* just results in that character in the pattern.
* e.g., "\a" means "a" and "\\" means "\"
*
* If invoking the StringMatcher with string literals in Java, don't forget
* escape characters are represented by "\\".
*
* @param aPattern the pattern to match text against
* @param ignoreCase if true, case is ignored
* @param ignoreWildCards if true, wild cards and their escape sequences are ignored
* (everything is taken literally).
*/
public StringMatcher(String aPattern, boolean ignoreCase, boolean ignoreWildCards) {
fIgnoreCase= ignoreCase;
fIgnoreWildCards= ignoreWildCards;
fLength= aPattern.length();
/* convert case */
if (fIgnoreCase) {
fPattern= aPattern.toUpperCase();
} else {
fPattern= aPattern;
}
if (fIgnoreWildCards) {
parseNoWildCards();
} else {
parseWildCards();
}
}
/**
* Given the starting (inclusive) and the ending (exclusive) poisitions in the
* <code>text</code>, determine if the given substring matches with aPattern
* @return true if the specified portion of the text matches the pattern
* @param String <code>text</code>, a String object that contains the substring to match
* @param int <code>start<code> marks the starting position (inclusive) of the substring
* @param int <code>end<code> marks the ending index (exclusive) of the substring
*/
public boolean match(String text, int start, int end) {
if (null == fPattern || null == text)
throw new IllegalArgumentException();
if (start > end)
return false;
if (fIgnoreWildCards)
return fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength);
int segCount= fSegments.length;
if (segCount == 0) //pattern contains only '*'(s) or empty pattern
return true;
if (start == end)
return fLength == 0;
if (fLength == 0)
return start == end;
int tlen= text.length();
if (start < 0)
start= 0;
if (end > tlen)
end= tlen;
int tCurPos= start;
int bound= end - fBound;
if (bound < 0)
return false;
int i= 0;
String current= fSegments[i];
int segLength= current.length();
/* process first segment */
if (!fHasLeadingStar) {
if (!regExpRegionMatches(text, start, current, 0, segLength)) {
return false;
} else {
++i;
tCurPos= tCurPos + segLength;
}
}
/* process middle segments */
for (; i < segCount && tCurPos <= bound; ++i) {
current= fSegments[i];
int currentMatch;
int k= current.indexOf(fSingleWildCard);
if (k < 0) {
currentMatch= textPosIn(text, tCurPos, end, current);
if (currentMatch < 0)
return false;
} else {
currentMatch= regExpPosIn(text, tCurPos, end, current);
if (currentMatch < 0)
return false;
}
tCurPos= currentMatch + current.length();
}
/* process final segment */
if (!fHasTrailingStar && tCurPos != end) {
int clen= current.length();
return regExpRegionMatches(text, end - clen, current, 0, clen);
}
return i == segCount;
}
/**
* match the given <code>text</code> with the pattern
* @return true if matched eitherwise false
* @param <code>text</code>, a String object
*/
public boolean match(String text) {
return match(text, 0, text.length());
}
/**
* This method parses the given pattern into segments seperated by wildcard '*' characters.
* Since wildcards are not being used in this case, the pattern consists of a single segment.
*/
private void parseNoWildCards() {
fSegments= new String[1];
fSegments[0]= fPattern;
fBound= fLength;
}
/**
* This method parses the given pattern into segments seperated by wildcard '*' characters.
* @param p, a String object that is a simple regular expression with *  and/or ? 
*/
private void parseWildCards() {
if (fPattern.startsWith("*")) //$NON-NLS-1$
fHasLeadingStar= true;
if (fPattern.endsWith("*")) { //$NON-NLS-1$
/* make sure it's not an escaped wildcard */
if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
fHasTrailingStar= true;
}
}
Vector temp= new Vector();
int pos= 0;
StringBuffer buf= new StringBuffer();
while (pos < fLength) {
char c= fPattern.charAt(pos++);
switch (c) {
case '\\' :
if (pos >= fLength) {
buf.append(c);
} else {
char next= fPattern.charAt(pos++);
/* if it's an escape sequence */
if (next == '*' || next == '?' || next == '\\') {
buf.append(next);
} else {
/* not an escape sequence, just insert literally */
buf.append(c);
buf.append(next);
}
}
break;
case '*' :
if (buf.length() > 0) {
/* new segment */
temp.addElement(buf.toString());
fBound += buf.length();
buf.setLength(0);
}
break;
case '?' :
/* append special character representing single match wildcard */
buf.append(fSingleWildCard);
break;
default :
buf.append(c);
}
}
/* add last buffer to segment list */
if (buf.length() > 0) {
temp.addElement(buf.toString());
fBound += buf.length();
}
fSegments= new String[temp.size()];
temp.copyInto(fSegments);
}
/**
* @param <code>text</code>, a string which contains no wildcard
* @param <code>start</code>, the starting index in the text for search, inclusive
* @param <code>end</code>, the stopping point of search, exclusive
* @return the starting index in the text of the pattern , or -1 if not found
*/
protected int posIn(String text, int start, int end) { //no wild card in pattern
int max= end - fLength;
if (!fIgnoreCase) {
int i= text.indexOf(fPattern, start);
if (i == -1 || i > max)
return -1;
return i;
}
for (int i= start; i <= max; ++i) {
if (text.regionMatches(true, i, fPattern, 0, fLength))
return i;
}
return -1;
}
/**
* @param <code>text</code>, a simple regular expression that may only contain '?'(s)
* @param <code>start</code>, the starting index in the text for search, inclusive
* @param <code>end</code>, the stopping point of search, exclusive
* @param <code>p</code>, a simple regular expression that may contains '?'
* @param <code>caseIgnored</code>, wether the pattern is not casesensitive
* @return the starting index in the text of the pattern , or -1 if not found
*/
protected int regExpPosIn(String text, int start, int end, String p) {
int plen= p.length();
int max= end - plen;
for (int i= start; i <= max; ++i) {
if (regExpRegionMatches(text, i, p, 0, plen))
return i;
}
return -1;
}
/**
*
* @return boolean
* @param <code>text</code>, a String to match
* @param <code>start</code>, int that indicates the starting index of match, inclusive
* @param <code>end</code> int that indicates the ending index of match, exclusive
* @param <code>p</code>, String, String, a simple regular expression that may contain '?'
* @param <code>ignoreCase</code>, boolean indicating wether code>p</code> is case sensitive
*/
protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) {
while (plen-- > 0) {
char tchar= text.charAt(tStart++);
char pchar= p.charAt(pStart++);
/* process wild cards */
if (!fIgnoreWildCards) {
/* skip single wild cards */
if (pchar == fSingleWildCard) {
continue;
}
}
if (pchar == tchar)
continue;
if (fIgnoreCase) {
char tc= Character.toUpperCase(tchar);
if (tc == pchar)
continue;
}
return false;
}
return true;
}
/**
* @param <code>text</code>, the string to match
* @param <code>start</code>, the starting index in the text for search, inclusive
* @param <code>end</code>, the stopping point of search, exclusive
* @param code>p</code>, a string that has no wildcard
* @param <code>ignoreCase</code>, boolean indicating wether code>p</code> is case sensitive
* @return the starting index in the text of the pattern , or -1 if not found
*/
protected int textPosIn(String text, int start, int end, String p) {
int plen= p.length();
int max= end - plen;
if (!fIgnoreCase) {
int i= text.indexOf(p, start);
if (i == -1 || i > max)
return -1;
return i;
}
for (int i= 0; i <= max; ++i) {
if (text.regionMatches(true, i, p, 0, plen))
return i;
}
return -1;
}
}

View file

@ -1,62 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index;
public class TypeEntry extends NamedEntry implements ITypeEntry {
int type_kind;
IIndexEntry[] baseTypes;
IIndexEntry[] friends;
public TypeEntry(int type_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber){
super(IIndex.TYPE, entry_type, fullName, modifiers, fileNumber);
this.type_kind = type_kind;
}
public void serialize(IIndexerOutput output) {
output.addIndexEntry(this);
}
public int getTypeKind() {
return type_kind;
}
public void setBaseTypes(IIndexEntry[] baseTypes) {
this.baseTypes=baseTypes;
}
public IIndexEntry[] getBaseTypes() {
return baseTypes;
}
public IIndexEntry[] getFriends() {
return friends;
}
public void setFriends(IIndexEntry[] friends) {
this.friends = friends;
}
/* BugZilla ID#124618 */
public void setTypeEntry(int type_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber) {
this.entry_type = entry_type;
this.fileNumber = fileNumber;
this.fullName = fullName;
this.modifiers = modifiers;
this.type_kind = type_kind;
// since we reuse TypeEntry instance,
// the following vars should be cleared.
this.baseTypes = null;
this.friends = null;
}
}

View file

@ -1,502 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.CRC32;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.index.ICDTIndexer;
import org.eclipse.cdt.core.index.IIndexStorage;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.IndexRequest;
import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMIndexRequest;
import org.eclipse.cdt.internal.core.search.CWorkspaceScope;
import org.eclipse.cdt.internal.core.search.IndexSelector;
import org.eclipse.cdt.internal.core.search.SimpleLookupTable;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor;
import org.eclipse.cdt.internal.core.search.processing.IIndexJob;
import org.eclipse.cdt.internal.core.search.processing.JobManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
/**
* @author Bogdan Gheorghe
*/
public class CIndexStorage implements IIndexStorage {
/* number of file contents in memory */
public static int MAX_FILES_IN_MEMORY = 0;
public IWorkspace workspace;
public SimpleLookupTable indexNames = new SimpleLookupTable();
/* index */
private IIndex index;
/* read write monitor */
private ReadWriteMonitor monitor;
/* need to save ? */
private boolean needToSave = false;
private static final CRC32 checksumCalculator = new CRC32();
private IPath cCorePluginLocation = null;
/* can only replace a current state if its less than the new one */
private SimpleLookupTable indexStates = null;
private File savedIndexNamesFile =
new File(getCCorePluginWorkingLocation().append("savedIndexNames.txt").toOSString()); //$NON-NLS-1$
private SimpleLookupTable encounteredHeaders = null;
public static Integer SAVED_STATE = new Integer(0);
public static Integer UPDATING_STATE = new Integer(1);
public static Integer UNKNOWN_STATE = new Integer(2);
public static Integer REBUILDING_STATE = new Integer(3);
public static boolean VERBOSE = false;
private ICDTIndexer indexer = null;
private IndexManager indexManager = null;
public ReadWriteMonitor indexAccessMonitor = null;
public CIndexStorage(ICDTIndexer indexer){
this.indexer = indexer;
this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager();
}
public void aboutToUpdateIndex(IPath path, Integer newIndexState) {
// newIndexState is either UPDATING_STATE or REBUILDING_STATE
// must tag the index as inconsistent, in case we exit before the update job is started
String indexName = computeIndexName(path);
Object state = getIndexStates().get(indexName);
Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
if (currentIndexState.equals(REBUILDING_STATE)) return; // already rebuilding the index
int compare = newIndexState.compareTo(currentIndexState);
if (compare > 0) {
// so UPDATING_STATE replaces SAVED_STATE and REBUILDING_STATE replaces everything
updateIndexState(indexName, newIndexState);
} else if (compare < 0 && index == null) {
// if already cached index then there is nothing more to do
rebuildIndex(indexName, path);
}
}
String computeIndexName(IPath path) {
String name = (String) indexNames.get(path);
if (name == null) {
String pathString = path.toOSString();
checksumCalculator.reset();
checksumCalculator.update(pathString.getBytes());
String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; //$NON-NLS-1$
if (IndexManager.VERBOSE)
JobManager.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$
name = getCCorePluginWorkingLocation().append(fileName).toOSString();
indexNames.put(path, name);
}
return name;
}
/**
* Returns the index for a given project, according to the following algorithm:
* - if index is already in memory: answers this one back
* - if (reuseExistingFile) then read it and return this index and record it in memory
* - if (createIfMissing) then create a new empty index and record it in memory
*
* Warning: Does not check whether index is consistent (not being used)
*/
public synchronized IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing) {
// Path is already canonical per construction
if (index == null) {
String indexName = computeIndexName(path);
Object state = getIndexStates().get(indexName);
Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state;
if (currentIndexState == UNKNOWN_STATE) {
// should only be reachable for query jobs
rebuildIndex(indexName, path);
return null;
}
// index isn't cached, consider reusing an existing index file
if (reuseExistingFile) {
File indexFile = new File(indexName);
if (indexFile.exists()) { // check before creating index so as to avoid creating a new empty index if file is missing
try {
index = new Index(indexName, "Index for " + path.toOSString(), true /*reuse index file*/, indexer); //$NON-NLS-1$
monitor= new ReadWriteMonitor();
return index;
} catch (IOException e) {
// failed to read the existing file or its no longer compatible
if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt
if (IndexManager.VERBOSE)
JobManager.verbose("-> cannot reuse existing index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
rebuildIndex(indexName, path);
return null;
}
index = null; // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate
}
}
if (currentIndexState == SAVED_STATE) { // rebuild index if existing file is missing
rebuildIndex(indexName, path);
return null;
}
}
// index wasn't found on disk, consider creating an empty new one
if (createIfMissing) {
try {
if (VERBOSE)
JobManager.verbose("-> create empty index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
index = new Index(indexName, "Index for " + path.toOSString(), false /*do not reuse index file*/, indexer); //$NON-NLS-1$
monitor=new ReadWriteMonitor();
return index;
} catch (IOException e) {
if (VERBOSE)
JobManager.verbose("-> unable to create empty index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
// The file could not be created. Possible reason: the project has been deleted.
return null;
}
}
}
//System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
return index;
}
private SimpleLookupTable getIndexStates() {
if (indexStates != null) return indexStates;
this.indexStates = new SimpleLookupTable();
char[] savedIndexNames = readIndexState();
if (savedIndexNames.length > 0) {
char[][] names = CharOperation.splitOn('\n', savedIndexNames);
for (int i = 0, l = names.length; i < l; i++) {
char[] name = names[i];
if (name.length > 0)
this.indexStates.put(new String(name), SAVED_STATE);
}
}
return this.indexStates;
}
public SimpleLookupTable getEncounteredHeaders(){
if (encounteredHeaders == null){
this.encounteredHeaders = new SimpleLookupTable();
}
return this.encounteredHeaders;
}
/**
* Resets the headers table
*/
public void resetEncounteredHeaders() {
this.encounteredHeaders = null;
}
private IPath getCCorePluginWorkingLocation() {
if (this.cCorePluginLocation != null) return this.cCorePluginLocation;
return this.cCorePluginLocation = CCorePlugin.getDefault().getStateLocation();
}
/**
* Index access is controlled through a read-write monitor so as
* to ensure there is no concurrent read and write operations
* (only concurrent reading is allowed).
*/
public ReadWriteMonitor getMonitorForIndex(){
return monitor;
}
private void rebuildIndex(String indexName, IPath path) {
Object target = org.eclipse.cdt.internal.core.Util.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true);
if (target == null) return;
if (IndexManager.VERBOSE)
JobManager.verbose("-> request to rebuild index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
updateIndexState(indexName, REBUILDING_STATE);
DOMIndexRequest request = null;
if (target instanceof IProject) {
IProject p = (IProject) target;
if( p.exists() && indexer.isIndexEnabled( p ) )
//request = new IndexAllProject(p, indexer);
indexer.addRequest(p, null, ICDTIndexer.PROJECT);
}
if (request != null)
indexManager.request(request);
}
/**
* Recreates the index for a given path, keeping the same read-write monitor.
* Returns the new empty index or null if it didn't exist before.
* Warning: Does not check whether index is consistent (not being used)
*/
public synchronized IIndex recreateIndex(IPath path) {
// only called to over write an existing cached index...
try {
// Path is already canonical
String indexPath = computeIndexName(path);
if (IndexManager.VERBOSE)
JobManager.verbose("-> recreating index: "+indexPath+" for path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
index = new Index(indexPath, "Index for " + path.toOSString(), false /*reuse index file*/,indexer); //$NON-NLS-1$
//Monitor can be left alone - no need to recreate
return index;
} catch (IOException e) {
// The file could not be created. Possible reason: the project has been deleted.
if (IndexManager.VERBOSE) {
JobManager.verbose("-> failed to recreate index for path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
return null;
}
}
/**
* Removes the index for a given path.
* This is a no-op if the index did not exist.
*/
public synchronized void removeIndex(IPath path) {
if (IndexManager.VERBOSE)
JobManager.verbose("removing index " + path); //$NON-NLS-1$
String indexName = computeIndexName(path);
File indexFile = new File(indexName);
if (indexFile.exists())
indexFile.delete();
index=null;
monitor=null;
updateIndexState(indexName, null);
}
/**
* Removes all indexes whose paths start with (or are equal to) the given path.
*/
public synchronized void removeIndexFamily(IPath path) {
// only finds cached index files... shutdown removes all non-cached index files
this.removeIndex(path);
}
public void saveIndex(IIndex index) throws IOException {
// must have permission to write from the write monitor
if (index.hasChanged()) {
if (IndexManager.VERBOSE)
JobManager.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$
index.save();
}
String indexName = index.getIndexFile().getPath();
if (indexManager.getJobEnd() > indexManager.getJobStart()) {
Object indexPath = indexNames.keyForValue(indexName);
if (indexPath != null) {
for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) { // skip the current job
IIndexJob job = indexManager.getAwaitingJobAt(i);
if (job instanceof DOMIndexRequest)
if (((IndexRequest) job).getIndexPath().equals(indexPath)) return;
}
}
}
updateIndexState(indexName, SAVED_STATE);
}
/**
* Commit all index memory changes to disk
*/
public void saveIndexes() {
// only save cached indexes... the rest were not modified
ReadWriteMonitor monitor = getMonitorForIndex();
if (monitor == null) return; // index got deleted since acquired
try {
monitor.enterWrite();
try {
saveIndex(index);
} catch(IOException e){
if (IndexManager.VERBOSE) {
JobManager.verbose("-> got the following exception while saving:"); //$NON-NLS-1$
e.printStackTrace();
}
//Util.log(e);
}
} finally {
monitor.exitWrite();
}
needToSave = false;
}
public void shutdown() {
if (IndexManager.VERBOSE)
JobManager.verbose("Shutdown"); //$NON-NLS-1$
//Get index entries for all projects in the workspace, store their absolute paths
IndexSelector indexSelector = new IndexSelector(new CWorkspaceScope(), null, false, indexManager);
IIndex[] selectedIndexes = indexSelector.getIndexes();
SimpleLookupTable knownPaths = new SimpleLookupTable();
for (int i = 0, max = selectedIndexes.length; i < max; i++) {
String path = selectedIndexes[i].getIndexFile().getAbsolutePath();
knownPaths.put(path, path);
}
//Any index entries that are in the index state must have a corresponding
//path entry - if not they are removed from the saved indexes file
if (indexStates != null) {
Object[] indexNames = indexStates.keyTable;
for (int i = 0, l = indexNames.length; i < l; i++) {
String key = (String) indexNames[i];
if (key != null && !knownPaths.containsKey(key)) //here is an index that is in t
updateIndexState(key, null);
}
}
//Clean up the .metadata folder - if there are any files in the directory that
//are not associated to an index we delete them
File indexesDirectory = new File(getCCorePluginWorkingLocation().toOSString());
if (indexesDirectory.isDirectory()) {
File[] indexesFiles = indexesDirectory.listFiles();
if (indexesFiles != null) {
for (int i = 0, indexesFilesLength = indexesFiles.length; i < indexesFilesLength; i++) {
String fileName = indexesFiles[i].getAbsolutePath();
if (!knownPaths.containsKey(fileName) && fileName.toLowerCase().endsWith(".index")) { //$NON-NLS-1$
if (IndexManager.VERBOSE)
JobManager.verbose("Deleting index file " + indexesFiles[i]); //$NON-NLS-1$
indexesFiles[i].delete();
}
}
}
}
}
public String toString() {
StringBuffer buffer = new StringBuffer(10);
buffer.append(super.toString());
buffer.append("In-memory indexes:\n"); //$NON-NLS-1$
int count = 0;
buffer.append(++count).append(" - ").append(index.toString()).append('\n'); //$NON-NLS-1$
return buffer.toString();
}
private char[] readIndexState() {
try {
return org.eclipse.cdt.internal.core.Util.getFileCharContent(savedIndexNamesFile, null);
} catch (IOException ignored) {
if (IndexManager.VERBOSE)
JobManager.verbose("Failed to read saved index file names"); //$NON-NLS-1$
return new char[0];
}
}
private void updateIndexState(String indexName, Integer indexState) {
getIndexStates(); // ensure the states are initialized
if (indexState != null) {
if (indexState.equals(indexStates.get(indexName))) return; // not changed
indexStates.put(indexName, indexState);
} else {
if (!indexStates.containsKey(indexName)) return; // did not exist anyway
indexStates.removeKey(indexName);
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(savedIndexNamesFile));
Object[] indexNames = indexStates.keyTable;
Object[] states = indexStates.valueTable;
for (int i = 0, l = states.length; i < l; i++) {
if (states[i] == SAVED_STATE) {
writer.write((String) indexNames[i]);
writer.write('\n');
}
}
} catch (IOException ignored) {
if (IndexManager.VERBOSE)
JobManager.verbose("Failed to write saved index file names"); //$NON-NLS-1$
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {}
}
}
if (IndexManager.VERBOSE) {
String state = "?"; //$NON-NLS-1$
if (indexState == SAVED_STATE) state = "SAVED"; //$NON-NLS-1$
else if (indexState == UPDATING_STATE) state = "UPDATING"; //$NON-NLS-1$
else if (indexState == UNKNOWN_STATE) state = "UNKNOWN"; //$NON-NLS-1$
else if (indexState == REBUILDING_STATE) state = "REBUILDING"; //$NON-NLS-1$
JobManager.verbose("-> index state updated to: " + state + " for: "+indexName); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.index2.IIndexStorage#getIndexers()
*/
public ICDTIndexer[] getIndexers() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.index2.IIndexStorage#getPathVariables()
*/
public String[] getPathVariables() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.index2.IIndexStorage#resolvePathVariables()
*/
public void resolvePathVariables() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.index2.IIndexStorage#merge()
*/
public void merge() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.index2.IIndexStorage#canMergeWith(org.eclipse.cdt.core.index2.IIndexStorage)
*/
public boolean canMergeWith(IIndexStorage storage) {
// TODO Auto-generated method stub
return false;
}
public boolean getNeedToSave() {
return needToSave;
}
public void setNeedToSave(boolean needToSave) {
this.needToSave = needToSave;
}
public void jobWasCancelled(IPath path) {
index=null;
monitor=null;
updateIndexState(computeIndexName(path), UNKNOWN_STATE);
}
public ReadWriteMonitor getIndexAccessMonitor() {
return indexAccessMonitor;
}
}

View file

@ -1,238 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.search.indexing.IndexManager;
import org.eclipse.cdt.internal.core.search.processing.JobManager;
public class EntryResult implements IEntryResult {
private int[] fileRefs;
private int[][] offsets;
private int[][] offsetLengths;
private int meta_type;
private int kind;
private int reftype;
private String longname;
public EntryResult(char[] word, int[] refs, int[][] offsets, int[][] offsetLengths) {
this.fileRefs = refs;
this.offsets = offsets;
this.offsetLengths = offsetLengths;
decode(word);
}
public boolean equals(Object anObject){
if (this == anObject) {
return true;
}
if ((anObject != null) && (anObject instanceof EntryResult)) {
EntryResult anEntryResult = (EntryResult) anObject;
if( this.meta_type != anEntryResult.meta_type ||
this.kind != anEntryResult.kind ||
this.reftype != anEntryResult.reftype ||
! this.longname.equals(anEntryResult.longname))
return false;
int length;
int[] refs, otherRefs;
if ((length = (refs = this.fileRefs).length) != (otherRefs = anEntryResult.fileRefs).length) return false;
for (int i = 0; i < length; i++){
if (refs[i] != otherRefs[i]) return false;
}
return true;
}
return false;
}
public int[] getFileReferences() {
return fileRefs;
}
public char[] getWord() {
return Index.encodeEntry(meta_type, kind, reftype, longname);
}
public int hashCode(){
return CharOperation.hashCode(getWord());
}
public String toString(){
StringBuffer buffer = new StringBuffer();
buffer.append("EntryResult: " + getName() + "\n\tmeta="); //$NON-NLS-1$ //$NON-NLS-2$
buffer.append(ICIndexStorageConstants.encodings[meta_type]);
if(meta_type == IIndex.TYPE) {
buffer.append(" type="); //$NON-NLS-1$
buffer.append(ICIndexStorageConstants.typeConstantNames[kind]);
}
buffer.append(" Reference="); //$NON-NLS-1$
buffer.append(ICIndexStorageConstants.encodingTypes[reftype]);
buffer.append(", refs={"); //$NON-NLS-1$
for (int i = 0; i < fileRefs.length; i++){
if (i > 0) buffer.append(',');
buffer.append(' ');
buffer.append(fileRefs[i]);
}
buffer.append(" }, offsets={"); //$NON-NLS-1$
for (int i = 0; i < offsets.length; i++){
if (i > 0) buffer.append(',');
buffer.append(' ');
buffer.append('[');
for (int j=0; j<offsets[i].length; j++){
if (j > 0) buffer.append(',');
buffer.append(' ');
buffer.append(offsets[i][j]);
}
buffer.append(']');
}
buffer.append(" }\n"); //$NON-NLS-1$
return buffer.toString();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.IEntryResult#getOffsets()
*/
public int[][] getOffsets() {
return offsets;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.IEntryResult#getOffsetLengths()
*/
public int[][] getOffsetLengths() {
return offsetLengths;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.IEntryResult#extractSimpleName()
*/
public String extractSimpleName() {
int sepPos=longname.indexOf(IndexerOutput.SEPARATOR);
if (sepPos>=0)
return longname.substring(0, sepPos);
else
return longname;
}
private void decode(char [] word) {
int pos = 0;
meta_type = 0;
for (int i = 1; i < ICIndexStorageConstants.encodings.length; i ++){
if (CharOperation.prefixEquals(ICIndexStorageConstants.encodings[i], word)) {
meta_type = i;
pos += ICIndexStorageConstants.encodings[i].length;
break;
}
}
for ( int i = 1; i < ICIndexStorageConstants.encodingTypes.length; i++) {
if (CharOperation.fragmentEquals(ICIndexStorageConstants.encodingTypes[i], word, pos, true)) {
reftype = i;
pos += ICIndexStorageConstants.encodingTypes[i].length;
break;
}
}
if (meta_type == IIndex.TYPE) {
for (int i = 1; i < Index.typeConstants.length; i++) {
if (word[pos] == Index.typeConstants[i]) {
kind = i;
pos++;
break;
}
}
// skip over separator
if (word[pos] != ICIndexStorageConstants.SEPARATOR) {
if (IndexManager.VERBOSE)
JobManager.verbose("Invalid encoding encoutered while decoding Entry Result"); //$NON-NLS-1$
}
pos++;
}
else
kind = IIndex.ANY;
longname = new String(word, pos, word.length - pos);
}
public String[] getEnclosingNames() {
int slash=longname.indexOf(IndexerOutput.SEPARATOR);
String[] enclosingNames= null;
if (slash != -1 && slash + 1 < longname.length()) {
char[][] temp = CharOperation.splitOn('/', CharOperation.subarray(longname.toCharArray(), slash + 1, -1));
enclosingNames= new String[temp.length];
for (int i = 0; i < temp.length; i++) {
enclosingNames[i] = String.valueOf(temp[temp.length - i - 1]);
}
}
return enclosingNames;
}
public int getMetaKind() {
return meta_type;
}
public int getKind() {
return kind;
}
public int getRefKind() {
return reftype;
}
public String getName() {
return longname;
}
public String getStringMetaKind() {
return String.valueOf(ICIndexStorageConstants.encodings[meta_type]);
}
public String getStringKind() {
return ICIndexStorageConstants.typeConstantNames[kind];
}
public String getStringRefKind() {
return String.valueOf(ICIndexStorageConstants.encodingTypes[reftype]);
}
public String getDisplayString() {
switch (meta_type) {
case IIndex.FUNCTION:
case IIndex.METHOD:
int startReturn = longname.indexOf(")R/"); //$NON-NLS-1$
int finishReturn = longname.indexOf("/R("); //$NON-NLS-1$
int startParam = longname.indexOf("/)", finishReturn); //$NON-NLS-1$
int finishParam = longname.indexOf("/(", startParam); //$NON-NLS-1$
String functionName;
String arguments = ""; //$NON-NLS-1$
if (startParam + 2 < finishParam)
arguments = longname.substring(startParam + 3, finishParam);
// TODO: flip arguments
arguments = arguments.replace('/',',');
arguments = '(' + arguments + ')';
if (startReturn == -1 || finishReturn == -1) {
// there is no return type !!!
functionName = longname.substring(0, startParam -1);
return functionName + arguments ;
}
else {
String returnType = ""; //$NON-NLS-1$
if (startReturn + 3 < finishReturn) {
returnType = longname.substring(startReturn + 3, finishReturn);
}
functionName = longname.substring(0, startReturn -1);
return functionName + arguments + ':' + returnType;
}
default:
return longname;
}
}
}

View file

@ -1,88 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
public interface ICIndexStorageConstants {
/**
* The signature of the index file.
*/
public static final String SIGNATURE= "INDEX FILE 0.017"; //$NON-NLS-1$
/**
* The size of a block for a <code>Block</code>.
*/
public static final int BLOCK_SIZE= 8192;
final public static char SEPARATOR= '/';
final static char [][] encodings = {
"".toCharArray(), // not used //$NON-NLS-1$
"type".toCharArray(), // TYPES //$NON-NLS-1$
"function".toCharArray(), // FUNCTIONS //$NON-NLS-1$
"method".toCharArray(), // METHODS //$NON-NLS-1$
"field".toCharArray(), // FIELDS //$NON-NLS-1$
"macro".toCharArray(), // MACROS //$NON-NLS-1$
"namespace".toCharArray(), // NAMESPACES //$NON-NLS-1$
"enumtor".toCharArray(), // ENUMERATORS //$NON-NLS-1$
"include" .toCharArray(), // INCLUDES //$NON-NLS-1$
"variable" .toCharArray() // VARIABLE //$NON-NLS-1$
};
final static char [][] encodingTypes = {
"".toCharArray(), // not used //$NON-NLS-1$
"Decl/".toCharArray(), // DECLARATIONS //$NON-NLS-1$
"Ref/".toCharArray(), // REFERENCES //$NON-NLS-1$
"Defn/".toCharArray() // DEFINTIONS //$NON-NLS-1$
};
final static char[] typeConstants = { ' ', // not used
'C', // CLASS
'S', // STRUCT
'U', // UNION
'E', // ENUM
'T', // TYPEDEF
'D', // DERIVED
'F' // FRIEND
};
final static String[] typeConstantNames = { "", // not used //$NON-NLS-1$
"Class", //$NON-NLS-1$
"Struct", //$NON-NLS-1$
"Union", //$NON-NLS-1$
"Enum", //$NON-NLS-1$
"Typedef", //$NON-NLS-1$
"Derived", //$NON-NLS-1$
"Friend", //$NON-NLS-1$
};
final static String[] allSpecifiers = {"", //not used //$NON-NLS-1$
"private", // private //$NON-NLS-1$
"public", // public //$NON-NLS-1$
"protected", // protected //$NON-NLS-1$
"const", // const //$NON-NLS-1$
"volatile", // volatile //$NON-NLS-1$
"static", // static //$NON-NLS-1$
"extern", // extern //$NON-NLS-1$
"inline", // inline //$NON-NLS-1$
"virtual", // virtual //$NON-NLS-1$
"pure virtual", // pure virtual //$NON-NLS-1$
"explicit", // explicit //$NON-NLS-1$
"auto", // auto //$NON-NLS-1$
"register", // register //$NON-NLS-1$
"mutable" // mutable //$NON-NLS-1$
};
}

View file

@ -1,297 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import java.io.File;
import java.io.IOException;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexOutput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexOutput;
/**
* This index stores the document names in an <code>ObjectVector</code>, and the words in
* an <code>HashtableOfObjects</code>.
*/
public class InMemoryIndex {
/**
* hashtable of IncludeEntrys = includeFiles+numbers of the files they appear in.
*/
protected IncludeEntryHashedArray includes;
/**
* Array of WordEntry
*/
protected WordEntryHashedArray words;
/**
* Array of IndexedFileEntry
*/
protected IndexedFileEntryHashedArray files;
/**
* Array of IndexedPathVariableEntry = file name + a unique number.
*/
protected IndexPathVariableEntryHashedArray pathVars;
/**
* Size of the index.
*/
protected long footprint;
private IncludeEntry[] sortedIncludeEntries;
private WordEntry[] sortedWordEntries;
private IndexedFileEntry[] sortedFiles;
private IndexPathVariableEntry[] sortedPathVars;
private int lastId;
public InMemoryIndex() {
init();
}
public IndexedFileEntry addFile(String path){
IndexedFileEntry indexedFileEntry = this.files.add(path);
this.footprint += indexedFileEntry.footprint() + 4;
this.sortedFiles = null;
return indexedFileEntry;
}
public void addIncludeRef(IndexedFileEntry indexedFile, char[] include) {
addIncludeRef(include, indexedFile.getFileID());
}
public void addIncludeRef(IndexedFileEntry indexedFile, String include) {
addIncludeRef(include.toCharArray(), indexedFile.getFileID());
}
/**
* Adds the references of the include to the tree (reference = number of the file the include belongs to).
*/
protected void addIncludeRef(char[] include, int[] references) {
int size= references.length;
int i= 0;
while (i < size) {
if (references[i] != 0)
addIncludeRef(include, references[i]);
i++;
}
}
/**
* Looks if the include already exists to the tree and adds the fileNum to this include.
* If the include does not exist, it adds it to the tree.
*/
protected void addIncludeRef(char[] include, int fileNum) {
IncludeEntry entry= this.includes.get(include);
if (entry == null) {
entry= new IncludeEntry(include, ++lastId);
entry.addRef(fileNum);
this.includes.add(entry);
this.sortedIncludeEntries= null;
this.footprint += entry.footprint();
} else {
this.footprint += entry.addRef(fileNum);
}
}
/**
* Looks if the word already exists in the index and add the fileNum to this word.
* If the word does not exist, it adds it in the index.
* @param indexFlags
*/
protected void addRef(char[] word, int fileNum, int offset, int offsetLength, int offsetType, int modifiers) {
WordEntry entry= this.words.get(word);
if (entry == null) {
entry= new WordEntry(word);
entry.addRef(fileNum);
entry.addOffset(offset, offsetLength, fileNum, offsetType);
entry.addModifiers(modifiers, fileNum);
this.words.add(entry);
this.sortedWordEntries= null;
this.footprint += entry.footprint();
} else {
this.footprint += entry.addRef(fileNum);
entry.addOffset(offset, offsetLength, fileNum, offsetType);
entry.addModifiers(modifiers, fileNum);
}
}
public void addRef(IndexedFileEntry indexedFile, char[] word, int offset, int offsetLength, int offsetType, int modifiers) {
addRef(word, indexedFile.getFileID(), offset, offsetLength, offsetType, modifiers);
}
public void addRef(IndexedFileEntry indexedFile, String word, int offset, int offsetLength, int offsetType, int modifiers) {
addRef(word.toCharArray(), indexedFile.getFileID(), offset, offsetLength, offsetType, modifiers);
}
public void addRelatives(int fileNumber, String inclusion, String parent) {
addRelatives(fileNumber,inclusion.toCharArray(),(parent != null ) ? parent.toCharArray() : null);
}
protected void addRelatives(int fileNumber, char[] inclusion, char[] parent) {
IncludeEntry childEntry=null;
IncludeEntry parentEntry=null;
if (inclusion != null)
childEntry= this.includes.get(inclusion);
if (parent != null)
parentEntry= this.includes.get(parent);
childEntry.addParent(fileNumber,(parentEntry!=null) ? parentEntry.getID() : -1);
if (parent!=null)
parentEntry.addChild(fileNumber,(childEntry!=null) ? childEntry.getID() : -1);
}
/**
* Returns the footprint of the index.
*/
public long getFootprint() {
return this.footprint;
}
/**
* Returns the indexed files contained in the hashtable of includes.
*/
public IndexedFileEntry[] getIndexedFiles(){
return this.files.asArray();
}
/**
* Returns the indexed file with the given path, or null if such file does not exist.
*/
public IndexedFileEntry getIndexedFile(String path) {
return files.get(path);
}
/**
* Returns the include entries contained in the hashtable of includes.
*/
public IncludeEntry[] getIncludeEntries() {
return this.includes.asArray();
}
/**
* Returns the include entry corresponding to the given include.
*/
protected IncludeEntry getIncludeEntry(char[] include) {
return includes.get(include);
}
public int getNumFiles() {
return files.size();
}
public int getNumWords() {
return words.elementSize;
}
public int getNumIncludes() {
return includes.elementSize;
}
/**
* Returns the words contained in the hashtable of words, sorted by alphabetical order.
*/
public IndexedFileEntry[] getSortedFiles() {
if (this.sortedFiles == null) {
IndexedFileEntry[] indexedFiles= files.asArray();
Util.sort(indexedFiles);
this.sortedFiles= indexedFiles;
}
return this.sortedFiles;
}
/**
* Returns the word entries contained in the hashtable of words, sorted by alphabetical order.
*/
public WordEntry[] getSortedWordEntries() {
if (this.sortedWordEntries == null) {
WordEntry[] words= this.words.asArray();
Util.sort(words);
this.sortedWordEntries= words;
}
return this.sortedWordEntries;
}
/**
* Returns the include entries contained in the hashtable of includeas, sorted by alphabetical order.
*/
public IncludeEntry[] getSortedIncludeEntries() {
if (this.sortedIncludeEntries == null) {
IncludeEntry[] includes= this.includes.asArray();
Util.sort(includes);
this.sortedIncludeEntries= includes;
}
return this.sortedIncludeEntries;
}
/**
* Returns the word entry corresponding to the given word.
*/
public WordEntry getWordEntry(char[] word) {
return words.get(word);
}
/**
* Initialises the fields of the index
*/
public void init() {
includes= new IncludeEntryHashedArray(501);
words= new WordEntryHashedArray(501);
files= new IndexedFileEntryHashedArray(101);
pathVars= new IndexPathVariableEntryHashedArray(101);
footprint= 0;
lastId=0;
sortedWordEntries= null;
sortedFiles= null;
sortedIncludeEntries=null;
}
/**
* Saves the index in the given file.
* Structure of the saved Index :
* - IndexedFiles in sorted order.
* + example:
* "c:/com/a.cpp 1"
* "c:/com/b.cpp 2"
* - References with the words in sorted order
* + example:
* "classDecl/a 1"
* "classDecl/b 2"
* "ref/String 1 2"
*/
public void save(File file) throws IOException {
BlocksIndexOutput output= new BlocksIndexOutput(file);
save(output);
}
/**
* Saves the index in the given IndexOutput.
* Structure of the saved Index :
* - IndexedFiles in sorted order.
* + example:
* "c:/com/a.cpp 1"
* "c:/com/b.cpp 2"
* - References with the words in sorted order
* + example:
* "classDecl/a 1"
* "classDecl/b 2"
* "ref/String 1 2"
*/
protected void save(IndexOutput output) throws IOException {
boolean ok= false;
try {
output.open();
IndexedFileEntry[] indexedFiles= files.asArray();
for (int i= 0, length = indexedFiles.length; i < length; ++i)
output.addFile(indexedFiles[i]); // written out in order BUT not alphabetical
getSortedWordEntries(); // init the slot
for (int i= 0, numWords= sortedWordEntries.length; i < numWords; ++i)
output.addWord(sortedWordEntries[i]);
output.flush();
output.close();
ok= true;
} finally {
if (!ok && output != null)
output.close();
}
}
}

View file

@ -1,240 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.sourcedependency.Node;
/**
* @author bgheorgh
*/
public class IncludeEntry {
protected char[] fFile;
protected int fId;
protected int fNumRefs;
protected int[] fRefs;
//TODO: BOG Consider making these arrays...
protected ArrayList fParent;
protected ArrayList fChild;
protected int fNumParent;
protected int fNumChild;
public IncludeEntry(int id) {
this(CharOperation.NO_CHAR,id);
}
public IncludeEntry(char[] file, int id) {
fFile = file;
fNumRefs= 0;
fRefs= new int[1];
fId=id;
fParent = new ArrayList(5);
fChild = new ArrayList(5);
fNumParent = 0;
fNumChild = 0;
}
/**
* Adds a reference and records the change in footprint.
*/
public int addRef(int fileNum) {
if (fNumRefs > 0 && fRefs[fNumRefs - 1] == fileNum) {
return 0;
}
if (fNumRefs < fRefs.length) {
fRefs[fNumRefs++]= fileNum;
return 0;
}
int newSize= fNumRefs < 4 ? 4 : fNumRefs * 2; // so will start @ 1, grow to 4, 8, 16, 32, 64 etc.
System.arraycopy(fRefs, 0, fRefs= new int[newSize], 0, fNumRefs);
fRefs[fNumRefs++]= fileNum;
return (newSize - fNumRefs + 1) * 4;
}
public void addParent(int fileRef, int parentId){
Node newParent = new Node(fileRef,parentId);
fParent.add(newParent);
fNumParent++;
}
/**
* @param is
*/
public void addRefs(int[] refs) {
int[] newRefs= new int[fNumRefs + refs.length];
int pos1= 0;
int pos2= 0;
int posNew= 0;
int compare;
int r1= 0;
int r2= 0;
while (pos1 < fNumRefs || pos2 < refs.length) {
if (pos1 >= fNumRefs) {
r2= refs[pos2];
compare= -1;
} else if (pos2 >= refs.length) {
compare= 1;
r1= fRefs[pos1];
} else {
r1= fRefs[pos1];
r2= refs[pos2];
compare= r2 - r1;
}
if (compare > 0) {
newRefs[posNew]= r1;
posNew++;
pos1++;
} else {
if (r2 != 0) {
newRefs[posNew]= r2;
posNew++;
}
pos2++;
}
}
fRefs= newRefs;
fNumRefs= posNew;
/*for (int i = 0; i < refs.length; i++)
addRef(refs[i]);
int[] newRefs = new int[fNumRefs];
System.arraycopy(fRefs, 0, newRefs, 0, fNumRefs);
fRefs = newRefs;
Util.sort(fRefs);*/
}
public void addChild(int fileRef, int parentId){
Node newChild = new Node(fileRef,parentId);
fChild.add(newChild);
fNumChild++;
}
/**
* Returns the number of references, e.g. the number of files this word appears in.
*/
public int getNumRefs() {
return fNumRefs;
}
/**
* returns the file number in the i position in the list of references.
*/
public int getRef(int i) {
if (i < fNumRefs) return fRefs[i];
throw new IndexOutOfBoundsException();
}
/**
* Returns the references of the includeEntry (the number of the files it appears in).
*/
public int[] getRefs() {
int[] result= new int[fNumRefs];
System.arraycopy(fRefs, 0, result, 0, fNumRefs);
return result;
}
/**
* returns the word of the includeEntry.
*/
public char[] getFile() {
return fFile;
}
/**
* Changes the references of the wordEntry to match the mapping. For example,<br>
* if the current references are [1 3 4]<br>
* and mapping is [1 2 3 4 5]<br>
* in references 1 becomes mapping[1] = 2, 3->4, and 4->5<br>
* => references = [2 4 5].<br>
*/
public void mapRefs(int[] mappings) {
int position= 0;
for (int i= 0; i < fNumRefs; i++) {
//Take care that the reference is actually within the bounds of the mapping
int map= -1;
if(fRefs[i] >= 0 && fRefs[i] < mappings.length)
map= mappings[fRefs[i]];
if (map != -1 && map != 0)
fRefs[position++]= map;
}
fNumRefs= position;
//to be changed!
System.arraycopy(fRefs, 0, (fRefs= new int[fNumRefs]), 0, fNumRefs);
Util.sort(fRefs);
}
/**
* Clears the includeEntry.
*/
public void reset(char[] word) {
for (int i= fNumRefs; i-- > 0;) {
fRefs[i]= 0;
}
fNumRefs= 0;
fFile= word;
}
public int getID(){
return fId;
}
public String toString() {
StringBuffer tempBuffer = new StringBuffer();
tempBuffer.append("<Name: "); //$NON-NLS-1$
tempBuffer.append(fFile);
tempBuffer.append(", Id: "); //$NON-NLS-1$
tempBuffer.append(fId);
tempBuffer.append(", Refs:{"); //$NON-NLS-1$
for (int i = 0; i < fRefs.length; i++){
if (i > 0) tempBuffer.append(',');
tempBuffer.append(' ');
tempBuffer.append(fRefs[i]);
}
tempBuffer.append("}, Parents:{"); //$NON-NLS-1$
Iterator x = fParent.iterator();
while (x.hasNext())
{
Node tempNode = (Node) x.next();
tempBuffer.append(tempNode.toString());
if (x.hasNext()) {
tempBuffer.append(',');
tempBuffer.append(' ');
}
}
tempBuffer.append("}, Children:{"); //$NON-NLS-1$
Iterator y = fChild.iterator();
while (y.hasNext())
{
Node tempNode = (Node) y.next();
tempBuffer.append(tempNode.toString());
if (y.hasNext()) {
tempBuffer.append(',');
tempBuffer.append(' ');
}
}
tempBuffer.append("} >"); //$NON-NLS-1$
return tempBuffer.toString();
}
/**
* @return
*/
public long footprint() {
//Size of Object + (number of fields * size of Fields) +
//(Size of ArrayListObject + (Number of Nodes * sizeof Node)) + (Size of ArrayObject + (Number of fFile * sizeof char)) +
//(Size of ArrayListObject + (Number of Nodes * sizeof Node)) +
//(Size of ArrayObject + (Number of refs * sizeof int))
return 8 + (8 * 4) +
(8 + fChild.size() * (8 + 2 * 4)) + (8 + fFile.length * 2) +
(8 + fParent.size() * (8 + 2 * 4)) + (8 + fRefs.length * 4);
}
}

View file

@ -1,84 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import org.eclipse.cdt.internal.core.CharOperation;
public final class IncludeEntryHashedArray {
public IncludeEntry elements[];
public int elementSize; // number of elements in the table
public int threshold;
public IncludeEntryHashedArray(int size) {
if (size < 7) size = 7;
this.elements = new IncludeEntry[2 * size + 1];
this.elementSize = 0;
this.threshold = size + 1; // size is the expected number of elements
}
public IncludeEntry add(IncludeEntry entry) {
int length = elements.length;
char[] word = entry.getFile();
int index = CharOperation.hashCode(word) % length;
IncludeEntry current;
while ((current = elements[index]) != null) {
if (CharOperation.equals(current.getFile(), word)) return elements[index] = entry;
if (++index == length) index = 0;
}
elements[index] = entry;
// assumes the threshold is never equal to the size of the table
if (++elementSize > threshold) grow();
return entry;
}
public IncludeEntry[] asArray() {
IncludeEntry[] array = new IncludeEntry[elementSize];
for (int i = 0, j = 0, length = elements.length; i < length; i++) {
IncludeEntry current = elements[i];
if (current != null) array[j++] = current;
}
return array;
}
public IncludeEntry get(char[] word) {
int length = elements.length;
int index = CharOperation.hashCode(word) % length;
IncludeEntry current;
while ((current = elements[index]) != null) {
if (CharOperation.equals(current.getFile(), word)) return current;
if (++index == length) index = 0;
}
return null;
}
private void grow() {
IncludeEntryHashedArray newArray = new IncludeEntryHashedArray(elementSize * 2); // double the number of expected elements
for (int i = 0, length = elements.length; i < length; i++)
if (elements[i] != null)
newArray.add(elements[i]);
this.elements = newArray.elements;
this.elementSize = newArray.elementSize;
this.threshold = newArray.threshold;
}
public String toString() {
String s = ""; //$NON-NLS-1$
IncludeEntry[] entries = asArray();
for (int i = 0, length = entries.length; i < length; i++)
s += entries[i].toString() + "\n"; //$NON-NLS-1$
return s;
}
}

View file

@ -1,825 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.index.ICDTIndexer;
import org.eclipse.cdt.core.index.IIndexDelta;
import org.eclipse.cdt.core.search.ICSearchConstants;
import org.eclipse.cdt.core.search.LimitTo;
import org.eclipse.cdt.core.search.SearchFor;
import org.eclipse.cdt.internal.core.CharOperation;
import org.eclipse.cdt.internal.core.index.IEntryResult;
import org.eclipse.cdt.internal.core.index.IIndex;
import org.eclipse.cdt.internal.core.index.IIndexerRunner;
import org.eclipse.cdt.internal.core.index.IQueryResult;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexOutput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexOutput;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.MergeFactory;
import org.eclipse.cdt.internal.core.index.cindexstorage.io.SimpleIndexInput;
import org.eclipse.cdt.internal.core.index.impl.IndexDelta;
import org.eclipse.cdt.internal.core.index.impl.Int;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
/**
* An Index is used to create an index on the disk, and to make queries. It uses a set of
* indexers and a mergeFactory. The index fills an inMemoryIndex up
* to it reaches a certain size, and then merges it with a main index on the disk.
* <br> <br>
* The changes are only taken into account by the queries after a merge.
*/
public class Index implements IIndex, ICIndexStorageConstants, ICSearchConstants {
/**
* Maximum size of the index in memory.
*/
public static final int MAX_FOOTPRINT= 10000000;
/**
* Index in memory, who is merged with mainIndex each times it
* reaches a certain size.
*/
protected InMemoryIndex addsIndex;
protected IndexInput addsIndexInput;
/**
* State of the indexGenerator: addsIndex empty <=> MERGED, or
* addsIndex not empty <=> CAN_MERGE
*/
protected int state;
/**
* Files removed form the addsIndex.
*/
protected Map removedInAdds;
/**
* Files removed form the oldIndex.
*/
protected Map removedInOld;
protected static final int CAN_MERGE= 0;
protected static final int MERGED= 1;
private File indexFile;
private ICDTIndexer indexer = null;
/**
* String representation of this index.
*/
public String toString;
public Index(String indexName, String toString, boolean reuseExistingFile, ICDTIndexer indexer) throws IOException {
super();
state= MERGED;
indexFile= new File(indexName);
this.toString = toString;
this.indexer = indexer;
initialize(reuseExistingFile);
}
/**
* Indexes the given document, using the appropriate indexer registered in the indexerRegistry.
* If the document already exists in the index, it overrides the previous one. The changes will be
* taken into account after a merge.
*/
public void add(IFile file, IIndexerRunner indexer) throws IOException {
if (timeToMerge()) {
merge();
}
IndexedFileEntry indexedFile= addsIndex.getIndexedFile(file.getFullPath().toString());
if (indexedFile != null /*&& removedInAdds.get(document.getName()) == null*/
)
remove(indexedFile, MergeFactory.ADDS_INDEX);
IndexerOutput output= new IndexerOutput(addsIndex);
indexer.index(file, output);
state= CAN_MERGE;
}
/**
* Returns true if the index in memory is not empty, so
* merge() can be called to fill the mainIndex with the files and words
* contained in the addsIndex.
*/
protected boolean canMerge() {
return state == CAN_MERGE;
}
/**
* Initialises the indexGenerator.
*/
public void empty() throws IOException {
if (indexFile.exists()){
indexFile.delete();
//initialisation of mainIndex
InMemoryIndex mainIndex= new InMemoryIndex();
IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile);
if (!indexFile.exists())
mainIndex.save(mainIndexOutput);
}
//initialisation of addsIndex
addsIndex= new InMemoryIndex();
addsIndexInput= new SimpleIndexInput(addsIndex);
//vectors who keep track of the removed Files
removedInAdds= new HashMap(11);
removedInOld= new HashMap(11);
}
/**
* @see IIndex#getIndexFile
*/
public File getIndexFile() {
return indexFile;
}
/**
* @see IIndex#getNumDocuments
*/
public int getNumDocuments() throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
return input.getNumFiles();
} finally {
input.close();
}
}
/**
* @see IIndex#getNumWords
*/
public int getNumWords() throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
return input.getNumWords();
} finally {
input.close();
}
}
/**
* @see IIndex#getNumWords
*/
public int getNumIncludes() throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
return input.getNumIncludes();
} finally {
input.close();
}
}
/**
* Returns the path corresponding to a given document number
*/
public String getPath(int documentNumber) throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
IndexedFileEntry file = input.getIndexedFile(documentNumber);
if (file == null) return null;
return file.getPath();
} finally {
input.close();
}
}
/**
* Returns the path list
*/
public String [] getDocumentList() throws IOException {
IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
int num = input.getNumFiles();
String [] result = new String[num+1];
for(int i = 1; i < num+1; i++) {
//i+1 since reference encoding starts at 1
IndexedFileEntry file = input.getIndexedFile(i);
if (file != null)
result[i] = file.getPath();
else
result[i] = null;
}
return result;
} finally {
input.close();
}
}
/**
* see IIndex.hasChanged
*/
public boolean hasChanged() {
return canMerge();
}
/**
* Initialises the indexGenerator.
*/
public void initialize(boolean reuseExistingFile) throws IOException {
//initialisation of addsIndex
addsIndex= new InMemoryIndex();
addsIndexInput= new SimpleIndexInput(addsIndex);
//vectors who keep track of the removed Files
removedInAdds= new HashMap(11);
removedInOld= new HashMap(11);
// check whether existing index file can be read
if (reuseExistingFile && indexFile.exists()) {
IndexInput mainIndexInput= new BlocksIndexInput(indexFile);
try {
mainIndexInput.open();
} catch(IOException e) {
BlocksIndexInput input = (BlocksIndexInput)mainIndexInput;
try {
input.setOpened(true);
input.close();
} finally {
input.setOpened(false);
}
indexFile.delete();
mainIndexInput = null;
throw e;
}
mainIndexInput.close();
} else {
InMemoryIndex mainIndex= new InMemoryIndex();
IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile);
mainIndex.save(mainIndexOutput);
}
}
/**
* Merges the in memory index and the index on the disk, and saves the results on the disk.
*/
protected void merge() throws IOException {
//initialisation of tempIndex
File tempFile= new File(indexFile.getAbsolutePath() + "TempVA"); //$NON-NLS-1$
IndexInput mainIndexInput= new BlocksIndexInput(indexFile);
BlocksIndexOutput tempIndexOutput= new BlocksIndexOutput(tempFile);
try {
//invoke a mergeFactory
new MergeFactory(
mainIndexInput,
addsIndexInput,
tempIndexOutput,
removedInOld,
removedInAdds).merge();
//rename the file created to become the main index
File mainIndexFile= (File) mainIndexInput.getSource();
File tempIndexFile= (File) tempIndexOutput.getDestination();
boolean deleted = mainIndexFile.delete();
int counter=0;
while (!deleted && counter<5){
try {
Thread.sleep(50);
} catch (InterruptedException e) {}
counter++;
deleted=mainIndexFile.delete();
}
tempIndexFile.renameTo(mainIndexFile);
} finally {
//initialise remove vectors and addsindex, and change the state
removedInAdds.clear();
removedInOld.clear();
addsIndex.init();
addsIndexInput= new SimpleIndexInput(addsIndex);
state= MERGED;
//flush the CDT log
CCorePlugin.getDefault().cdtLog.flushLog();
//Send out notification to listeners;
IndexDelta indexDelta = new IndexDelta(null,null,IIndexDelta.MERGE_DELTA);
indexer.notifyListeners(indexDelta);
}
}
public IEntryResult[] queryEntries(char[] prefix) throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryEntriesPrefixedBy(prefix);
} finally {
input.close();
}
}
/**
* @see IIndex#queryInDocumentNames
*/
public IQueryResult[] queryInDocumentNames(String word) throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryInDocumentNames(word);
} finally {
input.close();
}
}
/**
* @see IIndex#queryPrefix
*/
public IQueryResult[] queryPrefix(char[] prefix) throws IOException {
//save();
IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryFilesReferringToPrefix(prefix);
} finally {
input.close();
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.sourcedependency.IDependencyTree#getFileDepencies(int)
*/
public String[] getFileDependencies(IPath filePath) throws IOException {
// List tempFileReturn = new ArrayList();
//
// IndexedFile indexFile = addsIndex.getIndexedFile(filePath.toString());
//
// if (indexFile == null)
// return new String[0];
//
// int fileNum = indexFile.getFileNumber();
// IncludeEntry[] tempEntries = addsIndex.getIncludeEntries();
// for (int i=0; i<tempEntries.length; i++)
// {
// int[] fileRefs = tempEntries[i].getRefs();
// for (int j=0; j<fileRefs.length; j++)
// {
// if (fileRefs[j] == fileNum)
// {
// char[] tempFile = tempEntries[i].getFile();
// StringBuffer tempString = new StringBuffer();
// tempString.append(tempFile);
// tempFileReturn.add(tempString.toString());
// break;
// }
// }
// }
// return (String []) tempFileReturn.toArray(new String[tempFileReturn.size()]);
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.index.IIndex#getFileDependencies(org.eclipse.core.resources.IFile)
*/
public String[] getFileDependencies(IFile file) throws IOException {
IndexInput input= new BlocksIndexInput(indexFile);
int fileNum=0;
List tempFileReturn = new ArrayList();
try {
input.open();
IndexedFileEntry inFile = input.getIndexedFile(file.getFullPath().toString());
fileNum =inFile.getFileID();
IncludeEntry[] tempEntries = input.queryIncludeEntries(fileNum);
for (int i=0; i<tempEntries.length; i++)
{
char[] tempFile = tempEntries[i].getFile();
StringBuffer tempString = new StringBuffer();
tempString.append(tempFile);
tempFileReturn.add(tempString.toString());
}
}
finally{input.close();}
return (String []) tempFileReturn.toArray(new String[tempFileReturn.size()]);
}
/**
* @see IIndex#remove
*/
public void remove(String documentName) throws IOException {
IndexedFileEntry file= addsIndex.getIndexedFile(documentName);
if (file != null) {
//the file is in the adds Index, we remove it from this one
Int lastRemoved= (Int) removedInAdds.get(documentName);
if (lastRemoved != null) {
int fileNum= file.getFileID();
if (lastRemoved.value < fileNum)
lastRemoved.value= fileNum;
} else
removedInAdds.put(documentName, new Int(file.getFileID()));
} else {
//we remove the file from the old index
removedInOld.put(documentName, new Int(1));
}
state= CAN_MERGE;
}
/**
* Removes the given document from the given index (MergeFactory.ADDS_INDEX for the
* in memory index, MergeFactory.OLD_INDEX for the index on the disk).
*/
protected void remove(IndexedFileEntry file, int index) throws IOException {
String name= file.getPath();
if (index == MergeFactory.ADDS_INDEX) {
Int lastRemoved= (Int) removedInAdds.get(name);
if (lastRemoved != null) {
if (lastRemoved.value < file.getFileID())
lastRemoved.value= file.getFileID();
} else
removedInAdds.put(name, new Int(file.getFileID()));
} else if (index == MergeFactory.OLD_INDEX)
removedInOld.put(name, new Int(1));
else
throw new Error();
state= CAN_MERGE;
}
/**
* @see IIndex#save
*/
public void save() throws IOException {
if (canMerge())
merge();
}
/**
* Returns true if the in memory index reaches a critical size,
* to merge it with the index on the disk.
*/
protected boolean timeToMerge() {
return (addsIndex.getFootprint() >= MAX_FOOTPRINT);
}
public String toString() {
String str = this.toString;
if (str == null)
str = super.toString();
str += "(length: " + getIndexFile().length() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
return str;
}
public org.eclipse.cdt.core.index.ICDTIndexer getIndexer(){
return (org.eclipse.cdt.core.index.ICDTIndexer) indexer;
}
public IEntryResult[] queryEntries(char[] prefix, char optionalType, char[] name, char[][] containingTypes, int matchMode, boolean isCaseSensitive) throws IOException {
return queryEntries(Index.bestPrefix(prefix, optionalType, name, containingTypes, matchMode, isCaseSensitive));
}
public static final char[] bestTypePrefix( SearchFor searchFor, LimitTo limitTo, char[] typeName, char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.TYPE, ANY, DECLARATION);
} else if (limitTo == DEFINITIONS){
prefix = encodeEntry(IIndex.TYPE, ANY, DEFINITION);
} else if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.TYPE, ANY, REFERENCE);
} else {
return encodeEntry(IIndex.TYPE, ANY, ANY);
}
char classType = 0;
if( searchFor == ICSearchConstants.CLASS ){
classType = typeConstants[IIndex.TYPE_CLASS];
} else if ( searchFor == ICSearchConstants.STRUCT ){
classType = typeConstants[IIndex.TYPE_STRUCT];
} else if ( searchFor == ICSearchConstants.UNION ){
classType = typeConstants[IIndex.TYPE_UNION];
} else if ( searchFor == ICSearchConstants.ENUM ){
classType = typeConstants[IIndex.TYPE_ENUM];
} else if ( searchFor == ICSearchConstants.TYPEDEF ){
classType = typeConstants[IIndex.TYPE_TYPEDEF];
} else if ( searchFor == ICSearchConstants.DERIVED){
classType = typeConstants[IIndex.TYPE_DERIVED];
} else if ( searchFor == ICSearchConstants.FRIEND){
classType = typeConstants[IIndex.TYPE_FRIEND];
} else {
//could be TYPE or CLASS_STRUCT, best we can do for these is the prefix
return prefix;
}
return bestPrefix( prefix, classType, typeName, containingTypes, matchMode, isCaseSensitive );
}
public static final char[] bestNamespacePrefix(LimitTo limitTo, char[] namespaceName, char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.NAMESPACE, ANY, REFERENCE);
} else if ( limitTo == DEFINITIONS ) {
prefix = encodeEntry(IIndex.NAMESPACE, ANY, DEFINITION);
} else {
return encodeEntry(IIndex.NAMESPACE, ANY, ANY);
}
return bestPrefix( prefix, (char) 0, namespaceName, containingTypes, matchMode, isCaseSensitive );
}
public static final char[] bestVariablePrefix( LimitTo limitTo, char[] varName, char[][] containingTypes, int matchMode, boolean isCaseSenstive ){
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.VAR, ANY, REFERENCE);
} else if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.VAR, ANY, DECLARATION);
} else if( limitTo == DEFINITIONS ){
prefix = encodeEntry(IIndex.VAR, ANY, DEFINITION);
} else {
return encodeEntry(IIndex.VAR, ANY, ANY);
}
return bestPrefix( prefix, (char)0, varName, containingTypes, matchMode, isCaseSenstive );
}
public static final char[] bestFieldPrefix( LimitTo limitTo, char[] fieldName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.FIELD, ANY, REFERENCE);
} else if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.FIELD, ANY, DECLARATION);
} else if( limitTo == DEFINITIONS ){
prefix = encodeEntry(IIndex.FIELD, ANY, DEFINITION);
} else {
return encodeEntry(IIndex.FIELD, ANY, ANY);
}
return bestPrefix( prefix, (char)0, fieldName, containingTypes, matchMode, isCaseSensitive );
}
public static final char[] bestEnumeratorPrefix( LimitTo limitTo, char[] enumeratorName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.ENUMTOR, ANY, REFERENCE);
} else if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.ENUMTOR, ANY, DECLARATION);
} else if ( limitTo == DEFINITIONS ) {
prefix = encodeEntry(IIndex.ENUMTOR, ANY, DEFINITION);
} else if (limitTo == ALL_OCCURRENCES){
return encodeEntry(IIndex.ENUMTOR, ANY, ANY);
}
return bestPrefix( prefix, (char)0, enumeratorName, containingTypes, matchMode, isCaseSensitive );
}
public static final char[] bestMethodPrefix( LimitTo limitTo, char[] methodName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.METHOD, ANY, REFERENCE);
} else if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.METHOD, ANY, DECLARATION);
} else if( limitTo == DEFINITIONS ){
return encodeEntry(IIndex.METHOD, ANY, DEFINITION);
} else {
return encodeEntry(IIndex.METHOD, ANY, ANY);
}
return bestPrefix( prefix, (char)0, methodName, containingTypes, matchMode, isCaseSensitive );
}
public static final char[] bestFunctionPrefix( LimitTo limitTo, char[] functionName, int matchMode, boolean isCaseSensitive) {
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.FUNCTION, ANY, REFERENCE);
} else if( limitTo == DECLARATIONS ){
prefix = encodeEntry(IIndex.FUNCTION, ANY, DECLARATION);
} else if ( limitTo == DEFINITIONS ){
return encodeEntry(IIndex.FUNCTION, ANY, DEFINITION);
} else {
return encodeEntry(IIndex.FUNCTION, ANY, ANY);
}
return bestPrefix( prefix, (char)0, functionName, null, matchMode, isCaseSensitive );
}
public static final char[] bestPrefix( char [] prefix, char optionalType, char[] name, char[][] containingTypes, int matchMode, boolean isCaseSensitive) {
char[] result = null;
int pos = 0;
int wildPos, starPos = -1, questionPos;
//length of prefix + separator
int length = prefix.length;
//add length for optional type + another separator
if( optionalType != 0 )
length += 2;
if (!isCaseSensitive){
//index is case sensitive, thus in case attempting case insensitive search, cannot consider
//type name.
name = null;
} else if( matchMode == PATTERN_MATCH && name != null ){
int start = 0;
char [] temp = new char [ name.length ];
boolean isEscaped = false;
int tmpIdx = 0;
for( int i = 0; i < name.length; i++ ){
if( name[i] == '\\' ){
if( !isEscaped ){
isEscaped = true;
continue;
}
isEscaped = false;
} else if( name[i] == '*' && !isEscaped ){
starPos = i;
break;
}
temp[ tmpIdx++ ] = name[i];
}
name = new char [ tmpIdx ];
System.arraycopy( temp, 0, name, 0, tmpIdx );
//starPos = CharOperation.indexOf( '*', name );
questionPos = CharOperation.indexOf( '?', name );
if( starPos >= 0 ){
if( questionPos >= 0 )
wildPos = ( starPos < questionPos ) ? starPos : questionPos;
else
wildPos = starPos;
} else {
wildPos = questionPos;
}
switch( wildPos ){
case -1 : break;
case 0 : name = null; break;
default : name = CharOperation.subarray( name, 0, wildPos ); break;
}
}
//add length for name
if( name != null ){
length += name.length;
} else {
//name is null, don't even consider qualifications.
result = new char [ length ];
System.arraycopy( prefix, 0, result, 0, pos = prefix.length );
if( optionalType != 0){
result[ pos++ ] = optionalType;
result[ pos++ ] = SEPARATOR;
}
return result;
}
//add the total length of the qualifiers
//we don't want to mess with the contents of this array (treat it as constant)
//so check for wild cards later.
if( containingTypes != null ){
for( int i = 0; i < containingTypes.length; i++ ){
if( containingTypes[i].length > 0 ){
length += containingTypes[ i ].length;
length++; //separator
}
}
}
//because we haven't checked qualifier wild cards yet, this array might turn out
//to be too long. So fill a temp array, then check the length after
char [] temp = new char [ length ];
System.arraycopy( prefix, 0, temp, 0, pos = prefix.length );
if( optionalType != 0 ){
temp[ pos++ ] = optionalType;
temp[ pos++ ] = SEPARATOR;
}
System.arraycopy( name, 0, temp, pos, name.length );
pos += name.length;
if( containingTypes != null ){
for( int i = containingTypes.length - 1; i >= 0; i-- ){
if( matchMode == PATTERN_MATCH ){
starPos = CharOperation.indexOf( '*', containingTypes[i] );
questionPos = CharOperation.indexOf( '?', containingTypes[i] );
if( starPos >= 0 ){
if( questionPos >= 0 )
wildPos = ( starPos < questionPos ) ? starPos : questionPos;
else
wildPos = starPos;
} else {
wildPos = questionPos;
}
if( wildPos >= 0 ){
temp[ pos++ ] = SEPARATOR;
System.arraycopy( containingTypes[i], 0, temp, pos, wildPos );
pos += starPos;
break;
}
}
if( containingTypes[i].length > 0 ){
temp[ pos++ ] = SEPARATOR;
System.arraycopy( containingTypes[i], 0, temp, pos, containingTypes[i].length );
pos += containingTypes[i].length;
}
}
}
if( pos < length ){
result = new char[ pos ];
System.arraycopy( temp, 0, result, 0, pos );
} else {
result = temp;
}
return result;
}
/**
* @param _limitTo
* @param simpleName
* @param _matchMode
* @param _caseSensitive
* @return
*/
public static final char[] bestMacroPrefix( LimitTo limitTo, char[] macroName, int matchMode, boolean isCaseSenstive ){
//since we only index macro declarations we already know the prefix
char [] prefix = null;
if( limitTo == DECLARATIONS ){
prefix = Index.encodeEntry(IIndex.MACRO, IIndex.ANY, IIndex.DECLARATION);
} else {
return null;
}
return bestPrefix( prefix, (char)0, macroName, null, matchMode, isCaseSenstive );
}
/**
* @param _limitTo
* @param simpleName
* @param _matchMode
* @param _caseSensitive
* @return
*/
public static final char[] bestIncludePrefix( LimitTo limitTo, char[] incName, int matchMode, boolean isCaseSenstive ){
//since we only index macro declarations we already know the prefix
char [] prefix = null;
if( limitTo == REFERENCES ){
prefix = encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE);
} else {
return null;
}
return bestPrefix( prefix, (char)0, incName, null, matchMode, isCaseSenstive );
}
public static String getDescriptionOf (int meta_kind, int kind, int ref) {
StringBuffer buff = new StringBuffer();
buff.append(encodings[meta_kind]);
buff.append(encodingTypes[ref]);
if(kind != 0) {
buff.append(typeConstants[kind]);
buff.append(SEPARATOR);
}
return buff.toString();
}
public static char [] encodeEntry (int meta_kind, int kind, int ref, String name) {
// if( kind == ANY && ref == ANY )
// return encodings[meta_kind];
StringBuffer buff = new StringBuffer();
buff.append(encodings[meta_kind]);
buff.append(encodingTypes[ref]);
if(kind != 0) {
buff.append(typeConstants[kind]);
buff.append( SEPARATOR );
}
buff.append ( name );
return buff.toString().toCharArray();
}
public static char [] encodeEntry (int meta_kind, int kind, int ref) {
StringBuffer buff = new StringBuffer();
buff.append(encodings[meta_kind]);
buff.append(encodingTypes[ref]);
if(kind != 0)
buff.append(typeConstants[kind]);
return buff.toString().toCharArray();
}
public IEntryResult[] getEntries(int meta_kind, int kind, int ref, String name) throws IOException {
return queryEntries(encodeEntry(meta_kind, kind, ref, name));
}
public IEntryResult[] getEntries(int meta_kind, int kind, int ref) throws IOException {
return queryEntries(encodeEntry(meta_kind, kind, ref));
}
public IQueryResult[] getPrefix(int meta_kind, int kind, int ref, String name) throws IOException {
return queryPrefix(encodeEntry(meta_kind, kind, ref, name));
}
public IQueryResult[] getPrefix(int meta_kind, int kind, int ref) throws IOException {
return queryPrefix(encodeEntry(meta_kind, kind, ref));
}
}

View file

@ -1,21 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
public class IndexEntryNotSupportedException extends Exception {
public IndexEntryNotSupportedException(String string) {
super(string);
}
private static final long serialVersionUID = 3257002138168211513L;
}

View file

@ -1,70 +0,0 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.index.cindexstorage;
/**
* @author Bogdan Gheorghe
*/
public class IndexPathVariableEntry {
//All indexes will reserve 1 in the PathVariable block to represent
//the workspace location
public static final int WORKSPACE_ID = 1;
private String pathVariableName;
private String pathVariablePath;
private int pathVarID;
public IndexPathVariableEntry(String pathVarName, String pathVarPath, int id){
this.pathVariableName = pathVarName;
this.pathVariablePath = pathVarPath;
this.pathVarID = id;
}
/**
* @return Returns the id.
*/
public int getId() {
return pathVarID;
}
/**
* @param id The id to set.
*/
public void setId(int id) {
this.pathVarID = id;
}
/**
* @return Returns the pathVariableName.
*/
public String getPathVariableName() {
return pathVariableName;
}
/**
* @return Returns the pathVariablePath.
*/
public String getPathVariablePath() {
return pathVariablePath;
}
/**
* Returns the size of the indexedFile.
*/
public int footprint() {
//object+ 3 slots + size of the string (Object size + (4 fields in String class)
//+ 8 for char array in string + (2 for each char * number of chars in string)) + {another String}
return 8 + (3 * 4) + (8 + (4 * 4) + 8 + (pathVariableName.length() * 2)) + (8 + (4 * 4) + 8 + (pathVariablePath.length() * 2));
}
public String toString() {
return "IndexPathVariableEntry(" + pathVarID + ": " + pathVariableName + " + " + pathVariablePath + ")"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
}
}

Some files were not shown because too many files have changed in this diff Show more