676
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java
public String getJavadocContents(IProgressMonitor monitor, String defaultEncoding) throws JavaModelException {
return null;
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public static IJavaSearchScope createHierarchyScope(IType type) throws JavaModelException {
return createHierarchyScope(type, DefaultWorkingCopyOwner.PRIMARY);
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public static IJavaSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaModelException {
return new HierarchyScope(type, owner);
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public static IJavaSearchScope createStrictHierarchyScope(IJavaProject project, IType type, boolean onlySubtypes, boolean includeFocusType, WorkingCopyOwner owner) throws JavaModelException {
return new HierarchyScope(project, type, owner, onlySubtypes, true, includeFocusType);
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchAllConstructorDeclarations(
final char[] packageName,
final char[] typeName,
final int typeMatchRule,
IJavaSearchScope scope,
final IRestrictedAccessConstructorRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
// Validate match rule first
final int validatedTypeMatchRule = SearchPattern.validateMatchRule(typeName == null ? null : new String (typeName), typeMatchRule);
final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[])
// Debug
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
Util.verbose(" - package name: "+(packageName==null?"null":new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - type name: "+(typeName==null?"null":new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - type match rule: "+getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
if (validatedTypeMatchRule != typeMatchRule) {
Util.verbose(" - validated type match rule: "+getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
}
Util.verbose(" - scope: "+scope); //$NON-NLS-1$
}
if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results
// Create pattern
IndexManager indexManager = JavaModelManager.getIndexManager();
final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(
packageName,
typeName,
validatedTypeMatchRule);
// Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
final HashSet workingCopyPaths = new HashSet();
String workingCopyPath = null;
ICompilationUnit[] copies = getWorkingCopies();
final int copiesLength = copies == null ? 0 : copies.length;
if (copies != null) {
if (copiesLength == 1) {
workingCopyPath = copies[0].getPath().toString();
} else {
for (int i = 0; i < copiesLength; i++) {
ICompilationUnit workingCopy = copies[i];
workingCopyPaths.add(workingCopy.getPath().toString());
}
}
}
final String singleWkcpPath = workingCopyPath;
// Index requestor
IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
// Filter unexpected types
ConstructorDeclarationPattern record = (ConstructorDeclarationPattern)indexRecord;
if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) {
return true; // filter out member classes
}
if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) {
return true; // filter out local and anonymous classes
}
switch (copiesLength) {
case 0:
break;
case 1:
if (singleWkcpPath.equals(documentPath)) {
return true; // filter out *the* working copy
}
break;
default:
if (workingCopyPaths.contains(documentPath)) {
return true; // filter out working copies
}
break;
}
// Accept document path
AccessRestriction accessRestriction = null;
if (access != null) {
// Compute document relative path
int pkgLength = (record.declaringPackageName==null || record.declaringPackageName.length==0) ? 0 : record.declaringPackageName.length+1;
int nameLength = record.declaringSimpleName==null ? 0 : record.declaringSimpleName.length;
char[] path = new char[pkgLength+nameLength];
int pos = 0;
if (pkgLength > 0) {
System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength-1);
CharOperation.replace(path, '.', '/');
path[pkgLength-1] = '/';
pos += pkgLength;
}
if (nameLength > 0) {
System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength);
pos += nameLength;
}
// Update access restriction if path is not empty
if (pos > 0) {
accessRestriction = access.getViolatedRestriction(path);
}
}
nameRequestor.acceptConstructor(
record.modifiers,
record.declaringSimpleName,
record.parameterCount,
record.signature,
record.parameterTypes,
record.parameterNames,
record.declaringTypeModifiers,
record.declaringPackageName,
record.extraFlags,
documentPath,
accessRestriction);
return true;
}
};
try {
if (progressMonitor != null) {
progressMonitor.beginTask(Messages.engine_searching, 1000);
}
// add type names from indexes
indexManager.performConcurrentJob(
new PatternSearchJob(
pattern,
getDefaultSearchParticipant(), // Java search only
scope,
searchRequestor),
waitingPolicy,
progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000-copiesLength));
// add type names from working copies
if (copies != null) {
for (int i = 0; i < copiesLength; i++) {
final ICompilationUnit workingCopy = copies[i];
if (scope instanceof HierarchyScope) {
if (!((HierarchyScope)scope).encloses(workingCopy, progressMonitor)) continue;
} else {
if (!scope.encloses(workingCopy)) continue;
}
final String path = workingCopy.getPath().toString();
if (workingCopy.isConsistent()) {
IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray();
IType[] allTypes = workingCopy.getAllTypes();
for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
IType type = allTypes[j];
char[] simpleName = type.getElementName().toCharArray();
if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) {
int extraFlags = ExtraFlags.getExtraFlags(type);
boolean hasConstructor = false;
IMethod[] methods = type.getMethods();
for (int k = 0; k < methods.length; k++) {
IMethod method = methods[k];
if (method.isConstructor()) {
hasConstructor = true;
String[] stringParameterNames = method.getParameterNames();
String[] stringParameterTypes = method.getParameterTypes();
int length = stringParameterNames.length;
char[][] parameterNames = new char[length][];
char[][] parameterTypes = new char[length][];
for (int l = 0; l < length; l++) {
parameterNames[l] = stringParameterNames[l].toCharArray();
parameterTypes[l] = Signature.toCharArray(Signature.getTypeErasure(stringParameterTypes[l]).toCharArray());
}
nameRequestor.acceptConstructor(
method.getFlags(),
simpleName,
parameterNames.length,
null,// signature is not used for source type
parameterTypes,
parameterNames,
type.getFlags(),
packageDeclaration,
extraFlags,
path,
null);
}
}
if (!hasConstructor) {
nameRequestor.acceptConstructor(
Flags.AccPublic,
simpleName,
-1,
null, // signature is not used for source type
CharOperation.NO_CHAR_CHAR,
CharOperation.NO_CHAR_CHAR,
type.getFlags(),
packageDeclaration,
extraFlags,
path,
null);
}
}
}
} else {
Parser basicParser = getParser();
org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit);
CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
if (parsedUnit != null) {
final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
class AllConstructorDeclarationsVisitor extends ASTVisitor {
private TypeDeclaration[] declaringTypes = new TypeDeclaration[0];
private int declaringTypesPtr = -1;
private void endVisit(TypeDeclaration typeDeclaration) {
if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) {
if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) {
nameRequestor.acceptConstructor(
Flags.AccPublic,
typeName,
-1,
null, // signature is not used for source type
CharOperation.NO_CHAR_CHAR,
CharOperation.NO_CHAR_CHAR,
typeDeclaration.modifiers,
packageDeclaration,
ExtraFlags.getExtraFlags(typeDeclaration),
path,
null);
}
}
this.declaringTypes[this.declaringTypesPtr] = null;
this.declaringTypesPtr--;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
endVisit(typeDeclaration);
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
endVisit(memberTypeDeclaration);
}
private boolean hasConstructor(TypeDeclaration typeDeclaration) {
AbstractMethodDeclaration[] methods = typeDeclaration.methods;
int length = methods == null ? 0 : methods.length;
for (int j = 0; j < length; j++) {
if (methods[j].isConstructor()) {
return true;
}
}
return false;
}
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) {
TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr];
if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) {
Argument[] arguments = constructorDeclaration.arguments;
int length = arguments == null ? 0 : arguments.length;
char[][] parameterNames = new char[length][];
char[][] parameterTypes = new char[length][];
for (int l = 0; l < length; l++) {
Argument argument = arguments[l];
parameterNames[l] = argument.name;
if (argument.type instanceof SingleTypeReference) {
parameterTypes[l] = ((SingleTypeReference)argument.type).token;
} else {
parameterTypes[l] = CharOperation.concatWith(((QualifiedTypeReference)argument.type).tokens, '.');
}
}
TypeDeclaration enclosing = typeDeclaration.enclosingType;
char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
while (enclosing != null) {
enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames);
if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
enclosing = enclosing.enclosingType;
} else {
enclosing = null;
}
}
nameRequestor.acceptConstructor(
constructorDeclaration.modifiers,
typeName,
parameterNames.length,
null, // signature is not used for source type
parameterTypes,
parameterNames,
typeDeclaration.modifiers,
packageDeclaration,
ExtraFlags.getExtraFlags(typeDeclaration),
path,
null);
}
return false; // no need to find constructors from local/anonymous type
}
public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
return false;
}
private boolean visit(TypeDeclaration typeDeclaration) {
if(this.declaringTypes.length <= ++this.declaringTypesPtr) {
int length = this.declaringTypesPtr;
System.arraycopy(this.declaringTypes, 0, this.declaringTypes = new TypeDeclaration[length * 2 + 1], 0, length);
}
this.declaringTypes[this.declaringTypesPtr] = typeDeclaration;
return true;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) {
return visit(typeDeclaration);
}
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) {
return visit(memberTypeDeclaration);
}
}
parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), parsedUnit.scope);
}
}
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) throw new OperationCanceledException();
progressMonitor.worked(1);
}
}
}
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchAllSecondaryTypeNames(
IPackageFragmentRoot[] sourceFolders,
final IRestrictedAccessTypeRequestor nameRequestor,
boolean waitForIndexes,
IProgressMonitor progressMonitor) throws JavaModelException {
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchAllSecondaryTypeNames(IPackageFragmentRoot[], IRestrictedAccessTypeRequestor, boolean, IProgressMonitor)"); //$NON-NLS-1$
StringBuffer buffer = new StringBuffer(" - source folders: "); //$NON-NLS-1$
int length = sourceFolders.length;
for (int i=0; i<length; i++) {
if (i==0) {
buffer.append('[');
} else {
buffer.append(',');
}
buffer.append(sourceFolders[i].getElementName());
}
buffer.append("]\n - waitForIndexes: "); //$NON-NLS-1$
buffer.append(waitForIndexes);
Util.verbose(buffer.toString());
}
IndexManager indexManager = JavaModelManager.getIndexManager();
final TypeDeclarationPattern pattern = new SecondaryTypeDeclarationPattern();
// Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
final HashSet workingCopyPaths = new HashSet();
String workingCopyPath = null;
ICompilationUnit[] copies = getWorkingCopies();
final int copiesLength = copies == null ? 0 : copies.length;
if (copies != null) {
if (copiesLength == 1) {
workingCopyPath = copies[0].getPath().toString();
} else {
for (int i = 0; i < copiesLength; i++) {
ICompilationUnit workingCopy = copies[i];
workingCopyPaths.add(workingCopy.getPath().toString());
}
}
}
final String singleWkcpPath = workingCopyPath;
// Index requestor
IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
// Filter unexpected types
TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord;
if (!record.secondary) {
return true; // filter maint types
}
if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
return true; // filter out local and anonymous classes
}
switch (copiesLength) {
case 0:
break;
case 1:
if (singleWkcpPath.equals(documentPath)) {
return true; // fliter out *the* working copy
}
break;
default:
if (workingCopyPaths.contains(documentPath)) {
return true; // filter out working copies
}
break;
}
// Accept document path
AccessRestriction accessRestriction = null;
if (access != null) {
// Compute document relative path
int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1;
int nameLength = record.simpleName==null ? 0 : record.simpleName.length;
char[] path = new char[pkgLength+nameLength];
int pos = 0;
if (pkgLength > 0) {
System.arraycopy(record.pkg, 0, path, pos, pkgLength-1);
CharOperation.replace(path, '.', '/');
path[pkgLength-1] = '/';
pos += pkgLength;
}
if (nameLength > 0) {
System.arraycopy(record.simpleName, 0, path, pos, nameLength);
pos += nameLength;
}
// Update access restriction if path is not empty
if (pos > 0) {
accessRestriction = access.getViolatedRestriction(path);
}
}
nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
return true;
}
};
// add type names from indexes
try {
if (progressMonitor != null) {
progressMonitor.beginTask(Messages.engine_searching, 100);
}
indexManager.performConcurrentJob(
new PatternSearchJob(
pattern,
getDefaultSearchParticipant(), // Java search only
createJavaSearchScope(sourceFolders),
searchRequestor),
waitForIndexes
? IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH
: IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH,
progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));
} catch (OperationCanceledException oce) {
// do nothing
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchAllTypeNames(
final char[] packageName,
final int packageMatchRule,
final char[] typeName,
final int typeMatchRule,
int searchFor,
IJavaSearchScope scope,
final IRestrictedAccessTypeRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
// Validate match rule first
final int validatedTypeMatchRule = SearchPattern.validateMatchRule(typeName == null ? null : new String (typeName), typeMatchRule);
// Debug
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
Util.verbose(" - package name: "+(packageName==null?"null":new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - package match rule: "+getMatchRuleString(packageMatchRule)); //$NON-NLS-1$
Util.verbose(" - type name: "+(typeName==null?"null":new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - type match rule: "+getMatchRuleString(typeMatchRule)); //$NON-NLS-1$
if (validatedTypeMatchRule != typeMatchRule) {
Util.verbose(" - validated type match rule: "+getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$
}
Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$
Util.verbose(" - scope: "+scope); //$NON-NLS-1$
}
if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results
// Create pattern
IndexManager indexManager = JavaModelManager.getIndexManager();
final char typeSuffix;
switch(searchFor){
case IJavaSearchConstants.CLASS :
typeSuffix = IIndexConstants.CLASS_SUFFIX;
break;
case IJavaSearchConstants.CLASS_AND_INTERFACE :
typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
break;
case IJavaSearchConstants.CLASS_AND_ENUM :
typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
break;
case IJavaSearchConstants.INTERFACE :
typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
break;
case IJavaSearchConstants.INTERFACE_AND_ANNOTATION :
typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
break;
case IJavaSearchConstants.ENUM :
typeSuffix = IIndexConstants.ENUM_SUFFIX;
break;
case IJavaSearchConstants.ANNOTATION_TYPE :
typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
break;
default :
typeSuffix = IIndexConstants.TYPE_SUFFIX;
break;
}
final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH
? new TypeDeclarationPattern(
packageName,
null,
typeName,
typeSuffix,
validatedTypeMatchRule)
: new QualifiedTypeDeclarationPattern(
packageName,
packageMatchRule,
typeName,
typeSuffix,
validatedTypeMatchRule);
// Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
final HashSet workingCopyPaths = new HashSet();
String workingCopyPath = null;
ICompilationUnit[] copies = getWorkingCopies();
final int copiesLength = copies == null ? 0 : copies.length;
if (copies != null) {
if (copiesLength == 1) {
workingCopyPath = copies[0].getPath().toString();
} else {
for (int i = 0; i < copiesLength; i++) {
ICompilationUnit workingCopy = copies[i];
workingCopyPaths.add(workingCopy.getPath().toString());
}
}
}
final String singleWkcpPath = workingCopyPath;
// Index requestor
IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
// Filter unexpected types
TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord;
if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
return true; // filter out local and anonymous classes
}
switch (copiesLength) {
case 0:
break;
case 1:
if (singleWkcpPath.equals(documentPath)) {
return true; // filter out *the* working copy
}
break;
default:
if (workingCopyPaths.contains(documentPath)) {
return true; // filter out working copies
}
break;
}
// Accept document path
AccessRestriction accessRestriction = null;
if (access != null) {
// Compute document relative path
int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1;
int nameLength = record.simpleName==null ? 0 : record.simpleName.length;
char[] path = new char[pkgLength+nameLength];
int pos = 0;
if (pkgLength > 0) {
System.arraycopy(record.pkg, 0, path, pos, pkgLength-1);
CharOperation.replace(path, '.', '/');
path[pkgLength-1] = '/';
pos += pkgLength;
}
if (nameLength > 0) {
System.arraycopy(record.simpleName, 0, path, pos, nameLength);
pos += nameLength;
}
// Update access restriction if path is not empty
if (pos > 0) {
accessRestriction = access.getViolatedRestriction(path);
}
}
if (match(record.typeSuffix, record.modifiers)) {
nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
}
return true;
}
};
try {
if (progressMonitor != null) {
progressMonitor.beginTask(Messages.engine_searching, 1000);
}
// add type names from indexes
indexManager.performConcurrentJob(
new PatternSearchJob(
pattern,
getDefaultSearchParticipant(), // Java search only
scope,
searchRequestor),
waitingPolicy,
progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000-copiesLength));
// add type names from working copies
if (copies != null) {
for (int i = 0; i < copiesLength; i++) {
final ICompilationUnit workingCopy = copies[i];
if (scope instanceof HierarchyScope) {
if (!((HierarchyScope)scope).encloses(workingCopy, progressMonitor)) continue;
} else {
if (!scope.encloses(workingCopy)) continue;
}
final String path = workingCopy.getPath().toString();
if (workingCopy.isConsistent()) {
IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray();
IType[] allTypes = workingCopy.getAllTypes();
for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
IType type = allTypes[j];
IJavaElement parent = type.getParent();
char[][] enclosingTypeNames;
if (parent instanceof IType) {
char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray();
enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
} else {
enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
}
char[] simpleName = type.getElementName().toCharArray();
int kind;
if (type.isEnum()) {
kind = TypeDeclaration.ENUM_DECL;
} else if (type.isAnnotation()) {
kind = TypeDeclaration.ANNOTATION_TYPE_DECL;
} else if (type.isClass()) {
kind = TypeDeclaration.CLASS_DECL;
} else /*if (type.isInterface())*/ {
kind = TypeDeclaration.INTERFACE_DECL;
}
if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, kind, packageDeclaration, simpleName)) {
if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, type.getFlags()));
} else {
nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null);
}
}
}
} else {
Parser basicParser = getParser();
org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit);
CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
if (parsedUnit != null) {
final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
class AllTypeDeclarationsVisitor extends ASTVisitor {
public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
return false; // no local/anonymous type
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) {
if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) {
if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
IType type = workingCopy.getType(new String(typeName));
((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, typeDeclaration.modifiers));
} else {
nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
}
}
return true;
}
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) {
// compute enclosing type names
TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
while (enclosing != null) {
enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames);
if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
enclosing = enclosing.enclosingType;
} else {
enclosing = null;
}
}
// report
if (nameRequestor instanceof TypeNameMatchRequestorWrapper) {
IType type = workingCopy.getType(new String(enclosingTypeNames[0]));
for (int j=1, l=enclosingTypeNames.length; j<l; j++) {
type = type.getType(new String(enclosingTypeNames[j]));
}
((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0));
} else {
nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null);
}
}
return true;
}
}
parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
}
}
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) throw new OperationCanceledException();
progressMonitor.worked(1);
}
}
}
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchAllTypeNames(
final char[][] qualifications,
final char[][] typeNames,
final int matchRule,
int searchFor,
IJavaSearchScope scope,
final IRestrictedAccessTypeRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
// Debug
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$
Util.verbose(" - package name: "+(qualifications==null?"null":new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - type name: "+(typeNames==null?"null":new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$
Util.verbose(" - match rule: "+getMatchRuleString(matchRule)); //$NON-NLS-1$
Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$
Util.verbose(" - scope: "+scope); //$NON-NLS-1$
}
IndexManager indexManager = JavaModelManager.getIndexManager();
// Create pattern
final char typeSuffix;
switch(searchFor){
case IJavaSearchConstants.CLASS :
typeSuffix = IIndexConstants.CLASS_SUFFIX;
break;
case IJavaSearchConstants.CLASS_AND_INTERFACE :
typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX;
break;
case IJavaSearchConstants.CLASS_AND_ENUM :
typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX;
break;
case IJavaSearchConstants.INTERFACE :
typeSuffix = IIndexConstants.INTERFACE_SUFFIX;
break;
case IJavaSearchConstants.INTERFACE_AND_ANNOTATION :
typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX;
break;
case IJavaSearchConstants.ENUM :
typeSuffix = IIndexConstants.ENUM_SUFFIX;
break;
case IJavaSearchConstants.ANNOTATION_TYPE :
typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
break;
default :
typeSuffix = IIndexConstants.TYPE_SUFFIX;
break;
}
final MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames, typeSuffix, matchRule);
// Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor
final HashSet workingCopyPaths = new HashSet();
String workingCopyPath = null;
ICompilationUnit[] copies = getWorkingCopies();
final int copiesLength = copies == null ? 0 : copies.length;
if (copies != null) {
if (copiesLength == 1) {
workingCopyPath = copies[0].getPath().toString();
} else {
for (int i = 0; i < copiesLength; i++) {
ICompilationUnit workingCopy = copies[i];
workingCopyPaths.add(workingCopy.getPath().toString());
}
}
}
final String singleWkcpPath = workingCopyPath;
// Index requestor
IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){
public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) {
// Filter unexpected types
QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) indexRecord;
if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) {
return true; // filter out local and anonymous classes
}
switch (copiesLength) {
case 0:
break;
case 1:
if (singleWkcpPath.equals(documentPath)) {
return true; // filter out *the* working copy
}
break;
default:
if (workingCopyPaths.contains(documentPath)) {
return true; // filter out working copies
}
break;
}
// Accept document path
AccessRestriction accessRestriction = null;
if (access != null) {
// Compute document relative path
int qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0 : record.qualification.length + 1;
int nameLength = record.simpleName == null ? 0 : record.simpleName.length;
char[] path = new char[qualificationLength + nameLength];
int pos = 0;
if (qualificationLength > 0) {
System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1);
CharOperation.replace(path, '.', '/');
path[qualificationLength-1] = '/';
pos += qualificationLength;
}
if (nameLength > 0) {
System.arraycopy(record.simpleName, 0, path, pos, nameLength);
pos += nameLength;
}
// Update access restriction if path is not empty
if (pos > 0) {
accessRestriction = access.getViolatedRestriction(path);
}
}
nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction);
return true;
}
};
try {
if (progressMonitor != null) {
progressMonitor.beginTask(Messages.engine_searching, 100);
}
// add type names from indexes
indexManager.performConcurrentJob(
new PatternSearchJob(
pattern,
getDefaultSearchParticipant(), // Java search only
scope,
searchRequestor),
waitingPolicy,
progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100));
// add type names from working copies
if (copies != null) {
for (int i = 0, length = copies.length; i < length; i++) {
ICompilationUnit workingCopy = copies[i];
final String path = workingCopy.getPath().toString();
if (workingCopy.isConsistent()) {
IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations();
char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray();
IType[] allTypes = workingCopy.getAllTypes();
for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) {
IType type = allTypes[j];
IJavaElement parent = type.getParent();
char[][] enclosingTypeNames;
char[] qualification = packageDeclaration;
if (parent instanceof IType) {
char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray();
enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName);
qualification = CharOperation.concat(qualification, parentQualifiedName);
} else {
enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
}
char[] simpleName = type.getElementName().toCharArray();
char suffix = IIndexConstants.TYPE_SUFFIX;
if (type.isClass()) {
suffix = IIndexConstants.CLASS_SUFFIX;
} else if (type.isInterface()) {
suffix = IIndexConstants.INTERFACE_SUFFIX;
} else if (type.isEnum()) {
suffix = IIndexConstants.ENUM_SUFFIX;
} else if (type.isAnnotation()) {
suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX;
}
if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification, simpleName, suffix, matchRule))) {
nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null);
}
}
} else {
Parser basicParser = getParser();
org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy;
CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit);
CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult);
if (parsedUnit != null) {
final char[] packageDeclaration = parsedUnit.currentPackage == null
? CharOperation.NO_CHAR
: CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.');
class AllTypeDeclarationsVisitor extends ASTVisitor {
public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) {
return false; // no local/anonymous type
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) {
SearchPattern decodedPattern =
new QualifiedTypeDeclarationPattern(packageDeclaration, typeDeclaration.name, convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)), matchRule);
if (pattern.matchesDecodedKey(decodedPattern)) {
nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null);
}
return true;
}
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) {
// compute enclosing type names
char[] qualification = packageDeclaration;
TypeDeclaration enclosing = memberTypeDeclaration.enclosingType;
char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR;
while (enclosing != null) {
qualification = CharOperation.concat(qualification, enclosing.name, '.');
enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames);
if ((enclosing.bits & ASTNode.IsMemberType) != 0) {
enclosing = enclosing.enclosingType;
} else {
enclosing = null;
}
}
SearchPattern decodedPattern =
new QualifiedTypeDeclarationPattern(qualification, memberTypeDeclaration.name, convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)), matchRule);
if (pattern.matchesDecodedKey(decodedPattern)) {
nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null);
}
return true;
}
}
parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope);
}
}
}
}
} finally {
if (progressMonitor != null) {
progressMonitor.done();
}
}
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchDeclarations(IJavaElement enclosingElement, SearchRequestor requestor, SearchPattern pattern, IProgressMonitor monitor) throws JavaModelException {
if (VERBOSE) {
Util.verbose(" - java element: "+enclosingElement); //$NON-NLS-1$
}
IJavaSearchScope scope = createJavaSearchScope(new IJavaElement[] {enclosingElement});
IResource resource = ((JavaElement) enclosingElement).resource();
if (enclosingElement instanceof IMember) {
IMember member = (IMember) enclosingElement;
ICompilationUnit cu = member.getCompilationUnit();
if (cu != null) {
resource = cu.getResource();
} else if (member.isBinary()) {
// binary member resource cannot be used as this
// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=148215
resource = null;
}
}
try {
if (resource instanceof IFile) {
try {
requestor.beginReporting();
if (VERBOSE) {
Util.verbose("Searching for " + pattern + " in " + resource.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$
}
SearchParticipant participant = getDefaultSearchParticipant();
SearchDocument[] documents = MatchLocator.addWorkingCopies(
pattern,
new SearchDocument[] {new JavaSearchDocument(enclosingElement.getPath().toString(), participant)},
getWorkingCopies(enclosingElement),
participant);
participant.locateMatches(
documents,
pattern,
scope,
requestor,
monitor);
} finally {
requestor.endReporting();
}
} else {
search(
pattern,
new SearchParticipant[] {getDefaultSearchParticipant()},
scope,
requestor,
monitor);
}
} catch (CoreException e) {
if (e instanceof JavaModelException)
throw (JavaModelException) e;
throw new JavaModelException(e);
}
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchDeclarationsOfAccessedFields(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchDeclarationsOfAccessedFields(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
}
// Do not accept other kind of element type than those specified in the spec
switch (enclosingElement.getElementType()) {
case IJavaElement.FIELD:
case IJavaElement.METHOD:
case IJavaElement.TYPE:
case IJavaElement.COMPILATION_UNIT:
// valid element type
break;
default:
throw new IllegalArgumentException();
}
SearchPattern pattern = new DeclarationOfAccessedFieldsPattern(enclosingElement);
searchDeclarations(enclosingElement, requestor, pattern, monitor);
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchDeclarationsOfReferencedTypes(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchDeclarationsOfReferencedTypes(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
}
// Do not accept other kind of element type than those specified in the spec
switch (enclosingElement.getElementType()) {
case IJavaElement.FIELD:
case IJavaElement.METHOD:
case IJavaElement.TYPE:
case IJavaElement.COMPILATION_UNIT:
// valid element type
break;
default:
throw new IllegalArgumentException();
}
SearchPattern pattern = new DeclarationOfReferencedTypesPattern(enclosingElement);
searchDeclarations(enclosingElement, requestor, pattern, monitor);
}
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void searchDeclarationsOfSentMessages(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
if (VERBOSE) {
Util.verbose("BasicSearchEngine.searchDeclarationsOfSentMessages(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$
}
// Do not accept other kind of element type than those specified in the spec
switch (enclosingElement.getElementType()) {
case IJavaElement.FIELD:
case IJavaElement.METHOD:
case IJavaElement.TYPE:
case IJavaElement.COMPILATION_UNIT:
// valid element type
break;
default:
throw new IllegalArgumentException();
}
SearchPattern pattern = new DeclarationOfReferencedMethodsPattern(enclosingElement);
searchDeclarations(enclosingElement, requestor, pattern, monitor);
}
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected BinaryTypeBinding cacheBinaryType(IType type, IBinaryType binaryType) throws JavaModelException {
IType enclosingType = type.getDeclaringType();
if (enclosingType != null)
cacheBinaryType(enclosingType, null); // cache enclosing types first, so that binary type can be found in lookup enviroment
if (binaryType == null) {
ClassFile classFile = (ClassFile) type.getClassFile();
try {
binaryType = getBinaryInfo(classFile, classFile.resource());
} catch (CoreException e) {
if (e instanceof JavaModelException) {
throw (JavaModelException) e;
} else {
throw new JavaModelException(e);
}
}
}
BinaryTypeBinding binding = this.lookupEnvironment.cacheBinaryType(binaryType, null /*no access restriction*/);
if (binding == null) { // it was already cached as a result of a previous query
char[][] compoundName = CharOperation.splitOn('.', type.getFullyQualifiedName().toCharArray());
ReferenceBinding referenceBinding = this.lookupEnvironment.getCachedType(compoundName);
if (referenceBinding != null && (referenceBinding instanceof BinaryTypeBinding))
binding = (BinaryTypeBinding) referenceBinding; // if the binding could be found and if it comes from a binary type
}
return binding;
}
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public void initialize(JavaProject project, int possibleMatchSize) throws JavaModelException {
// clean up name environment only if there are several possible match as it is reused
// when only one possible match (bug 58581)
if (this.nameEnvironment != null && possibleMatchSize != 1)
this.nameEnvironment.cleanup();
SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.workingCopies);
// if only one possible match, a file name environment costs too much,
// so use the existing searchable environment which will populate the java model
// only for this possible match and its required types.
this.nameEnvironment = possibleMatchSize == 1
? (INameEnvironment) searchableEnvironment
: (INameEnvironment) new JavaSearchNameEnvironment(project, this.workingCopies);
// create lookup environment
Map map = project.getOptions(true);
map.put(CompilerOptions.OPTION_TaskTags, org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING);
this.options = new CompilerOptions(map);
ProblemReporter problemReporter =
new ProblemReporter(
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
this.options,
new DefaultProblemFactory());
this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
this.parser = MatchLocatorParser.createParser(problemReporter, this);
// basic parser needs also to be reset as project options may have changed
// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=163072
this.basicParser = null;
// remember project's name lookup
this.nameLookup = searchableEnvironment.nameLookup;
// initialize queue of units
this.numberOfMatches = 0;
this.matchesToProcess = new PossibleMatch[possibleMatchSize];
}
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
protected CompilationUnitDeclaration buildBindings(ICompilationUnit compilationUnit, boolean isTopLevelOrMember) throws JavaModelException {
// source unit
org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) compilationUnit;
CompilationResult compilationResult = new CompilationResult(sourceUnit, 1, 1, 0);
CompilationUnitDeclaration unit =
isTopLevelOrMember ?
this.locator.basicParser().dietParse(sourceUnit, compilationResult) :
this.locator.basicParser().parse(sourceUnit, compilationResult);
if (unit != null) {
this.locator.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);
this.locator.lookupEnvironment.completeTypeBindings(unit, !isTopLevelOrMember);
if (!isTopLevelOrMember) {
if (unit.scope != null)
unit.scope.faultInTypes(); // fault in fields & methods
unit.resolve();
}
}
return unit;
}
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
public char[][][] collect() throws JavaModelException {
if (this.type != null) {
// Collect the paths of the cus that are in the hierarchy of the given type
this.result = new char[1][][];
this.resultIndex = 0;
JavaProject javaProject = (JavaProject) this.type.getJavaProject();
this.locator.initialize(javaProject, 0);
try {
if (this.type.isBinary()) {
BinaryTypeBinding binding = this.locator.cacheBinaryType(this.type, null);
if (binding != null)
collectSuperTypeNames(binding);
} else {
ICompilationUnit unit = this.type.getCompilationUnit();
SourceType sourceType = (SourceType) this.type;
boolean isTopLevelOrMember = sourceType.getOuterMostLocalContext() == null;
CompilationUnitDeclaration parsedUnit = buildBindings(unit, isTopLevelOrMember);
if (parsedUnit != null) {
TypeDeclaration typeDecl = new ASTNodeFinder(parsedUnit).findType(this.type);
if (typeDecl != null && typeDecl.binding != null)
collectSuperTypeNames(typeDecl.binding);
}
}
} catch (AbortCompilation e) {
// problem with classpath: report inacurrate matches
return null;
}
if (this.result.length > this.resultIndex)
System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
return this.result;
}
// Collect the paths of the cus that declare a type which matches declaringQualification + declaringSimpleName
String[] paths = getPathsOfDeclaringType();
if (paths == null) return null;
// Create bindings from source types and binary types and collect super type names of the type declaration
// that match the given declaring type
Util.sort(paths); // sort by projects
JavaProject previousProject = null;
this.result = new char[1][][];
this.resultIndex = 0;
for (int i = 0, length = paths.length; i < length; i++) {
try {
Openable openable = this.locator.handleFactory.createOpenable(paths[i], this.locator.scope);
if (openable == null) continue; // outside classpath
IJavaProject project = openable.getJavaProject();
if (!project.equals(previousProject)) {
previousProject = (JavaProject) project;
this.locator.initialize(previousProject, 0);
}
if (openable instanceof ICompilationUnit) {
ICompilationUnit unit = (ICompilationUnit) openable;
CompilationUnitDeclaration parsedUnit = buildBindings(unit, true /*only toplevel and member types are visible to the focus type*/);
if (parsedUnit != null)
parsedUnit.traverse(new TypeDeclarationVisitor(), parsedUnit.scope);
} else if (openable instanceof IClassFile) {
IClassFile classFile = (IClassFile) openable;
BinaryTypeBinding binding = this.locator.cacheBinaryType(classFile.getType(), null);
if (matches(binding))
collectSuperTypeNames(binding);
}
} catch (AbortCompilation e) {
// ignore: continue with next element
} catch (JavaModelException e) {
// ignore: continue with next element
}
}
if (this.result.length > this.resultIndex)
System.arraycopy(this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
return this.result;
}
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
private IPath[] computeProjectsAndJars(IType type) throws JavaModelException {
HashSet set = new HashSet();
IPackageFragmentRoot root = (IPackageFragmentRoot)type.getPackageFragment().getParent();
if (root.isArchive()) {
// add the root
set.add(root.getPath());
// add all projects that reference this archive and their dependents
IPath rootPath = root.getPath();
IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
IJavaProject[] projects = model.getJavaProjects();
HashSet visited = new HashSet();
for (int i = 0; i < projects.length; i++) {
JavaProject project = (JavaProject) projects[i];
IClasspathEntry entry = project.getClasspathEntryFor(rootPath);
if (entry != null) {
// add the project and its binary pkg fragment roots
IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
set.add(project.getPath());
for (int k = 0; k < roots.length; k++) {
IPackageFragmentRoot pkgFragmentRoot = roots[k];
if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
set.add(pkgFragmentRoot.getPath());
}
}
// add the dependent projects
computeDependents(project, set, visited);
}
}
} else {
// add all the project's pkg fragment roots
IJavaProject project = (IJavaProject)root.getParent();
IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
for (int i = 0; i < roots.length; i++) {
IPackageFragmentRoot pkgFragmentRoot = roots[i];
if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
set.add(pkgFragmentRoot.getPath());
} else {
set.add(pkgFragmentRoot.getParent().getPath());
}
}
// add the dependent projects
computeDependents(project, set, new HashSet());
}
IPath[] result = new IPath[set.size()];
set.toArray(result);
return result;
}
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
protected void initialize() throws JavaModelException {
initialize(null);
}
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
protected void initialize(IProgressMonitor progressMonitor) throws JavaModelException {
this.resourcePaths = new HashSet();
this.elements = new IResource[5];
this.elementCount = 0;
this.needsRefresh = false;
if (this.hierarchy == null) {
if (this.javaProject != null) {
this.hierarchy = this.focusType.newTypeHierarchy(this.javaProject, this.owner, progressMonitor);
} else {
this.hierarchy = this.focusType.newTypeHierarchy(this.owner, progressMonitor);
}
} else {
this.hierarchy.refresh(progressMonitor);
}
buildResourceVector();
}
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
protected void refresh() throws JavaModelException {
refresh(null);
}
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
protected void refresh(IProgressMonitor progressMonitor) throws JavaModelException {
if (this.hierarchy != null) {
initialize(progressMonitor);
}
}
// in search/org/eclipse/jdt/internal/core/search/TypeNameMatchRequestorWrapper.java
private IType createTypeFromJar(String resourcePath, int separatorIndex) throws JavaModelException {
// path to a class file inside a jar
// Optimization: cache package fragment root handle and package handles
if (this.lastPkgFragmentRootPath == null
|| this.lastPkgFragmentRootPath.length() > resourcePath.length()
|| !resourcePath.startsWith(this.lastPkgFragmentRootPath)) {
String jarPath= resourcePath.substring(0, separatorIndex);
IPackageFragmentRoot root= ((AbstractJavaSearchScope)this.scope).packageFragmentRoot(resourcePath, separatorIndex, jarPath);
if (root == null) return null;
this.lastPkgFragmentRootPath= jarPath;
this.lastPkgFragmentRoot= root;
this.packageHandles= new HashtableOfArrayToObject(5);
}
// create handle
String classFilePath= resourcePath.substring(separatorIndex + 1);
String[] simpleNames = new Path(classFilePath).segments();
String[] pkgName;
int length = simpleNames.length-1;
if (length > 0) {
pkgName = new String[length];
System.arraycopy(simpleNames, 0, pkgName, 0, length);
} else {
pkgName = CharOperation.NO_STRINGS;
}
IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName);
if (pkgFragment == null) {
pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
// filter org.apache.commons.lang.enum package for projects above 1.5
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264
if (length == 5 && pkgName[4].equals("enum")) { //$NON-NLS-1$
IJavaProject proj = (IJavaProject)pkgFragment.getAncestor(IJavaElement.JAVA_PROJECT);
if (!proj.equals(this.lastProject)) {
String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
this.complianceValue = CompilerOptions.versionToJdkLevel(complianceStr);
this.lastProject = proj;
}
if (this.complianceValue >= ClassFileConstants.JDK1_5)
return null;
}
this.packageHandles.put(pkgName, pkgFragment);
}
return pkgFragment.getClassFile(simpleNames[length]).getType();
}
// in search/org/eclipse/jdt/internal/core/search/TypeNameMatchRequestorWrapper.java
private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaModelException {
// path to a file in a directory
// Optimization: cache package fragment root handle and package handles
int rootPathLength = -1;
if (this.lastPkgFragmentRootPath == null
|| !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
&& (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0
&& resourcePath.charAt(rootPathLength) == '/')) {
PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope)this.scope).packageFragmentRoot(resourcePath, -1/*not a jar*/, null/*no jar path*/);
if (root == null) return null;
this.lastPkgFragmentRoot = root;
this.lastPkgFragmentRootPath = root.internalPath().toString();
this.packageHandles = new HashtableOfArrayToObject(5);
}
// create handle
resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
String[] simpleNames = new Path(resourcePath).segments();
String[] pkgName;
int length = simpleNames.length-1;
if (length > 0) {
pkgName = new String[length];
System.arraycopy(simpleNames, 0, pkgName, 0, length);
} else {
pkgName = CharOperation.NO_STRINGS;
}
IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName);
if (pkgFragment == null) {
pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
this.packageHandles.put(pkgName, pkgFragment);
}
String simpleName= simpleNames[length];
if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) {
ICompilationUnit unit= pkgFragment.getCompilationUnit(simpleName);
int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length;
IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0]));
if (etnLength > 0) {
for (int i=1; i<etnLength; i++) {
type = type.getType(new String(enclosingTypeNames[i]));
}
type = type.getType(simpleTypeName);
}
return type;
} else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)){
IClassFile classFile= pkgFragment.getClassFile(simpleName);
return classFile.getType();
}
return null;
}
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
private static IJavaElement[] getFocusedElementsAndTypes(SearchPattern pattern, IJavaElement focusElement, ObjectVector superTypes) throws JavaModelException {
if (pattern instanceof MethodPattern) {
// For method pattern, it needs to walk along the focus type super hierarchy
// and add jars/projects of all the encountered types.
IType type = (IType) pattern.focus.getAncestor(IJavaElement.TYPE);
MethodPattern methodPattern = (MethodPattern) pattern;
String selector = new String(methodPattern.selector);
int parameterCount = methodPattern.parameterCount;
ITypeHierarchy superHierarchy = type.newSupertypeHierarchy(null);
IType[] allTypes = superHierarchy.getAllSupertypes(type);
int length = allTypes.length;
SimpleSet focusSet = new SimpleSet(length+1);
if (focusElement != null) focusSet.add(focusElement);
for (int i=0; i<length; i++) {
IMethod[] methods = allTypes[i].getMethods();
int mLength = methods.length;
for (int m=0; m<mLength; m++) {
if (parameterCount == methods[m].getNumberOfParameters() && methods[m].getElementName().equals(selector)) {
IPackageFragmentRoot root = (IPackageFragmentRoot) allTypes[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
IJavaElement element = root.isArchive() ? root : root.getParent();
focusSet.add(element);
if (superTypes != null) superTypes.add(allTypes[i]);
break;
}
}
}
// Rebuilt a contiguous array
IJavaElement[] focuses = new IJavaElement[focusSet.elementSize];
Object[] values = focusSet.values;
int count = 0;
for (int i = values.length; --i >= 0;) {
if (values[i] != null) {
focuses[count++] = (IJavaElement) values[i];
}
}
return focuses;
}
if (focusElement == null) return new IJavaElement[0];
return new IJavaElement[] { focusElement };
}
// in search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
public void add(JavaProject project, int includeMask, HashSet projectsToBeAdded) throws JavaModelException {
add(project, null, includeMask, projectsToBeAdded, new HashSet(2), null);
}
// in search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
void add(JavaProject javaProject, IPath pathToAdd, int includeMask, HashSet projectsToBeAdded, HashSet visitedProjects, IClasspathEntry referringEntry) throws JavaModelException {
IProject project = javaProject.getProject();
if (!project.isAccessible() || !visitedProjects.add(project)) return;
IPath projectPath = project.getFullPath();
String projectPathString = projectPath.toString();
addEnclosingProjectOrJar(projectPath);
IClasspathEntry[] entries = javaProject.getResolvedClasspath();
IJavaModel model = javaProject.getJavaModel();
JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo();
for (int i = 0, length = entries.length; i < length; i++) {
IClasspathEntry entry = entries[i];
AccessRuleSet access = null;
ClasspathEntry cpEntry = (ClasspathEntry) entry;
if (referringEntry != null) {
// Add only exported entries.
// Source folder are implicitly exported.
if (!entry.isExported() && entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
continue;
}
cpEntry = cpEntry.combineWith((ClasspathEntry)referringEntry);
// cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry);
}
access = cpEntry.getAccessRuleSet();
switch (entry.getEntryKind()) {
case IClasspathEntry.CPE_LIBRARY:
IClasspathEntry rawEntry = null;
Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
if (rootPathToRawEntries != null) {
rawEntry = (IClasspathEntry) rootPathToRawEntries.get(entry.getPath());
}
if (rawEntry == null) break;
rawKind: switch (rawEntry.getEntryKind()) {
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
if ((includeMask & APPLICATION_LIBRARIES) != 0) {
IPath path = entry.getPath();
if (pathToAdd == null || pathToAdd.equals(path)) {
Object target = JavaModel.getTarget(path, false/*don't check existence*/);
if (target instanceof IFolder) // case of an external folder
path = ((IFolder) target).getFullPath();
String pathToString = path.getDevice() == null ? path.toString() : path.toOSString();
add(projectPath.toString(), "", pathToString, false/*not a package*/, access); //$NON-NLS-1$
addEnclosingProjectOrJar(entry.getPath());
}
}
break;
case IClasspathEntry.CPE_CONTAINER:
IClasspathContainer container = JavaCore.getClasspathContainer(rawEntry.getPath(), javaProject);
if (container == null) break;
switch (container.getKind()) {
case IClasspathContainer.K_APPLICATION:
if ((includeMask & APPLICATION_LIBRARIES) == 0) break rawKind;
break;
case IClasspathContainer.K_SYSTEM:
case IClasspathContainer.K_DEFAULT_SYSTEM:
if ((includeMask & SYSTEM_LIBRARIES) == 0) break rawKind;
break;
default:
break rawKind;
}
IPath path = entry.getPath();
if (pathToAdd == null || pathToAdd.equals(path)) {
Object target = JavaModel.getTarget(path, false/*don't check existence*/);
if (target instanceof IFolder) // case of an external folder
path = ((IFolder) target).getFullPath();
String pathToString = path.getDevice() == null ? path.toString() : path.toOSString();
add(projectPath.toString(), "", pathToString, false/*not a package*/, access); //$NON-NLS-1$
addEnclosingProjectOrJar(entry.getPath());
}
break;
}
break;
case IClasspathEntry.CPE_PROJECT:
if ((includeMask & REFERENCED_PROJECTS) != 0) {
IPath path = entry.getPath();
if (pathToAdd == null || pathToAdd.equals(path)) {
JavaProject referencedProject = (JavaProject) model.getJavaProject(path.lastSegment());
if (!projectsToBeAdded.contains(referencedProject)) { // do not recurse if depending project was used to create the scope
add(referencedProject, null, includeMask, projectsToBeAdded, visitedProjects, cpEntry);
}
}
}
break;
case IClasspathEntry.CPE_SOURCE:
if ((includeMask & SOURCES) != 0) {
IPath path = entry.getPath();
if (pathToAdd == null || pathToAdd.equals(path)) {
add(projectPath.toString(), Util.relativePath(path,1/*remove project segment*/), projectPathString, false/*not a package*/, access);
}
}
break;
}
}
}
// in search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
public void add(IJavaElement element) throws JavaModelException {
IPath containerPath = null;
String containerPathToString = null;
PackageFragmentRoot root = null;
int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES;
switch (element.getElementType()) {
case IJavaElement.JAVA_MODEL:
// a workspace sope should be used
break;
case IJavaElement.JAVA_PROJECT:
add((JavaProject)element, null, includeMask, new HashSet(2), new HashSet(2), null);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
root = (PackageFragmentRoot)element;
IPath rootPath = root.internalPath();
containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : rootPath;
containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
IResource rootResource = root.resource();
String projectPath = root.getJavaProject().getPath().toString();
if (rootResource != null && rootResource.isAccessible()) {
String relativePath = Util.relativePath(rootResource.getFullPath(), containerPath.segmentCount());
add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
} else {
add(projectPath, "", containerPathToString, false/*not a package*/, null); //$NON-NLS-1$
}
break;
case IJavaElement.PACKAGE_FRAGMENT:
root = (PackageFragmentRoot)element.getParent();
projectPath = root.getJavaProject().getPath().toString();
if (root.isArchive()) {
String relativePath = Util.concatWith(((PackageFragment) element).names, '/');
containerPath = root.getPath();
containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
add(projectPath, relativePath, containerPathToString, true/*package*/, null);
} else {
IResource resource = ((JavaElement) element).resource();
if (resource != null) {
if (resource.isAccessible()) {
containerPath = root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.internalPath();
} else {
// for working copies, get resource container full path
containerPath = resource.getParent().getFullPath();
}
containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount());
add(projectPath, relativePath, containerPathToString, true/*package*/, null);
}
}
break;
default:
// remember sub-cu (or sub-class file) java elements
if (element instanceof IMember) {
if (this.elements == null) {
this.elements = new ArrayList();
}
this.elements.add(element);
}
root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
projectPath = root.getJavaProject().getPath().toString();
String relativePath;
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
containerPath = root.getParent().getPath();
relativePath = Util.relativePath(getPath(element, false/*full path*/), 1/*remove project segment*/);
} else {
containerPath = root.internalPath();
relativePath = getPath(element, true/*relative path*/).toString();
}
containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
add(projectPath, relativePath, containerPathToString, false/*not a package*/, null);
}
if (root != null)
addEnclosingProjectOrJar(root.getKind() == IPackageFragmentRoot.K_SOURCE ? root.getParent().getPath() : root.getPath());
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public static IJavaSearchScope createHierarchyScope(IType type) throws JavaModelException {
return BasicSearchEngine.createHierarchyScope(type);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public static IJavaSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaModelException {
return BasicSearchEngine.createHierarchyScope(type, owner);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public static IJavaSearchScope createStrictHierarchyScope(IJavaProject project, IType type, boolean onlySubtypes, boolean includeFocusType, WorkingCopyOwner owner) throws JavaModelException {
return BasicSearchEngine.createStrictHierarchyScope(project, type, onlySubtypes, includeFocusType, owner);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void search(IWorkspace workspace, String patternString, int searchFor, int limitTo, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
try {
int matchMode = patternString.indexOf('*') != -1 || patternString.indexOf('?') != -1
? SearchPattern.R_PATTERN_MATCH
: SearchPattern.R_EXACT_MATCH;
search(
SearchPattern.createPattern(patternString, searchFor, limitTo, matchMode | SearchPattern.R_CASE_SENSITIVE),
new SearchParticipant[] {getDefaultSearchParticipant()},
scope,
new ResultCollectorAdapter(resultCollector),
resultCollector.getProgressMonitor());
} catch (CoreException e) {
if (e instanceof JavaModelException)
throw (JavaModelException) e;
throw new JavaModelException(e);
}
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void search(IWorkspace workspace, IJavaElement element, int limitTo, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
search(workspace, createSearchPattern(element, limitTo), scope, resultCollector);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void search(IWorkspace workspace, ISearchPattern searchPattern, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
try {
search(
((SearchPatternAdapter)searchPattern).pattern,
new SearchParticipant[] {getDefaultSearchParticipant()},
scope,
new ResultCollectorAdapter(resultCollector),
resultCollector.getProgressMonitor());
} catch (CoreException e) {
if (e instanceof JavaModelException)
throw (JavaModelException) e;
throw new JavaModelException(e);
}
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[] packageExactName,
final char[] typeName,
final int matchRule,
int searchFor,
IJavaSearchScope scope,
final TypeNameRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
searchAllTypeNames(packageExactName, SearchPattern.R_EXACT_MATCH, typeName, matchRule, searchFor, scope, nameRequestor, waitingPolicy, progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[] packageName,
final int packageMatchRule,
final char[] typeName,
final int typeMatchRule,
int searchFor,
IJavaSearchScope scope,
final TypeNameRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor);
this.basicEngine.searchAllTypeNames(packageName,
packageMatchRule,
typeName,
typeMatchRule,
searchFor,
scope,
requestorWrapper,
waitingPolicy,
progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[] packageName,
final int packageMatchRule,
final char[] typeName,
final int typeMatchRule,
int searchFor,
IJavaSearchScope scope,
final TypeNameMatchRequestor nameMatchRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope);
this.basicEngine.searchAllTypeNames(packageName,
packageMatchRule,
typeName,
typeMatchRule,
searchFor,
scope,
requestorWrapper,
waitingPolicy,
progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[][] qualifications,
final char[][] typeNames,
IJavaSearchScope scope,
final TypeNameRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor);
this.basicEngine.searchAllTypeNames(
qualifications,
typeNames,
SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
scope,
requestorWrapper,
waitingPolicy,
progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[][] qualifications,
final char[][] typeNames,
IJavaSearchScope scope,
final TypeNameMatchRequestor nameMatchRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope);
this.basicEngine.searchAllTypeNames(
qualifications,
typeNames,
SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
scope,
requestorWrapper,
waitingPolicy,
progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
final char[] packageName,
final char[] typeName,
final int matchRule,
int searchFor,
IJavaSearchScope scope,
final ITypeNameRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
TypeNameRequestorAdapter requestorAdapter = new TypeNameRequestorAdapter(nameRequestor);
this.basicEngine.searchAllTypeNames(packageName, SearchPattern.R_EXACT_MATCH, typeName, matchRule, searchFor, scope, requestorAdapter, waitingPolicy, progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchAllTypeNames(
IWorkspace workspace,
final char[] packageName,
final char[] typeName,
final int matchMode,
final boolean isCaseSensitive,
int searchFor,
IJavaSearchScope scope,
final ITypeNameRequestor nameRequestor,
int waitingPolicy,
IProgressMonitor progressMonitor) throws JavaModelException {
searchAllTypeNames(
packageName,
typeName,
isCaseSensitive ? matchMode | SearchPattern.R_CASE_SENSITIVE : matchMode,
searchFor,
scope,
nameRequestor,
waitingPolicy,
progressMonitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfAccessedFields(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
this.basicEngine.searchDeclarationsOfAccessedFields(enclosingElement, requestor, monitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfAccessedFields(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
SearchPattern pattern = new DeclarationOfAccessedFieldsPattern(enclosingElement);
this.basicEngine.searchDeclarations(enclosingElement, new ResultCollectorAdapter(resultCollector), pattern, resultCollector.getProgressMonitor());
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfReferencedTypes(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
this.basicEngine.searchDeclarationsOfReferencedTypes(enclosingElement, requestor, monitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfReferencedTypes(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
SearchPattern pattern = new DeclarationOfReferencedTypesPattern(enclosingElement);
this.basicEngine.searchDeclarations(enclosingElement, new ResultCollectorAdapter(resultCollector), pattern, resultCollector.getProgressMonitor());
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfSentMessages(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor);
}
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void searchDeclarationsOfSentMessages(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
SearchPattern pattern = new DeclarationOfReferencedMethodsPattern(enclosingElement);
this.basicEngine.searchDeclarations(enclosingElement, new ResultCollectorAdapter(resultCollector), pattern, resultCollector.getProgressMonitor());
}
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
protected void renameEntryInClasspath(IPath rootPath, IJavaProject project) throws JavaModelException {
IClasspathEntry[] classpath = project.getRawClasspath();
IClasspathEntry[] newClasspath = null;
int cpLength = classpath.length;
int newCPIndex = -1;
for (int i = 0; i < cpLength; i++) {
IClasspathEntry entry = classpath[i];
IPath entryPath = entry.getPath();
if (rootPath.equals(entryPath)) {
// rename entry
if (newClasspath == null) {
newClasspath = new IClasspathEntry[cpLength];
System.arraycopy(classpath, 0, newClasspath, 0, i);
newCPIndex = i;
}
newClasspath[newCPIndex++] = copy(entry);
} else if (this.destination.equals(entryPath)) {
// remove entry equals to destination
if (newClasspath == null) {
newClasspath = new IClasspathEntry[cpLength];
System.arraycopy(classpath, 0, newClasspath, 0, i);
newCPIndex = i;
}
} else if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
// update exclusion/inclusion patterns
IPath projectRelativePath = rootPath.removeFirstSegments(1);
IPath[] newExclusionPatterns = renamePatterns(projectRelativePath, entry.getExclusionPatterns());
IPath[] newInclusionPatterns = renamePatterns(projectRelativePath, entry.getInclusionPatterns());
if (newExclusionPatterns != null || newInclusionPatterns != null) {
if (newClasspath == null) {
newClasspath = new IClasspathEntry[cpLength];
System.arraycopy(classpath, 0, newClasspath, 0, i);
newCPIndex = i;
}
newClasspath[newCPIndex++] =
JavaCore.newSourceEntry(
entry.getPath(),
newInclusionPatterns == null ? entry.getInclusionPatterns() : newInclusionPatterns,
newExclusionPatterns == null ? entry.getExclusionPatterns() : newExclusionPatterns,
entry.getOutputLocation(),
entry.getExtraAttributes());
} else if (newClasspath != null) {
newClasspath[newCPIndex++] = entry;
}
} else if (newClasspath != null) {
newClasspath[newCPIndex++] = entry;
}
}
if (newClasspath != null) {
if (newCPIndex < newClasspath.length) {
System.arraycopy(newClasspath, 0, newClasspath = new IClasspathEntry[newCPIndex], 0, newCPIndex);
}
IJavaModelStatus status = JavaConventions.validateClasspath(project, newClasspath, project.getOutputLocation());
if (status.isOK())
project.setRawClasspath(newClasspath, this.progressMonitor);
// don't update classpath if status is not ok to avoid JavaModelException (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129991)
}
}
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
protected void executeOperation() throws JavaModelException {
IPackageFragmentRoot root = (IPackageFragmentRoot) getElementToProcess();
IClasspathEntry rootEntry = root.getRawClasspathEntry();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
// move resource
if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
moveResource(root, rootEntry, workspaceRoot);
}
// update refering projects classpath excluding orignating project
IJavaProject originatingProject = root.getJavaProject();
if ((this.updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_CLASSPATH) != 0) {
updateReferringProjectClasspaths(rootEntry.getPath(), originatingProject);
}
boolean isRename = this.destination.segment(0).equals(originatingProject.getElementName());
boolean updateOriginating = (this.updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH) != 0;
boolean updateDestination = (this.updateModelFlags & IPackageFragmentRoot.DESTINATION_PROJECT_CLASSPATH) != 0;
// update originating classpath
if (updateOriginating) {
if (isRename && updateDestination) {
renameEntryInClasspath(rootEntry.getPath(), originatingProject);
} else {
removeEntryFromClasspath(rootEntry.getPath(), originatingProject);
}
}
// update destination classpath
if (updateDestination) {
if (!isRename || !updateOriginating) {
addEntryToClasspath(rootEntry, workspaceRoot);
} // else reference has been updated when updating originating project classpath
}
}
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
protected void moveResource(
IPackageFragmentRoot root,
IClasspathEntry rootEntry,
final IWorkspaceRoot workspaceRoot)
throws JavaModelException {
final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
IResource rootResource = ((JavaElement) root).resource();
if (rootEntry.getEntryKind() != IClasspathEntry.CPE_SOURCE || exclusionPatterns == null) {
try {
IResource destRes;
if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& (destRes = workspaceRoot.findMember(this.destination)) != null) {
destRes.delete(this.updateResourceFlags, this.progressMonitor);
}
rootResource.move(this.destination, this.updateResourceFlags, this.progressMonitor);
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else {
final int sourceSegmentCount = rootEntry.getPath().segmentCount();
final IFolder destFolder = workspaceRoot.getFolder(this.destination);
final IPath[] nestedFolders = getNestedFolders(root);
IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
public boolean visit(IResourceProxy proxy) throws CoreException {
if (proxy.getType() == IResource.FOLDER) {
IPath path = proxy.requestFullPath();
if (prefixesOneOf(path, nestedFolders)) {
if (equalsOneOf(path, nestedFolders)) {
// nested source folder
return false;
} else {
// folder containing nested source folder
IFolder folder = destFolder.getFolder(path.removeFirstSegments(sourceSegmentCount));
if ((MovePackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& folder.exists()) {
return true;
}
folder.create(MovePackageFragmentRootOperation.this.updateResourceFlags, true, MovePackageFragmentRootOperation.this.progressMonitor);
return true;
}
} else {
// subtree doesn't contain any nested source folders
IPath destPath = MovePackageFragmentRootOperation.this.destination.append(path.removeFirstSegments(sourceSegmentCount));
IResource destRes;
if ((MovePackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& (destRes = workspaceRoot.findMember(destPath)) != null) {
destRes.delete(MovePackageFragmentRootOperation.this.updateResourceFlags, MovePackageFragmentRootOperation.this.progressMonitor);
}
proxy.requestResource().move(destPath, MovePackageFragmentRootOperation.this.updateResourceFlags, MovePackageFragmentRootOperation.this.progressMonitor);
return false;
}
} else {
IPath path = proxy.requestFullPath();
IPath destPath = MovePackageFragmentRootOperation.this.destination.append(path.removeFirstSegments(sourceSegmentCount));
IResource destRes;
if ((MovePackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& (destRes = workspaceRoot.findMember(destPath)) != null) {
destRes.delete(MovePackageFragmentRootOperation.this.updateResourceFlags, MovePackageFragmentRootOperation.this.progressMonitor);
}
proxy.requestResource().move(destPath, MovePackageFragmentRootOperation.this.updateResourceFlags, MovePackageFragmentRootOperation.this.progressMonitor);
return false;
}
}
};
try {
rootResource.accept(visitor, IResource.NONE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
}
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
protected void updateReferringProjectClasspaths(IPath rootPath, IJavaProject projectOfRoot) throws JavaModelException {
IJavaModel model = getJavaModel();
IJavaProject[] projects = model.getJavaProjects();
for (int i = 0, length = projects.length; i < length; i++) {
IJavaProject project = projects[i];
if (project.equals(projectOfRoot)) continue;
renameEntryInClasspath(rootPath, project);
}
}
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
protected void removeEntryFromClasspath(IPath rootPath, IJavaProject project) throws JavaModelException {
IClasspathEntry[] classpath = project.getRawClasspath();
IClasspathEntry[] newClasspath = null;
int cpLength = classpath.length;
int newCPIndex = -1;
for (int i = 0; i < cpLength; i++) {
IClasspathEntry entry = classpath[i];
if (rootPath.equals(entry.getPath())) {
if (newClasspath == null) {
newClasspath = new IClasspathEntry[cpLength];
System.arraycopy(classpath, 0, newClasspath, 0, i);
newCPIndex = i;
}
} else if (newClasspath != null) {
newClasspath[newCPIndex++] = entry;
}
}
if (newClasspath != null) {
if (newCPIndex < newClasspath.length) {
System.arraycopy(newClasspath, 0, newClasspath = new IClasspathEntry[newCPIndex], 0, newCPIndex);
}
project.setRawClasspath(newClasspath, this.progressMonitor);
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public ICompilationUnit becomeWorkingCopy(IProblemRequestor problemRequestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
if (perWorkingCopyInfo == null) {
// close cu and its children
close();
BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
operation.runOperation(monitor);
return workingCopy;
}
return perWorkingCopyInfo.workingCopy;
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
IBinaryType typeInfo = getBinaryTypeInfo((IFile) underlyingResource);
if (typeInfo == null) {
// The structure of a class file is unknown if a class file format errors occurred
//during the creation of the diet class file representative of this ClassFile.
info.setChildren(new IJavaElement[] {});
return false;
}
// Make the type
IType type = getType();
info.setChildren(new IJavaElement[] {type});
newElements.put(type, typeInfo);
// Read children
((ClassFileInfo) info).readBinaryChildren(this, (HashMap) newElements, typeInfo);
return true;
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, ICompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
codeComplete(offset, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), owner);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, CompletionRequestor requestor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, CompletionRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
codeComplete(offset, requestor, owner, null);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
String source = getSource();
if (source != null) {
BinaryType type = (BinaryType) getType();
BasicCompilationUnit cu =
new BasicCompilationUnit(
getSource().toCharArray(),
null,
type.sourceFileName((IBinaryType) type.getElementInfo()),
getJavaProject()); // use project to retrieve corresponding .java IFile
codeComplete(cu, cu, offset, requestor, owner, null/*extended context isn't computed*/, monitor);
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) throws JavaModelException {
IBuffer buffer = getBuffer();
char[] contents;
if (buffer != null && (contents = buffer.getCharacters()) != null) {
BinaryType type = (BinaryType) getType();
BasicCompilationUnit cu = new BasicCompilationUnit(contents, null, type.sourceFileName((IBinaryType) type.getElementInfo()));
return super.codeSelect(cu, offset, length, owner);
} else {
//has no associated souce
return new IJavaElement[] {};
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
return getType().getAttachedJavadoc(monitor);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IBinaryType getBinaryTypeInfo(IFile file) throws JavaModelException {
return getBinaryTypeInfo(file, true/*fully initialize so as to not keep a reference to the byte array*/);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IBinaryType getBinaryTypeInfo(IFile file, boolean fullyInitialize) throws JavaModelException {
JavaElement pkg = (JavaElement) getParent();
if (pkg instanceof JarPackageFragment) {
try {
IBinaryType info = getJarBinaryTypeInfo((PackageFragment) pkg, fullyInitialize);
if (info == null) {
throw newNotPresentException();
}
return info;
} catch (ClassFormatException cfe) {
//the structure remains unknown
if (JavaCore.getPlugin().isDebugging()) {
cfe.printStackTrace(System.err);
}
return null;
} catch (IOException ioe) {
throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
} catch (CoreException e) {
if (e instanceof JavaModelException) {
throw (JavaModelException)e;
} else {
throw new JavaModelException(e);
}
}
} else {
byte[] contents = Util.getResourceContentsAsByteArray(file);
try {
return new ClassFileReader(contents, file.getFullPath().toString().toCharArray(), fullyInitialize);
} catch (ClassFormatException cfe) {
//the structure remains unknown
return null;
}
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public byte[] getBytes() throws JavaModelException {
JavaElement pkg = (JavaElement) getParent();
if (pkg instanceof JarPackageFragment) {
JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
ZipFile zip = null;
try {
zip = root.getJar();
String entryName = Util.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
ZipEntry ze = zip.getEntry(entryName);
if (ze != null) {
return org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
}
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
} catch (IOException ioe) {
throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
} catch (CoreException e) {
if (e instanceof JavaModelException) {
throw (JavaModelException)e;
} else {
throw new JavaModelException(e);
}
} finally {
JavaModelManager.getJavaModelManager().closeZipFile(zip);
}
} else {
IFile file = (IFile) resource();
return Util.getResourceContentsAsByteArray(file);
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IBuffer getBuffer() throws JavaModelException {
IStatus status = validateClassFile();
if (status.isOK()) {
return super.getBuffer();
} else {
// .class file not on classpath, create a new buffer to be nice (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=41444)
Object info = ((ClassFile) getClassFile()).getBinaryTypeInfo((IFile) resource());
IBuffer buffer = openBuffer(null, info);
if (buffer != null && !(buffer instanceof NullBuffer))
return buffer;
switch (status.getCode()) {
case IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH: // don't throw a JavaModelException to be able to open .class file outside the classpath (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138507 )
case IJavaModelStatusConstants.INVALID_ELEMENT_TYPES: // don't throw a JavaModelException to be able to open .class file in proj==src case without source (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=221904 )
return null;
default:
throw new JavaModelException((IJavaModelStatus) status);
}
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IResource getCorrespondingResource() throws JavaModelException {
IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
if (root.isArchive()) {
return null;
} else {
return getUnderlyingResource();
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IJavaElement getElementAt(int position) throws JavaModelException {
IJavaElement parentElement = getParent();
while (parentElement.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) {
parentElement = parentElement.getParent();
}
PackageFragmentRoot root = (PackageFragmentRoot) parentElement;
SourceMapper mapper = root.getSourceMapper();
if (mapper == null) {
return null;
} else {
// ensure this class file's buffer is open so that source ranges are computed
getBuffer();
IType type = getType();
return findElement(type, position, mapper);
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IJavaElement getElementAtConsideringSibling(int position) throws JavaModelException {
IPackageFragment fragment = (IPackageFragment)getParent();
PackageFragmentRoot root = (PackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
SourceMapper mapper = root.getSourceMapper();
if (mapper == null) {
return null;
} else {
int index = this.name.indexOf('$');
int prefixLength = index < 0 ? this.name.length() : index;
IType type = null;
int start = -1;
int end = Integer.MAX_VALUE;
IJavaElement[] children = fragment.getChildren();
for (int i = 0; i < children.length; i++) {
String childName = children[i].getElementName();
int childIndex = childName.indexOf('$');
int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex;
if (prefixLength == childPrefixLength && this.name.regionMatches(0, childName, 0, prefixLength)) {
IClassFile classFile = (IClassFile) children[i];
// ensure this class file's buffer is open so that source ranges are computed
classFile.getBuffer();
SourceRange range = mapper.getSourceRange(classFile.getType());
if (range == SourceMapper.UNKNOWN_RANGE) continue;
int newStart = range.getOffset();
int newEnd = newStart + range.getLength() - 1;
if(newStart > start && newEnd < end
&& newStart <= position && newEnd >= position) {
type = classFile.getType();
start = newStart;
end = newEnd;
}
}
}
if(type != null) {
return findElement(type, position, mapper);
}
return null;
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public String getSource() throws JavaModelException {
IBuffer buffer = getBuffer();
if (buffer == null) {
return null;
}
return buffer.getContents();
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public ISourceRange getSourceRange() throws JavaModelException {
IBuffer buffer = getBuffer();
if (buffer != null) {
String contents = buffer.getContents();
if (contents == null) return null;
return new SourceRange(0, contents.length());
} else {
return null;
}
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public ICompilationUnit getWorkingCopy(WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
CompilationUnit workingCopy = new ClassFileWorkingCopy(this, owner == null ? DefaultWorkingCopyOwner.PRIMARY : owner);
JavaModelManager manager = JavaModelManager.getJavaModelManager();
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
if (perWorkingCopyInfo != null) {
return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
}
BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, null);
op.runOperation(monitor);
return workingCopy;
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public IJavaElement getWorkingCopy(IProgressMonitor monitor, org.eclipse.jdt.core.IBufferFactory factory) throws JavaModelException {
return getWorkingCopy(BufferFactoryWrapper.create(factory), monitor);
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public boolean isClass() throws JavaModelException {
return getType().isClass();
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public boolean isInterface() throws JavaModelException {
return getType().isInterface();
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
// Check the cache for the top-level type first
IType outerMostEnclosingType = getOuterMostEnclosingType();
IBuffer buffer = getBufferManager().getBuffer(outerMostEnclosingType.getClassFile());
if (buffer == null) {
SourceMapper mapper = getSourceMapper();
IBinaryType typeInfo = info instanceof IBinaryType ? (IBinaryType) info : null;
if (mapper != null) {
buffer = mapSource(mapper, typeInfo, outerMostEnclosingType.getClassFile());
}
}
return buffer;
}
// in model/org/eclipse/jdt/internal/core/ClassFile.java
public void codeComplete(int offset, final org.eclipse.jdt.core.ICodeCompletionRequestor requestor) throws JavaModelException {
if (requestor == null){
codeComplete(offset, (ICompletionRequestor)null);
return;
}
codeComplete(
offset,
new ICompletionRequestor(){
public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName, char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
// ignore
}
public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
}
public void acceptError(IProblem error) {
// was disabled in 1.0
}
public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptField(declaringTypePackageName, declaringTypeName, fieldName, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
requestor.acceptKeyword(keywordName, completionStart, completionEnd);
}
public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
requestor.acceptLabel(labelName, completionStart, completionEnd);
}
public void acceptLocalVariable(char[] localVarName,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// skip parameter names
requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
requestor.acceptModifier(modifierName, completionStart, completionEnd);
}
public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
}
public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
}
public void acceptVariableName(char[] typePackageName,char[] typeName,char[] varName,char[] completionName,int completionStart,int completionEnd, int relevance){
// ignore
}
});
}
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
protected void executeOperation() throws JavaModelException {
checkCanceled();
try {
beginTask(Messages.element_reconciling, 2);
CompilationUnit workingCopy = getWorkingCopy();
boolean wasConsistent = workingCopy.isConsistent();
// check is problem requestor is active
IProblemRequestor problemRequestor = workingCopy.getPerWorkingCopyInfo();
if (problemRequestor != null)
problemRequestor = ((JavaModelManager.PerWorkingCopyInfo)problemRequestor).getProblemRequestor();
boolean defaultRequestorIsActive = problemRequestor != null && problemRequestor.isActive();
IProblemRequestor ownerProblemRequestor = this.workingCopyOwner.getProblemRequestor(workingCopy);
boolean ownerRequestorIsActive = ownerProblemRequestor != null && ownerProblemRequestor != problemRequestor && ownerProblemRequestor.isActive();
this.requestorIsActive = defaultRequestorIsActive || ownerRequestorIsActive;
// create the delta builder (this remembers the current content of the cu)
this.deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
// make working copy consistent if needed and compute AST if needed
makeConsistent(workingCopy);
// notify reconcile participants only if working copy was not consistent or if forcing problem detection
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=177319)
if (!wasConsistent || ((this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0)) {
notifyParticipants(workingCopy);
// recreate ast if one participant reset it
if (this.ast == null)
makeConsistent(workingCopy);
}
// report problems
if (this.problems != null && (((this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) || !wasConsistent)) {
if (defaultRequestorIsActive) {
reportProblems(workingCopy, problemRequestor);
}
if (ownerRequestorIsActive) {
reportProblems(workingCopy, ownerProblemRequestor);
}
}
// report delta
JavaElementDelta delta = this.deltaBuilder.delta;
if (delta != null) {
addReconcileDelta(workingCopy, delta);
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(CompilationUnit workingCopy) throws JavaModelException {
if (!workingCopy.isConsistent()) {
// make working copy consistent
if (this.problems == null) this.problems = new HashMap();
this.resolveBindings = this.requestorIsActive;
this.ast = workingCopy.makeConsistent(this.astLevel, this.resolveBindings, this.reconcileFlags, this.problems, this.progressMonitor);
this.deltaBuilder.buildDeltas();
if (this.ast != null && this.deltaBuilder.delta != null)
this.deltaBuilder.delta.changedAST(this.ast);
return this.ast;
}
if (this.ast != null)
return this.ast; // no need to recompute AST if known already
CompilationUnitDeclaration unit = null;
try {
JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
CompilationUnit source = workingCopy.cloneCachingContents();
// find problems if needed
if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject())
&& (this.reconcileFlags & ICompilationUnit.FORCE_PROBLEM_DETECTION) != 0) {
this.resolveBindings = this.requestorIsActive;
if (this.problems == null)
this.problems = new HashMap();
unit =
CompilationUnitProblemFinder.process(
source,
this.workingCopyOwner,
this.problems,
this.astLevel != ICompilationUnit.NO_AST/*creating AST if level is not NO_AST */,
this.reconcileFlags,
this.progressMonitor);
if (this.progressMonitor != null) this.progressMonitor.worked(1);
}
// create AST if needed
if (this.astLevel != ICompilationUnit.NO_AST
&& unit !=null/*unit is null if working copy is consistent && (problem detection not forced || non-Java project) -> don't create AST as per API*/) {
Map options = workingCopy.getJavaProject().getOptions(true);
// convert AST
this.ast =
AST.convertCompilationUnit(
this.astLevel,
unit,
options,
this.resolveBindings,
source,
this.reconcileFlags,
this.progressMonitor);
if (this.ast != null) {
if (this.deltaBuilder.delta == null) {
this.deltaBuilder.delta = new JavaElementDelta(workingCopy);
}
this.deltaBuilder.delta.changedAST(this.ast);
}
if (this.progressMonitor != null) this.progressMonitor.worked(1);
}
} catch (JavaModelException e) {
if (JavaProject.hasJavaNature(workingCopy.getJavaProject().getProject()))
throw e;
// else JavaProject has lost its nature (or most likely was closed/deleted) while reconciling -> ignore
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=100919)
} finally {
JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
if (unit != null) {
unit.cleanUp();
}
}
return this.ast;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
protected void closing(Object info) throws JavaModelException {
ClassFileInfo cfi = getClassFileInfo();
cfi.removeBinaryChildren();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,ICompletionRequestor requestor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,ICompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), owner);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, owner, null);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public void codeComplete(
char[] snippet,
int insertion,
int position,
char[][] localVariableTypeNames,
char[][] localVariableNames,
int[] localVariableModifiers,
boolean isStatic,
CompletionRequestor requestor,
WorkingCopyOwner owner,
IProgressMonitor monitor) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
JavaProject project = (JavaProject) getJavaProject();
SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);
CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
String source = getClassFile().getSource();
if (source != null && insertion > -1 && insertion < source.length()) {
// code complete
char[] prefix = CharOperation.concat(source.substring(0, insertion).toCharArray(), new char[]{'{'});
char[] suffix = CharOperation.concat(new char[]{'}'}, source.substring(insertion).toCharArray());
char[] fakeSource = CharOperation.concat(prefix, snippet, suffix);
BasicCompilationUnit cu =
new BasicCompilationUnit(
fakeSource,
null,
getElementName(),
project); // use project to retrieve corresponding .java IFile
engine.complete(cu, prefix.length + position, prefix.length, null/*extended context isn't computed*/);
} else {
engine.complete(this, snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic);
}
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IAnnotation[] getAnnotations() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
IBinaryAnnotation[] binaryAnnotations = info.getAnnotations();
return getAnnotations(binaryAnnotations, info.getTagBits());
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IJavaElement[] getChildren() throws JavaModelException {
ClassFileInfo cfi = getClassFileInfo();
return cfi.binaryChildren;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IJavaElement[] getChildrenForCategory(String category) throws JavaModelException {
IJavaElement[] children = getChildren();
int length = children.length;
if (length == 0) return children;
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that categories are computed
((ClassFile)getClassFile()).getBuffer();
HashMap categories = mapper.categories;
IJavaElement[] result = new IJavaElement[length];
int index = 0;
if (categories != null) {
for (int i = 0; i < length; i++) {
IJavaElement child = children[i];
String[] cats = (String[]) categories.get(child);
if (cats != null) {
for (int j = 0, length2 = cats.length; j < length2; j++) {
if (cats[j].equals(category)) {
result[index++] = child;
break;
}
}
}
}
}
if (index < length)
System.arraycopy(result, 0, result = new IJavaElement[index], 0, index);
return result;
}
return NO_ELEMENTS;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
protected ClassFileInfo getClassFileInfo() throws JavaModelException {
ClassFile cf = (ClassFile)this.parent;
return (ClassFileInfo) cf.getElementInfo();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
Object info = manager.getInfo(this);
if (info != null && info != JavaModelCache.NON_EXISTING_JAR_TYPE_INFO) return info;
return openWhenClosed(createElementInfo(), monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IField[] getFields() throws JavaModelException {
ArrayList list = getChildrenOfType(FIELD);
int size;
if ((size = list.size()) == 0) {
return NO_FIELDS;
} else {
IField[] array= new IField[size];
list.toArray(array);
return array;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public int getFlags() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return info.getModifiers() & ~ClassFileConstants.AccSuper;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String getFullyQualifiedParameterizedName() throws JavaModelException {
return getFullyQualifiedName('.', true/*show parameters*/);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String getKey(boolean forceOpen) throws JavaModelException {
return getKey(this, forceOpen);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IMethod[] getMethods() throws JavaModelException {
ArrayList list = getChildrenOfType(METHOD);
int size;
if ((size = list.size()) == 0) {
return NO_METHODS;
} else {
IMethod[] array= new IMethod[size];
list.toArray(array);
return array;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String getSuperclassTypeSignature() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature != null) {
int signatureLength = genericSignature.length;
// skip type parameters
int index = 0;
if (genericSignature[0] == '<') {
int count = 1;
while (count > 0 && ++index < signatureLength) {
switch (genericSignature[index]) {
case '<':
count++;
break;
case '>':
count--;
break;
}
}
index++;
}
int start = index;
index = org.eclipse.jdt.internal.compiler.util.Util.scanClassTypeSignature(genericSignature, start) + 1;
char[] superclassSig = CharOperation.subarray(genericSignature, start, index);
return new String(ClassFile.translatedName(superclassSig));
} else {
char[] superclassName = info.getSuperclassName();
if (superclassName == null) {
return null;
}
return new String(Signature.createTypeSignature(ClassFile.translatedName(superclassName), true));
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String getSuperclassName() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
char[] superclassName = info.getSuperclassName();
if (superclassName == null) {
return null;
}
return new String(ClassFile.translatedName(superclassName));
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String[] getSuperInterfaceNames() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
char[][] names= info.getInterfaceNames();
int length;
if (names == null || (length = names.length) == 0) {
return CharOperation.NO_STRINGS;
}
names= ClassFile.translatedNames(names);
String[] strings= new String[length];
for (int i= 0; i < length; i++) {
strings[i]= new String(names[i]);
}
return strings;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String[] getSuperInterfaceTypeSignatures() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature != null) {
ArrayList interfaces = new ArrayList();
int signatureLength = genericSignature.length;
// skip type parameters
int index = 0;
if (genericSignature[0] == '<') {
int count = 1;
while (count > 0 && ++index < signatureLength) {
switch (genericSignature[index]) {
case '<':
count++;
break;
case '>':
count--;
break;
}
}
index++;
}
// skip superclass
index = org.eclipse.jdt.internal.compiler.util.Util.scanClassTypeSignature(genericSignature, index) + 1;
while (index < signatureLength) {
int start = index;
index = org.eclipse.jdt.internal.compiler.util.Util.scanClassTypeSignature(genericSignature, start) + 1;
char[] interfaceSig = CharOperation.subarray(genericSignature, start, index);
interfaces.add(new String(ClassFile.translatedName(interfaceSig)));
}
int size = interfaces.size();
String[] result = new String[size];
interfaces.toArray(result);
return result;
} else {
char[][] names= info.getInterfaceNames();
int length;
if (names == null || (length = names.length) == 0) {
return CharOperation.NO_STRINGS;
}
names= ClassFile.translatedNames(names);
String[] strings= new String[length];
for (int i= 0; i < length; i++) {
strings[i]= new String(Signature.createTypeSignature(names[i], true));
}
return strings;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeParameter[] getTypeParameters() throws JavaModelException {
String[] typeParameterSignatures = getTypeParameterSignatures();
int length = typeParameterSignatures.length;
if (length == 0) return TypeParameter.NO_TYPE_PARAMETERS;
ITypeParameter[] typeParameters = new ITypeParameter[length];
for (int i = 0; i < typeParameterSignatures.length; i++) {
String typeParameterName = Signature.getTypeVariable(typeParameterSignatures[i]);
typeParameters[i] = new TypeParameter(this, typeParameterName);
}
return typeParameters;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String[] getTypeParameterSignatures() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature == null)
return CharOperation.NO_STRINGS;
char[] dotBaseSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
char[][] typeParams = Signature.getTypeParameters(dotBaseSignature);
return CharOperation.toStrings(typeParams);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public IType[] getTypes() throws JavaModelException {
ArrayList list = getChildrenOfType(TYPE);
int size;
if ((size = list.size()) == 0) {
return NO_TYPES;
} else {
IType[] array= new IType[size];
list.toArray(array);
return array;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isAnonymous() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return info.isAnonymous();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isClass() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isEnum() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.ENUM_DECL;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isInterface() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
switch (TypeDeclaration.kind(info.getModifiers())) {
case TypeDeclaration.INTERFACE_DECL:
case TypeDeclaration.ANNOTATION_TYPE_DECL: // annotation is interface too
return true;
}
return false;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isAnnotation() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.ANNOTATION_TYPE_DECL;
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isLocal() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return info.isLocal();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public boolean isMember() throws JavaModelException {
IBinaryType info = (IBinaryType) getElementInfo();
return info.isMember();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaModelException {
return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
return TypeHierarchy.load(this, input, owner);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newSupertypeHierarchy(
ICompilationUnit[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newSupertypeHierarchy(
IWorkingCopy[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] copies;
if (workingCopies == null) {
copies = null;
} else {
int length = workingCopies.length;
System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length);
}
return newSupertypeHierarchy(copies, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newSupertypeHierarchy(
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException {
return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(IJavaProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
if (project == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullProject);
}
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
ICompilationUnit[] projectWCs = null;
if (workingCopies != null) {
int length = workingCopies.length;
projectWCs = new ICompilationUnit[length];
int index = 0;
for (int i = 0; i < length; i++) {
ICompilationUnit wc = workingCopies[i];
if (project.equals(wc.getJavaProject())) {
projectWCs[index++] = wc;
}
}
if (index != length) {
System.arraycopy(projectWCs, 0, projectWCs = new ICompilationUnit[index], 0, index);
}
}
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(
this,
projectWCs,
project,
true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=228845, consider any
// changes that may exist on primary working copies.
return newTypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(
ICompilationUnit[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(
IWorkingCopy[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] copies;
if (workingCopies == null) {
copies = null;
} else {
int length = workingCopies.length;
System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length);
}
return newTypeHierarchy(copies, monitor);
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public ITypeHierarchy newTypeHierarchy(
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
JavadocContents javadocContents = getJavadocContents(monitor);
if (javadocContents == null) return null;
return javadocContents.getTypeDoc();
}
// in model/org/eclipse/jdt/internal/core/BinaryType.java
public JavadocContents getJavadocContents(IProgressMonitor monitor) throws JavaModelException {
PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(getJavaProject().getProject());
JavadocContents cachedJavadoc = null;
synchronized (projectInfo.javadocCache) {
cachedJavadoc = (JavadocContents) projectInfo.javadocCache.get(this);
}
if (cachedJavadoc != null && cachedJavadoc != EMPTY_JAVADOC) {
return cachedJavadoc;
}
URL baseLocation= getJavadocBaseLocation();
if (baseLocation == null) {
return null;
}
StringBuffer pathBuffer = new StringBuffer(baseLocation.toExternalForm());
if (!(pathBuffer.charAt(pathBuffer.length() - 1) == '/')) {
pathBuffer.append('/');
}
IPackageFragment pack= getPackageFragment();
String typeQualifiedName = null;
if (isMember()) {
IType currentType = this;
StringBuffer typeName = new StringBuffer();
while (currentType != null) {
typeName.insert(0, currentType.getElementName());
currentType = currentType.getDeclaringType();
if (currentType != null) {
typeName.insert(0, '.');
}
}
typeQualifiedName = new String(typeName.toString());
} else {
typeQualifiedName = getElementName();
}
pathBuffer.append(pack.getElementName().replace('.', '/')).append('/').append(typeQualifiedName).append(JavadocConstants.HTML_EXTENSION);
if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
final String contents = getURLContents(String.valueOf(pathBuffer));
JavadocContents javadocContents = new JavadocContents(this, contents);
synchronized (projectInfo.javadocCache) {
projectInfo.javadocCache.put(this, javadocContents);
}
return javadocContents;
}
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
private void addPackageFragmentRoot(OpenableElementInfo parent, IPackageFragmentRoot child)
throws JavaModelException {
IJavaElement[] roots = parent.getChildren();
if (roots.length > 0) {
IClasspathEntry[] resolvedClasspath = ((JavaProject) child.getJavaProject()).getResolvedClasspath();
IPath currentEntryPath = child.getResolvedClasspathEntry().getPath();
int indexToInsert = -1;
int lastComparedIndex = -1;
int i = 0, j = 0;
for (; i < roots.length && j < resolvedClasspath.length;) {
IClasspathEntry classpathEntry = resolvedClasspath[j];
if (lastComparedIndex != j && currentEntryPath.equals(classpathEntry.getPath())) {
indexToInsert = i;
break;
}
lastComparedIndex = j;
IClasspathEntry rootEntry = ((IPackageFragmentRoot) roots[i]).getResolvedClasspathEntry();
if (rootEntry.getPath().equals(classpathEntry.getPath()))
i++;
else
j++;
}
for (; i < roots.length; i++) {
// If the new root is already among the children, no need to proceed further. Just return.
if (roots[i].equals(child)) {
return;
}
// If we start seeing root's classpath entry different from the child's entry, then the child can't
// be present further down the roots array.
if (!((IPackageFragmentRoot) roots[i]).getResolvedClasspathEntry().getPath()
.equals(currentEntryPath))
break;
}
if (indexToInsert >= 0) {
int newSize = roots.length + 1;
IPackageFragmentRoot[] newChildren = new IPackageFragmentRoot[newSize];
if (indexToInsert > 0)
System.arraycopy(roots, 0, newChildren, 0, indexToInsert);
newChildren[indexToInsert] = child;
System.arraycopy(roots, indexToInsert, newChildren, indexToInsert + 1, (newSize - indexToInsert - 1));
parent.setChildren(newChildren);
return;
}
}
parent.addChild(child);
}
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
public void checkExternalArchiveChanges(IJavaElement[] elementsScope, IProgressMonitor monitor) throws JavaModelException {
checkExternalArchiveChanges(elementsScope, false, monitor);
}
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
private void checkExternalArchiveChanges(IJavaElement[] elementsScope, boolean asynchronous, IProgressMonitor monitor) throws JavaModelException {
if (monitor != null && monitor.isCanceled())
throw new OperationCanceledException();
try {
if (monitor != null) monitor.beginTask("", 1); //$NON-NLS-1$
boolean hasExternalWorkingCopyProject = false;
for (int i = 0, length = elementsScope.length; i < length; i++) {
IJavaElement element = elementsScope[i];
this.state.addForRefresh(elementsScope[i]);
if (element.getElementType() == IJavaElement.JAVA_MODEL) {
// ensure external working copies' projects' caches are reset
HashSet projects = JavaModelManager.getJavaModelManager().getExternalWorkingCopyProjects();
if (projects != null) {
hasExternalWorkingCopyProject = true;
Iterator iterator = projects.iterator();
while (iterator.hasNext()) {
JavaProject project = (JavaProject) iterator.next();
project.resetCaches();
}
}
}
}
HashSet elementsToRefresh = this.state.removeExternalElementsToRefresh();
boolean hasDelta = elementsToRefresh != null && createExternalArchiveDelta(elementsToRefresh, monitor);
if (hasDelta){
IJavaElementDelta[] projectDeltas = this.currentDelta.getAffectedChildren();
final int length = projectDeltas.length;
final IProject[] projectsToTouch = new IProject[length];
for (int i = 0; i < length; i++) {
IJavaElementDelta delta = projectDeltas[i];
JavaProject javaProject = (JavaProject)delta.getElement();
projectsToTouch[i] = javaProject.getProject();
}
if (projectsToTouch.length > 0) {
if (asynchronous){
WorkspaceJob touchJob = new WorkspaceJob(Messages.updating_external_archives_jobName) {
public IStatus runInWorkspace(IProgressMonitor progressMonitor) throws CoreException {
try {
if (progressMonitor != null)
progressMonitor.beginTask("", projectsToTouch.length); //$NON-NLS-1$
touchProjects(projectsToTouch, progressMonitor);
}
finally {
if (progressMonitor != null)
progressMonitor.done();
}
return Status.OK_STATUS;
}
public boolean belongsTo(Object family) {
return ResourcesPlugin.FAMILY_MANUAL_REFRESH == family;
}
};
touchJob.schedule();
}
else {
// touch the projects to force them to be recompiled while taking the workspace lock
// so that there is no concurrency with the Java builder
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96575
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
public void run(IProgressMonitor progressMonitor) throws CoreException {
for (int i = 0; i < projectsToTouch.length; i++) {
IProject project = projectsToTouch[i];
// touch to force a build of this project
if (JavaBuilder.DEBUG)
System.out.println("Touching project " + project.getName() + " due to external jar file change"); //$NON-NLS-1$ //$NON-NLS-2$
project.touch(progressMonitor);
}
}
};
try {
ResourcesPlugin.getWorkspace().run(runnable, monitor);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
}
if (this.currentDelta != null) { // if delta has not been fired while creating markers
fire(this.currentDelta, DEFAULT_CHANGE_EVENT);
}
} else if (hasExternalWorkingCopyProject) {
// flush jar type cache
JavaModelManager.getJavaModelManager().resetJarTypeCache();
}
} finally {
this.currentDelta = null;
if (monitor != null) monitor.done();
}
}
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
private void nonJavaResourcesChanged(Openable element, IResourceDelta delta) throws JavaModelException {
// reset non-java resources if element was open
if (element.isOpen()) {
JavaElementInfo info = (JavaElementInfo)element.getElementInfo();
switch (element.getElementType()) {
case IJavaElement.JAVA_MODEL :
((JavaModelInfo) info).nonJavaResources = null;
if (!ExternalFoldersManager.isInternalPathForExternalFolder(delta.getFullPath()))
currentDelta().addResourceDelta(delta);
return;
case IJavaElement.JAVA_PROJECT :
((JavaProjectElementInfo) info).setNonJavaResources(null);
// if a package fragment root is the project, clear it too
JavaProject project = (JavaProject) element;
PackageFragmentRoot projectRoot =
(PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject());
if (projectRoot.isOpen()) {
((PackageFragmentRootInfo) projectRoot.getElementInfo()).setNonJavaResources(null);
}
break;
case IJavaElement.PACKAGE_FRAGMENT :
((PackageFragmentInfo) info).setNonJavaResources(null);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
((PackageFragmentRootInfo) info).setNonJavaResources(null);
}
}
JavaElementDelta current = currentDelta();
JavaElementDelta elementDelta = current.find(element);
if (elementDelta == null) {
// don't use find after creating the delta as it can be null (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63434)
elementDelta = current.changed(element, IJavaElementDelta.F_CONTENT);
}
if (!ExternalFoldersManager.isInternalPathForExternalFolder(delta.getFullPath()))
elementDelta.addResourceDelta(delta);
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void applyTextEdit(ICompilationUnit cu, TextEdit edits) throws JavaModelException {
try {
edits.apply(getDocument(cu));
} catch (BadLocationException e) {
// content changed under us
throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void copyResources(IResource[] resources, IPath container) throws JavaModelException {
IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
try {
for (int i = 0, length = resources.length; i < length; i++) {
IResource resource = resources[i];
IPath destination = container.append(resource.getName());
if (root.findMember(destination) == null) {
resource.copy(destination, false, subProgressMonitor);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void createFile(IContainer folder, String name, InputStream contents, boolean forceFlag) throws JavaModelException {
IFile file= folder.getFile(new Path(name));
try {
file.create(
contents,
forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void createFolder(IContainer parentFolder, String name, boolean forceFlag) throws JavaModelException {
IFolder folder= parentFolder.getFolder(new Path(name));
try {
// we should use true to create the file locally. Only VCM should use tru/false
folder.create(
forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
true, // local
getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void deleteEmptyPackageFragment(
IPackageFragment fragment,
boolean forceFlag,
IResource rootResource)
throws JavaModelException {
IContainer resource = (IContainer) ((JavaElement)fragment).resource();
try {
resource.delete(
forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
while (resource instanceof IFolder) {
// deleting a package: delete the parent if it is empty (e.g. deleting x.y where folder x doesn't have resources but y)
// without deleting the package fragment root
resource = resource.getParent();
if (!resource.equals(rootResource) && resource.members().length == 0) {
resource.delete(
forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
}
}
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void deleteResource(IResource resource,int flags) throws JavaModelException {
try {
resource.delete(flags, getSubProgressMonitor(1));
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void deleteResources(IResource[] resources, boolean forceFlag) throws JavaModelException {
if (resources == null || resources.length == 0) return;
IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
IWorkspace workspace = resources[0].getWorkspace();
try {
workspace.delete(
resources,
forceFlag ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
subProgressMonitor);
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
public void executeNestedOperation(JavaModelOperation operation, int subWorkAmount) throws JavaModelException {
IJavaModelStatus status= operation.verify();
if (!status.isOK()) {
throw new JavaModelException(status);
}
IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
// fix for 1FW7IKC, part (1)
try {
operation.setNested(true);
operation.run(subProgressMonitor);
} catch (CoreException ce) {
if (ce instanceof JavaModelException) {
throw (JavaModelException)ce;
} else {
// translate the core exception to a java model exception
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e = ce.getStatus().getException();
if (e instanceof JavaModelException) {
throw (JavaModelException) e;
}
}
throw new JavaModelException(ce);
}
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected IDocument getDocument(ICompilationUnit cu) throws JavaModelException {
IBuffer buffer = cu.getBuffer();
if (buffer instanceof IDocument)
return (IDocument) buffer;
return new DocumentAdapter(buffer);
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected IPath[] getNestedFolders(IPackageFragmentRoot root) throws JavaModelException {
IPath rootPath = root.getPath();
IClasspathEntry[] classpath = root.getJavaProject().getRawClasspath();
int length = classpath.length;
IPath[] result = new IPath[length];
int index = 0;
for (int i = 0; i < length; i++) {
IPath path = classpath[i].getPath();
if (rootPath.isPrefixOf(path) && !rootPath.equals(path)) {
result[index++] = path;
}
}
if (index < length) {
System.arraycopy(result, 0, result = new IPath[index], 0, index);
}
return result;
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void moveResources(IResource[] resources, IPath container) throws JavaModelException {
IProgressMonitor subProgressMonitor = null;
if (this.progressMonitor != null) {
subProgressMonitor = new SubProgressMonitor(this.progressMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
try {
for (int i = 0, length = resources.length; i < length; i++) {
IResource resource = resources[i];
IPath destination = container.append(resource.getName());
if (root.findMember(destination) == null) {
resource.move(destination, false, subProgressMonitor);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
public void runOperation(IProgressMonitor monitor) throws JavaModelException {
IJavaModelStatus status= verify();
if (!status.isOK()) {
throw new JavaModelException(status);
}
try {
if (isReadOnly()) {
run(monitor);
} else {
// Use IWorkspace.run(...) to ensure that resource changes are batched
// Note that if the tree is locked, this will throw a CoreException, but this is ok
// as this operation is modifying the tree (not read-only) and a CoreException will be thrown anyway.
ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor);
}
} catch (CoreException ce) {
if (ce instanceof JavaModelException) {
throw (JavaModelException)ce;
} else {
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e= ce.getStatus().getException();
if (e instanceof JavaModelException) {
throw (JavaModelException) e;
}
}
throw new JavaModelException(ce);
}
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
protected void runPostActions() throws JavaModelException {
while (this.actionsStart <= this.actionsEnd) {
IPostAction postAction = this.actions[this.actionsStart++];
if (POST_ACTION_VERBOSE) {
System.out.println("(" + Thread.currentThread() + ") [JavaModelOperation.runPostActions()] Running action " + postAction.getID()); //$NON-NLS-1$ //$NON-NLS-2$
}
postAction.run();
}
}
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
protected void executeOperation() throws JavaModelException {
IPackageFragmentRoot root = (IPackageFragmentRoot)getElementToProcess();
IClasspathEntry rootEntry = root.getRawClasspathEntry();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
// copy resource
if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
copyResource(root, rootEntry, workspaceRoot);
}
// update classpath if needed
if ((this.updateModelFlags & IPackageFragmentRoot.DESTINATION_PROJECT_CLASSPATH) != 0) {
addEntryToClasspath(rootEntry, workspaceRoot);
}
}
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
protected void copyResource(
IPackageFragmentRoot root,
IClasspathEntry rootEntry,
final IWorkspaceRoot workspaceRoot)
throws JavaModelException {
final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
IResource rootResource = ((JavaElement) root).resource();
if (root.getKind() == IPackageFragmentRoot.K_BINARY || exclusionPatterns == null) {
try {
IResource destRes;
if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0) {
if (rootEntry.getPath().equals(this.destination)) return;
if ((destRes = workspaceRoot.findMember(this.destination)) != null) {
destRes.delete(this.updateResourceFlags, this.progressMonitor);
}
}
rootResource.copy(this.destination, this.updateResourceFlags, this.progressMonitor);
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else {
final int sourceSegmentCount = rootEntry.getPath().segmentCount();
final IFolder destFolder = workspaceRoot.getFolder(this.destination);
final IPath[] nestedFolders = getNestedFolders(root);
IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
public boolean visit(IResourceProxy proxy) throws CoreException {
if (proxy.getType() == IResource.FOLDER) {
IPath path = proxy.requestFullPath();
if (prefixesOneOf(path, nestedFolders)) {
if (equalsOneOf(path, nestedFolders)) {
// nested source folder
return false;
} else {
// folder containing nested source folder
IFolder folder = destFolder.getFolder(path.removeFirstSegments(sourceSegmentCount));
if ((CopyPackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& folder.exists()) {
return true;
}
folder.create(CopyPackageFragmentRootOperation.this.updateResourceFlags, true, CopyPackageFragmentRootOperation.this.progressMonitor);
return true;
}
} else {
// subtree doesn't contain any nested source folders
IPath destPath = CopyPackageFragmentRootOperation.this.destination.append(path.removeFirstSegments(sourceSegmentCount));
IResource destRes;
if ((CopyPackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& (destRes = workspaceRoot.findMember(destPath)) != null) {
destRes.delete(CopyPackageFragmentRootOperation.this.updateResourceFlags, CopyPackageFragmentRootOperation.this.progressMonitor);
}
proxy.requestResource().copy(destPath, CopyPackageFragmentRootOperation.this.updateResourceFlags, CopyPackageFragmentRootOperation.this.progressMonitor);
return false;
}
} else {
IPath path = proxy.requestFullPath();
IPath destPath = CopyPackageFragmentRootOperation.this.destination.append(path.removeFirstSegments(sourceSegmentCount));
IResource destRes;
if ((CopyPackageFragmentRootOperation.this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0
&& (destRes = workspaceRoot.findMember(destPath)) != null) {
destRes.delete(CopyPackageFragmentRootOperation.this.updateResourceFlags, CopyPackageFragmentRootOperation.this.progressMonitor);
}
proxy.requestResource().copy(destPath, CopyPackageFragmentRootOperation.this.updateResourceFlags, CopyPackageFragmentRootOperation.this.progressMonitor);
return false;
}
}
};
try {
rootResource.accept(visitor, IResource.NONE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
}
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
protected void addEntryToClasspath(IClasspathEntry rootEntry, IWorkspaceRoot workspaceRoot) throws JavaModelException {
IProject destProject = workspaceRoot.getProject(this.destination.segment(0));
IJavaProject jProject = JavaCore.create(destProject);
IClasspathEntry[] classpath = jProject.getRawClasspath();
int length = classpath.length;
IClasspathEntry[] newClasspath;
// case of existing entry and REPLACE was specified
if ((this.updateModelFlags & IPackageFragmentRoot.REPLACE) != 0) {
// find existing entry
for (int i = 0; i < length; i++) {
if (this.destination.equals(classpath[i].getPath())) {
newClasspath = new IClasspathEntry[length];
System.arraycopy(classpath, 0, newClasspath, 0, length);
newClasspath[i] = copy(rootEntry);
jProject.setRawClasspath(newClasspath, this.progressMonitor);
return;
}
}
}
// other cases
int position;
if (this.sibling == null) {
// insert at the end
position = length;
} else {
// insert before sibling
position = -1;
for (int i = 0; i < length; i++) {
if (this.sibling.equals(classpath[i])) {
position = i;
break;
}
}
}
if (position == -1) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_SIBLING, this.sibling.toString()));
}
newClasspath = new IClasspathEntry[length+1];
if (position != 0) {
System.arraycopy(classpath, 0, newClasspath, 0, position);
}
if (position != length) {
System.arraycopy(classpath, position, newClasspath, position+1, length-position);
}
IClasspathEntry newEntry = copy(rootEntry);
newClasspath[position] = newEntry;
jProject.setRawClasspath(newClasspath, this.progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
protected IClasspathEntry copy(IClasspathEntry entry) throws JavaModelException {
switch (entry.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
return JavaCore.newContainerEntry(entry.getPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
case IClasspathEntry.CPE_LIBRARY:
try {
return JavaCore.newLibraryEntry(this.destination, entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
} catch (ClasspathEntry.AssertionFailedException e) {
IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
throw new JavaModelException(status);
}
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(entry.getPath(), entry.getAccessRules(), entry.combineAccessRules(), entry.getExtraAttributes(), entry.isExported());
case IClasspathEntry.CPE_SOURCE:
return JavaCore.newSourceEntry(this.destination, entry.getInclusionPatterns(), entry.getExclusionPatterns(), entry.getOutputLocation(), entry.getExtraAttributes());
case IClasspathEntry.CPE_VARIABLE:
try {
return JavaCore.newVariableEntry(entry.getPath(), entry.getSourceAttachmentPath(), entry.getSourceAttachmentRootPath(), entry.getAccessRules(), entry.getExtraAttributes(), entry.isExported());
} catch (ClasspathEntry.AssertionFailedException e) {
IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
throw new JavaModelException(status);
}
default:
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, getElementToProcess()));
}
}
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
private void collectAllSubfolders(IFolder folder, ArrayList collection) throws JavaModelException {
try {
IResource[] members= folder.members();
for (int i = 0, max = members.length; i < max; i++) {
IResource r= members[i];
if (r.getType() == IResource.FOLDER) {
collection.add(r);
collectAllSubfolders((IFolder)r, collection);
}
}
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
private ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException {
ArrayList fragments = new ArrayList();
// see if this will cause any package fragments to be affected
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResource resource = null;
if (location != null) {
resource = workspace.getRoot().findMember(location);
}
if (resource != null && resource.getType() == IResource.FOLDER) {
IFolder folder = (IFolder) resource;
// only changes if it actually existed
IClasspathEntry[] classpath = this.project.getExpandedClasspath();
for (int i = 0; i < classpath.length; i++) {
IClasspathEntry entry = classpath[i];
IPath path = classpath[i].getPath();
if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
IPackageFragmentRoot[] roots = this.project.computePackageFragmentRoots(classpath[i]);
PackageFragmentRoot root = (PackageFragmentRoot) roots[0];
// now the output location becomes a package fragment - along with any subfolders
ArrayList folders = new ArrayList();
folders.add(folder);
collectAllSubfolders(folder, folders);
Iterator elements = folders.iterator();
int segments = path.segmentCount();
while (elements.hasNext()) {
IFolder f = (IFolder) elements.next();
IPath relativePath = f.getFullPath().removeFirstSegments(segments);
String[] pkgName = relativePath.segments();
IPackageFragment pkg = root.getPackageFragment(pkgName);
if (!Util.isExcluded(pkg))
fragments.add(pkg);
}
}
}
}
return fragments;
}
// in model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
ASTNode node = super.generateElementAST(rewriter, cu);
if (!(node instanceof AbstractTypeDeclaration))
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
return node;
}
// in model/org/eclipse/jdt/internal/core/SetClasspathOperation.java
protected void executeOperation() throws JavaModelException {
checkCanceled();
try {
// set raw classpath and null out resolved info
PerProjectInfo perProjectInfo = this.project.getPerProjectInfo();
ClasspathChange classpathChange = perProjectInfo.setRawClasspath(this.newRawClasspath, this.referencedEntries, this.newOutputLocation, JavaModelStatus.VERIFIED_OK/*format is ok*/);
// if needed, generate delta, update project ref, create markers, ...
classpathChanged(classpathChange, true/*refresh if external linked folder already exists*/);
// write .classpath file
if (this.canChangeResources && perProjectInfo.writeAndCacheClasspath(this.project, this.newRawClasspath, this.newOutputLocation))
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
void removeBinaryChildren() throws JavaModelException {
if (this.binaryChildren != null) {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
for (int i = 0; i <this.binaryChildren.length; i++) {
JavaElement child = this.binaryChildren[i];
if (child instanceof BinaryType) {
manager.removeInfoAndChildren((JavaElement)child.getParent());
} else {
manager.removeInfoAndChildren(child);
}
}
this.binaryChildren = JavaElement.NO_ELEMENTS;
}
if (this.typeParameters != null) {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
for (int i = 0; i <this.typeParameters.length; i++) {
TypeParameter typeParameter = (TypeParameter) this.typeParameters[i];
manager.removeInfoAndChildren(typeParameter);
}
this.typeParameters = TypeParameter.NO_TYPE_PARAMETERS;
}
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, ICompletionRequestor requestor) throws JavaModelException {
codeComplete(codeSnippet, position, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, ICompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
codeComplete(codeSnippet, position, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), owner);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, CompletionRequestor requestor) throws JavaModelException {
codeComplete(codeSnippet, position, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, CompletionRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
codeComplete(codeSnippet, position, requestor, DefaultWorkingCopyOwner.PRIMARY, null);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
codeComplete(codeSnippet, position, requestor, owner, null);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(
String codeSnippet,
int position,
CompletionRequestor requestor,
WorkingCopyOwner owner,
IProgressMonitor monitor) throws JavaModelException {
SearchableEnvironment environment = this.project.newSearchableNameEnvironment(owner);
this.context.complete(
codeSnippet.toCharArray(),
position,
environment,
requestor,
this.project.getOptions(true),
this.project,
owner,
monitor
);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public IJavaElement[] codeSelect(String codeSnippet, int offset, int length) throws JavaModelException {
return codeSelect(codeSnippet, offset, length, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public IJavaElement[] codeSelect(String codeSnippet, int offset, int length, WorkingCopyOwner owner) throws JavaModelException {
SearchableEnvironment environment = this.project.newSearchableNameEnvironment(owner);
SelectionRequestor requestor= new SelectionRequestor(environment.nameLookup, null); // null because there is no need to look inside the code snippet itself
this.context.select(
codeSnippet.toCharArray(),
offset,
offset + length - 1,
environment,
requestor,
this.project.getOptions(true),
owner
);
return requestor.getElements();
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void evaluateCodeSnippet(
String codeSnippet,
String[] localVariableTypeNames,
String[] localVariableNames,
int[] localVariableModifiers,
IType declaringType,
boolean isStatic,
boolean isConstructorCall,
ICodeSnippetRequestor requestor,
IProgressMonitor progressMonitor) throws org.eclipse.jdt.core.JavaModelException {
checkBuilderState();
int length = localVariableTypeNames.length;
char[][] varTypeNames = new char[length][];
for (int i = 0; i < length; i++){
varTypeNames[i] = localVariableTypeNames[i].toCharArray();
}
length = localVariableNames.length;
char[][] varNames = new char[length][];
for (int i = 0; i < length; i++){
varNames[i] = localVariableNames[i].toCharArray();
}
Map options = this.project.getOptions(true);
// transfer the imports of the IType to the evaluation context
if (declaringType != null) {
// retrieves the package statement
this.context.setPackageName(declaringType.getPackageFragment().getElementName().toCharArray());
ICompilationUnit compilationUnit = declaringType.getCompilationUnit();
if (compilationUnit != null) {
// retrieves the import statement
IImportDeclaration[] imports = compilationUnit.getImports();
int importsLength = imports.length;
if (importsLength != 0) {
char[][] importsNames = new char[importsLength][];
for (int i = 0; i < importsLength; i++) {
importsNames[i] = imports[i].getElementName().toCharArray();
}
this.context.setImports(importsNames);
// turn off import complaints for implicitly added ones
options.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
}
} else {
// try to retrieve imports from the source
SourceMapper sourceMapper = ((ClassFile) declaringType.getClassFile()).getSourceMapper();
if (sourceMapper != null) {
char[][] imports = sourceMapper.getImports((BinaryType) declaringType);
if (imports != null) {
this.context.setImports(imports);
// turn off import complaints for implicitly added ones
options.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
}
}
}
}
INameEnvironment environment = null;
try {
this.context.evaluate(
codeSnippet.toCharArray(),
varTypeNames,
varNames,
localVariableModifiers,
declaringType == null? null : declaringType.getFullyQualifiedName().toCharArray(),
isStatic,
isConstructorCall,
environment = getBuildNameEnvironment(),
options,
getInfrastructureEvaluationRequestor(requestor),
getProblemFactory());
} catch (InstallException e) {
handleInstallException(e);
} finally {
if (environment != null) environment.cleanup();
}
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void evaluateCodeSnippet(String codeSnippet, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {
checkBuilderState();
INameEnvironment environment = null;
try {
this.context.evaluate(
codeSnippet.toCharArray(),
environment = getBuildNameEnvironment(),
this.project.getOptions(true),
getInfrastructureEvaluationRequestor(requestor),
getProblemFactory());
} catch (InstallException e) {
handleInstallException(e);
} finally {
if (environment != null) environment.cleanup();
}
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void evaluateVariable(IGlobalVariable variable, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {
checkBuilderState();
INameEnvironment environment = null;
try {
this.context.evaluateVariable(
((GlobalVariableWrapper)variable).variable,
environment = getBuildNameEnvironment(),
this.project.getOptions(true),
getInfrastructureEvaluationRequestor(requestor),
getProblemFactory());
} catch (InstallException e) {
handleInstallException(e);
} finally {
if (environment != null) environment.cleanup();
}
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
protected void handleInstallException(InstallException e) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.EVALUATION_ERROR, e.toString()));
}
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void codeComplete(String codeSnippet, int position, final org.eclipse.jdt.core.ICodeCompletionRequestor requestor) throws JavaModelException {
if (requestor == null){
codeComplete(codeSnippet, position, (ICompletionRequestor)null);
return;
}
codeComplete(
codeSnippet,
position,
new ICompletionRequestor(){
public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
// implements interface method
}
public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
}
public void acceptError(IProblem error) {
// was disabled in 1.0
}
public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
requestor.acceptKeyword(keywordName, completionStart, completionEnd);
}
public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
requestor.acceptLabel(labelName, completionStart, completionEnd);
}
public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// skip parameter names
requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
requestor.acceptModifier(modifierName, completionStart, completionEnd);
}
public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
}
public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
}
public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance){
// ignore
}
});
}
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
public void updateExternalFoldersIfNecessary(boolean refreshIfExistAlready, IProgressMonitor monitor) throws JavaModelException {
HashSet oldFolders = ExternalFoldersManager.getExternalFolders(this.oldResolvedClasspath);
IClasspathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
HashSet newFolders = ExternalFoldersManager.getExternalFolders(newResolvedClasspath);
if (newFolders == null)
return;
ExternalFoldersManager foldersManager = JavaModelManager.getExternalManager();
Iterator iterator = newFolders.iterator();
while (iterator.hasNext()) {
Object folderPath = iterator.next();
if (oldFolders == null || !oldFolders.remove(folderPath) || foldersManager.removePendingFolder(folderPath)) {
try {
foldersManager.createLinkFolder((IPath) folderPath, refreshIfExistAlready, monitor);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
}
// removal of linked folders is done during save
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
private void appendTypeParameters(StringBuffer buffer) throws JavaModelException {
ITypeParameter[] typeParameters = getTypeParameters();
int length = typeParameters.length;
if (length == 0) return;
buffer.append('<');
for (int i = 0; i < length; i++) {
ITypeParameter typeParameter = typeParameters[i];
buffer.append(typeParameter.getElementName());
String[] bounds = typeParameter.getBounds();
int boundsLength = bounds.length;
if (boundsLength > 0) {
buffer.append(" extends "); //$NON-NLS-1$
for (int j = 0; j < boundsLength; j++) {
buffer.append(bounds[j]);
if (j < boundsLength-1)
buffer.append(" & "); //$NON-NLS-1$
}
}
if (i < length-1)
buffer.append(", "); //$NON-NLS-1$
}
buffer.append('>');
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
protected String getKey(IField field, boolean forceOpen) throws JavaModelException {
StringBuffer key = new StringBuffer();
// declaring class
String declaringKey = getKey((IType) field.getParent(), forceOpen);
key.append(declaringKey);
// field name
key.append('.');
key.append(field.getElementName());
return key.toString();
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
protected String getKey(IMethod method, boolean forceOpen) throws JavaModelException {
StringBuffer key = new StringBuffer();
// declaring class
String declaringKey = getKey((IType) method.getParent(), forceOpen);
key.append(declaringKey);
// selector
key.append('.');
String selector = method.getElementName();
key.append(selector);
// type parameters
if (forceOpen) {
ITypeParameter[] typeParameters = method.getTypeParameters();
int length = typeParameters.length;
if (length > 0) {
key.append('<');
for (int i = 0; i < length; i++) {
ITypeParameter typeParameter = typeParameters[i];
String[] bounds = typeParameter.getBounds();
int boundsLength = bounds.length;
char[][] boundSignatures = new char[boundsLength][];
for (int j = 0; j < boundsLength; j++) {
boundSignatures[j] = Signature.createCharArrayTypeSignature(bounds[j].toCharArray(), method.isBinary());
CharOperation.replace(boundSignatures[j], '.', '/');
}
char[] sig = Signature.createTypeParameterSignature(typeParameter.getElementName().toCharArray(), boundSignatures);
key.append(sig);
}
key.append('>');
}
}
// parameters
key.append('(');
String[] parameters = method.getParameterTypes();
for (int i = 0, length = parameters.length; i < length; i++)
key.append(parameters[i].replace('.', '/'));
key.append(')');
// return type
if (forceOpen)
key.append(method.getReturnType().replace('.', '/'));
else
key.append('V');
return key.toString();
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
protected String getKey(IType type, boolean forceOpen) throws JavaModelException {
StringBuffer key = new StringBuffer();
key.append('L');
String packageName = type.getPackageFragment().getElementName();
key.append(packageName.replace('.', '/'));
if (packageName.length() > 0)
key.append('/');
String typeQualifiedName = type.getTypeQualifiedName('$');
ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
String cuName = cu.getElementName();
String mainTypeName = cuName.substring(0, cuName.lastIndexOf('.'));
int end = typeQualifiedName.indexOf('$');
if (end == -1)
end = typeQualifiedName.length();
String topLevelTypeName = typeQualifiedName.substring(0, end);
if (!mainTypeName.equals(topLevelTypeName)) {
key.append(mainTypeName);
key.append('~');
}
}
key.append(typeQualifiedName);
key.append(';');
return key.toString();
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
protected String getFullyQualifiedParameterizedName(String fullyQualifiedName, String uniqueKey) throws JavaModelException {
String[] typeArguments = new BindingKey(uniqueKey).getTypeArguments();
int length = typeArguments.length;
if (length == 0) return fullyQualifiedName;
StringBuffer buffer = new StringBuffer();
buffer.append(fullyQualifiedName);
buffer.append('<');
for (int i = 0; i < length; i++) {
String typeArgument = typeArguments[i];
buffer.append(Signature.toString(typeArgument));
if (i < length-1)
buffer.append(',');
}
buffer.append('>');
return buffer.toString();
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
public String getFullyQualifiedName(char enclosingTypeSeparator, boolean showParameters) throws JavaModelException {
String packageName = getPackageFragment().getElementName();
if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
return getTypeQualifiedName(enclosingTypeSeparator, showParameters);
}
return packageName + '.' + getTypeQualifiedName(enclosingTypeSeparator, showParameters);
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
public String getTypeQualifiedName(char enclosingTypeSeparator, boolean showParameters) throws JavaModelException {
NamedMember declaringType;
switch (this.parent.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
if (showParameters) {
StringBuffer buffer = new StringBuffer(this.name);
appendTypeParameters(buffer);
return buffer.toString();
}
return this.name;
case IJavaElement.CLASS_FILE:
String classFileName = this.parent.getElementName();
String typeName;
if (classFileName.indexOf('$') == -1) {
// top level class file: name of type is same as name of class file
typeName = this.name;
} else {
// anonymous or local class file
typeName = classFileName.substring(0, classFileName.lastIndexOf('.'))/*remove .class*/.replace('$', enclosingTypeSeparator);
}
if (showParameters) {
StringBuffer buffer = new StringBuffer(typeName);
appendTypeParameters(buffer);
return buffer.toString();
}
return typeName;
case IJavaElement.TYPE:
declaringType = (NamedMember) this.parent;
break;
case IJavaElement.FIELD:
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
declaringType = (NamedMember) ((IMember) this.parent).getDeclaringType();
break;
default:
return null;
}
StringBuffer buffer = new StringBuffer(declaringType.getTypeQualifiedName(enclosingTypeSeparator, showParameters));
buffer.append(enclosingTypeSeparator);
String simpleName = this.name.length() == 0 ? Integer.toString(this.occurrenceCount) : this.name;
buffer.append(simpleName);
if (showParameters) {
appendTypeParameters(buffer);
}
return buffer.toString();
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
protected ITypeParameter[] getTypeParameters() throws JavaModelException {
return null;
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
public String[][] resolveType(String typeName) throws JavaModelException {
return resolveType(typeName, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/NamedMember.java
public String[][] resolveType(String typeName, WorkingCopyOwner owner) throws JavaModelException {
JavaProject project = (JavaProject) getJavaProject();
SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);
class TypeResolveRequestor implements ISelectionRequestor {
String[][] answers = null;
public void acceptType(char[] packageName, char[] tName, int modifiers, boolean isDeclaration, char[] uniqueKey, int start, int end) {
String[] answer = new String[] {new String(packageName), new String(tName) };
if (this.answers == null) {
this.answers = new String[][]{ answer };
} else {
// grow
int length = this.answers.length;
System.arraycopy(this.answers, 0, this.answers = new String[length+1][], 0, length);
this.answers[length] = answer;
}
}
public void acceptError(CategorizedProblem error) {
// ignore
}
public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName, boolean isDeclaration, char[] uniqueKey, int start, int end) {
// ignore
}
public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, String enclosingDeclaringTypeSignature, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, String[] parameterSignatures, char[][] typeParameterNames, char[][][] typeParameterBoundNames, boolean isConstructor, boolean isDeclaration, char[] uniqueKey, int start, int end) {
// ignore
}
public void acceptPackage(char[] packageName){
// ignore
}
public void acceptTypeParameter(char[] declaringTypePackageName, char[] declaringTypeName, char[] typeParameterName, boolean isDeclaration, int start, int end) {
// ignore
}
public void acceptMethodTypeParameter(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, int selectorStart, int selcetorEnd, char[] typeParameterName, boolean isDeclaration, int start, int end) {
// ignore
}
}
TypeResolveRequestor requestor = new TypeResolveRequestor();
SelectionEngine engine =
new SelectionEngine(environment, requestor, project.getOptions(true), owner);
engine.selectType(typeName.toCharArray(), (IType) this);
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
return requestor.answers;
}
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
protected void executeOperation() throws JavaModelException {
IPackageFragmentRoot root = (IPackageFragmentRoot)getElementToProcess();
IClasspathEntry rootEntry = root.getRawClasspathEntry();
// remember olds roots
DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().getDeltaProcessor();
if (deltaProcessor.oldRoots == null)
deltaProcessor.oldRoots = new HashMap();
// update classpath if needed
if ((this.updateModelFlags & IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH) != 0) {
updateProjectClasspath(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
}
if ((this.updateModelFlags & IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_CLASSPATH) != 0) {
updateReferringProjectClasspaths(rootEntry.getPath(), root.getJavaProject(), deltaProcessor.oldRoots);
}
// delete resource
if (!root.isExternal() && (this.updateModelFlags & IPackageFragmentRoot.NO_RESOURCE_MODIFICATION) == 0) {
deleteResource(root, rootEntry);
}
}
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
protected void deleteResource(
IPackageFragmentRoot root,
IClasspathEntry rootEntry)
throws JavaModelException {
final char[][] exclusionPatterns = ((ClasspathEntry)rootEntry).fullExclusionPatternChars();
IResource rootResource = ((JavaElement) root).resource();
if (rootEntry.getEntryKind() != IClasspathEntry.CPE_SOURCE || exclusionPatterns == null) {
try {
rootResource.delete(this.updateResourceFlags, this.progressMonitor);
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else {
final IPath[] nestedFolders = getNestedFolders(root);
IResourceProxyVisitor visitor = new IResourceProxyVisitor() {
public boolean visit(IResourceProxy proxy) throws CoreException {
if (proxy.getType() == IResource.FOLDER) {
IPath path = proxy.requestFullPath();
if (prefixesOneOf(path, nestedFolders)) {
// equals if nested source folder
return !equalsOneOf(path, nestedFolders);
} else {
// subtree doesn't contain any nested source folders
proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
return false;
}
} else {
proxy.requestResource().delete(DeletePackageFragmentRootOperation.this.updateResourceFlags, DeletePackageFragmentRootOperation.this.progressMonitor);
return false;
}
}
};
try {
rootResource.accept(visitor, IResource.NONE);
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
}
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
protected void updateReferringProjectClasspaths(IPath rootPath, IJavaProject projectOfRoot, Map oldRoots) throws JavaModelException {
IJavaModel model = getJavaModel();
IJavaProject[] projects = model.getJavaProjects();
for (int i = 0, length = projects.length; i < length; i++) {
IJavaProject project = projects[i];
if (project.equals(projectOfRoot)) continue;
updateProjectClasspath(rootPath, project, oldRoots);
}
}
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
protected void updateProjectClasspath(IPath rootPath, IJavaProject project, Map oldRoots) throws JavaModelException {
// remember old roots
oldRoots.put(project, project.getPackageFragmentRoots());
IClasspathEntry[] classpath = project.getRawClasspath();
IClasspathEntry[] newClasspath = null;
int cpLength = classpath.length;
int newCPIndex = -1;
for (int j = 0; j < cpLength; j++) {
IClasspathEntry entry = classpath[j];
if (rootPath.equals(entry.getPath())) {
if (newClasspath == null) {
newClasspath = new IClasspathEntry[cpLength-1];
System.arraycopy(classpath, 0, newClasspath, 0, j);
newCPIndex = j;
}
} else if (newClasspath != null) {
newClasspath[newCPIndex++] = entry;
}
}
if (newClasspath != null) {
if (newCPIndex < newClasspath.length) {
System.arraycopy(newClasspath, 0, newClasspath = new IClasspathEntry[newCPIndex], 0, newCPIndex);
}
project.setRawClasspath(newClasspath, this.progressMonitor);
}
}
// in model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
super.verify(element);
int elementType = element.getElementType();
if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) {
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
if (elementType == IJavaElement.COMPILATION_UNIT) {
CompilationUnit cu = (CompilationUnit)element;
if (cu.isWorkingCopy() && !cu.isPrimary()) {
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
}
verifyRenaming(element);
}
// in model/org/eclipse/jdt/internal/core/Openable.java
protected void codeComplete(
org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu,
org.eclipse.jdt.internal.compiler.env.ICompilationUnit unitToSkip,
int position, CompletionRequestor requestor,
WorkingCopyOwner owner,
ITypeRoot typeRoot,
IProgressMonitor monitor) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
PerformanceStats performanceStats = CompletionEngine.PERF
? PerformanceStats.getStats(JavaModelManager.COMPLETION_PERF, this)
: null;
if(performanceStats != null) {
performanceStats.startRun(new String(cu.getFileName()) + " at " + position); //$NON-NLS-1$
}
IBuffer buffer = getBuffer();
if (buffer == null) {
return;
}
if (position < -1 || position > buffer.getLength()) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
}
JavaProject project = (JavaProject) getJavaProject();
SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);
// set unit to skip
environment.unitToSkip = unitToSkip;
// code complete
CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
engine.complete(cu, position, 0, typeRoot);
if(performanceStats != null) {
performanceStats.endRun();
}
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// in model/org/eclipse/jdt/internal/core/Openable.java
protected IJavaElement[] codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, WorkingCopyOwner owner) throws JavaModelException {
PerformanceStats performanceStats = SelectionEngine.PERF
? PerformanceStats.getStats(JavaModelManager.SELECTION_PERF, this)
: null;
if(performanceStats != null) {
performanceStats.startRun(new String(cu.getFileName()) + " at [" + offset + "," + length + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
JavaProject project = (JavaProject)getJavaProject();
SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);
SelectionRequestor requestor= new SelectionRequestor(environment.nameLookup, this);
IBuffer buffer = getBuffer();
if (buffer == null) {
return requestor.getElements();
}
int end= buffer.getLength();
if (offset < 0 || length < 0 || offset + length > end ) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
}
// fix for 1FVXGDK
SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true), owner);
engine.select(cu, offset, offset + length - 1);
if(performanceStats != null) {
performanceStats.endRun();
}
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
return requestor.getElements();
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public String findRecommendedLineSeparator() throws JavaModelException {
IBuffer buffer = getBuffer();
String source = buffer == null ? null : buffer.getContents();
return Util.getLineSeparator(source, getJavaProject());
}
// in model/org/eclipse/jdt/internal/core/Openable.java
protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
if (JavaModelCache.VERBOSE){
String element;
switch (getElementType()) {
case JAVA_PROJECT:
element = "project"; //$NON-NLS-1$
break;
case PACKAGE_FRAGMENT_ROOT:
element = "root"; //$NON-NLS-1$
break;
case PACKAGE_FRAGMENT:
element = "package"; //$NON-NLS-1$
break;
case CLASS_FILE:
element = "class file"; //$NON-NLS-1$
break;
case COMPILATION_UNIT:
element = "compilation unit"; //$NON-NLS-1$
break;
default:
element = "element"; //$NON-NLS-1$
}
System.out.println(Thread.currentThread() +" OPENING " + element + " " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
}
// open its ancestors if needed
openAncestors(newElements, monitor);
// validate existence
IResource underlResource = resource();
IStatus status = validateExistence(underlResource);
if (!status.isOK())
throw newJavaModelException(status);
if (monitor != null && monitor.isCanceled())
throw new OperationCanceledException();
// puts the info before building the structure so that questions to the handle behave as if the element existed
// (case of compilation units becoming working copies)
newElements.put(this, info);
// build the structure of the openable (this will open the buffer if needed)
try {
OpenableElementInfo openableElementInfo = (OpenableElementInfo)info;
boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, underlResource);
openableElementInfo.setIsStructureKnown(isStructureKnown);
} catch (JavaModelException e) {
newElements.remove(this);
throw e;
}
// remove out of sync buffer for this element
JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
if (JavaModelCache.VERBOSE) {
System.out.println(JavaModelManager.getJavaModelManager().cacheToString("-> ")); //$NON-NLS-1$
}
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public IBuffer getBuffer() throws JavaModelException {
if (hasBuffer()) {
// ensure element is open
Object info = getElementInfo();
IBuffer buffer = getBufferManager().getBuffer(this);
if (buffer == null) {
// try to (re)open a buffer
buffer = openBuffer(null, info);
}
if (buffer instanceof NullBuffer) {
return null;
}
return buffer;
} else {
return null;
}
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public IResource getCorrespondingResource() throws JavaModelException {
return getUnderlyingResource();
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public IResource getUnderlyingResource() throws JavaModelException {
IResource parentResource = this.parent.getUnderlyingResource();
if (parentResource == null) {
return null;
}
int type = parentResource.getType();
if (type == IResource.FOLDER || type == IResource.PROJECT) {
IContainer folder = (IContainer) parentResource;
IResource resource = folder.findMember(getElementName());
if (resource == null) {
throw newNotPresentException();
} else {
return resource;
}
} else {
return parentResource;
}
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public boolean hasUnsavedChanges() throws JavaModelException{
if (isReadOnly() || !isOpen()) {
return false;
}
IBuffer buf = getBuffer();
if (buf != null && buf.hasUnsavedChanges()) {
return true;
}
// for package fragments, package fragment roots, and projects must check open buffers
// to see if they have an child with unsaved changes
int elementType = getElementType();
if (elementType == PACKAGE_FRAGMENT ||
elementType == PACKAGE_FRAGMENT_ROOT ||
elementType == JAVA_PROJECT ||
elementType == JAVA_MODEL) { // fix for 1FWNMHH
Enumeration openBuffers= getBufferManager().getOpenBuffers();
while (openBuffers.hasMoreElements()) {
IBuffer buffer= (IBuffer)openBuffers.nextElement();
if (buffer.hasUnsavedChanges()) {
IJavaElement owner= (IJavaElement)buffer.getOwner();
if (isAncestorOf(owner)) {
return true;
}
}
}
}
return false;
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public boolean isStructureKnown() throws JavaModelException {
return ((OpenableElementInfo)getElementInfo()).isStructureKnown();
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
// only compilation units can be inconsistent
// other openables cannot be inconsistent so default is to do nothing
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public void open(IProgressMonitor pm) throws JavaModelException {
getElementInfo(pm);
}
// in model/org/eclipse/jdt/internal/core/Openable.java
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
return null;
}
// in model/org/eclipse/jdt/internal/core/Openable.java
public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
if (isReadOnly()) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
IBuffer buf = getBuffer();
if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
buf.save(pm, force);
makeConsistent(pm); // update the element info of this element
}
}
// in model/org/eclipse/jdt/internal/core/Openable.java
protected void openAncestors(HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
Openable openableParent = (Openable)getOpenableParent();
if (openableParent != null && !openableParent.isOpen()) {
openableParent.generateInfos(openableParent.createElementInfo(), newElements, monitor);
}
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public void attachSource(IPath sourcePath, IPath rootPath, IProgressMonitor monitor) throws JavaModelException {
try {
verifyAttachSource(sourcePath);
if (monitor != null) {
monitor.beginTask(Messages.element_attachingSource, 2);
}
SourceMapper oldMapper= getSourceMapper();
boolean rootNeedsToBeClosed= false;
if (sourcePath == null) {
//source being detached
rootNeedsToBeClosed= true;
setSourceMapper(null);
/* Disable deltas (see 1GDTUSD)
// fire a delta to notify the UI about the source detachement.
JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
JavaModel model = (JavaModel) getJavaModel();
JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
attachedSourceDelta .sourceDetached(this); // this would be a PackageFragmentRoot
manager.registerResourceDelta(attachedSourceDelta );
manager.fire(); // maybe you want to fire the change later. Let us know about it.
*/
} else {
/*
// fire a delta to notify the UI about the source attachment.
JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
JavaModel model = (JavaModel) getJavaModel();
JavaElementDelta attachedSourceDelta = new JavaElementDelta(model);
attachedSourceDelta .sourceAttached(this); // this would be a PackageFragmentRoot
manager.registerResourceDelta(attachedSourceDelta );
manager.fire(); // maybe you want to fire the change later. Let us know about it.
*/
//check if different from the current attachment
IPath storedSourcePath= getSourceAttachmentPath();
IPath storedRootPath= getSourceAttachmentRootPath();
if (monitor != null) {
monitor.worked(1);
}
if (storedSourcePath != null) {
if (!(storedSourcePath.equals(sourcePath) && (rootPath != null && rootPath.equals(storedRootPath)) || storedRootPath == null)) {
rootNeedsToBeClosed= true;
}
}
// check if source path is valid
Object target = JavaModel.getTarget(sourcePath, false);
if (target == null) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, sourcePath));
}
SourceMapper mapper = createSourceMapper(sourcePath, rootPath);
if (rootPath == null && mapper.rootPath != null) {
// as a side effect of calling the SourceMapper constructor, the root path was computed
rootPath = new Path(mapper.rootPath);
}
setSourceMapper(mapper);
}
if (sourcePath == null) {
Util.setSourceAttachmentProperty(getPath(), null); //remove the property
} else {
//set the property to the path of the mapped source
Util.setSourceAttachmentProperty(
getPath(),
sourcePath.toString()
+ (rootPath == null ? "" : (ATTACHMENT_PROPERTY_DELIMITER + rootPath.toString()))); //$NON-NLS-1$
}
if (rootNeedsToBeClosed) {
if (oldMapper != null) {
oldMapper.close();
}
BufferManager manager= BufferManager.getDefaultBufferManager();
Enumeration openBuffers= manager.getOpenBuffers();
while (openBuffers.hasMoreElements()) {
IBuffer buffer= (IBuffer) openBuffers.nextElement();
IOpenable possibleMember= buffer.getOwner();
if (isAncestorOf((IJavaElement) possibleMember)) {
buffer.close();
}
}
if (monitor != null) {
monitor.worked(1);
}
}
} catch (JavaModelException e) {
Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed
throw e;
} finally {
if (monitor != null) {
monitor.done();
}
}
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
return computeChildren(info, underlyingResource);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public void delete(
int updateResourceFlags,
int updateModelFlags,
IProgressMonitor monitor)
throws JavaModelException {
DeletePackageFragmentRootOperation op = new DeletePackageFragmentRootOperation(this, updateResourceFlags, updateModelFlags);
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
protected boolean computeChildren(OpenableElementInfo info, IResource underlyingResource) throws JavaModelException {
// Note the children are not opened (so not added to newElements) for a regular package fragment root
// However they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren)
try {
// the underlying resource may be a folder or a project (in the case that the project folder
// is actually the package fragment root)
if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
ArrayList vChildren = new ArrayList(5);
IContainer rootFolder = (IContainer) underlyingResource;
char[][] inclusionPatterns = fullInclusionPatternChars();
char[][] exclusionPatterns = fullExclusionPatternChars();
computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, inclusionPatterns, exclusionPatterns), CharOperation.NO_STRINGS, vChildren, inclusionPatterns, exclusionPatterns);
IJavaElement[] children = new IJavaElement[vChildren.size()];
vChildren.toArray(children);
info.setChildren(children);
}
} catch (JavaModelException e) {
//problem resolving children; structure remains unknown
info.setChildren(new IJavaElement[]{});
throw e;
}
return true;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
protected void computeFolderChildren(IContainer folder, boolean isIncluded, String[] pkgName, ArrayList vChildren, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
if (isIncluded) {
IPackageFragment pkg = getPackageFragment(pkgName);
vChildren.add(pkg);
}
try {
JavaProject javaProject = (JavaProject)getJavaProject();
JavaModelManager manager = JavaModelManager.getJavaModelManager();
IResource[] members = folder.members();
boolean hasIncluded = isIncluded;
int length = members.length;
if (length >0) {
String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
for (int i = 0; i < length; i++) {
IResource member = members[i];
String memberName = member.getName();
switch(member.getType()) {
case IResource.FOLDER:
// recurse into sub folders even even parent not included as a sub folder could be included
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65637)
if (Util.isValidFolderNameForPackage(memberName, sourceLevel, complianceLevel)) {
// eliminate binary output only if nested inside direct subfolders
if (javaProject.contains(member)) {
String[] newNames = Util.arrayConcat(pkgName, manager.intern(memberName));
boolean isMemberIncluded = !Util.isExcluded(member, inclusionPatterns, exclusionPatterns);
computeFolderChildren((IFolder) member, isMemberIncluded, newNames, vChildren, inclusionPatterns, exclusionPatterns);
}
}
break;
case IResource.FILE:
// inclusion filter may only include files, in which case we still want to include the immediate parent package (lazily)
if (!hasIncluded
&& Util.isValidCompilationUnitName(memberName, sourceLevel, complianceLevel)
&& !Util.isExcluded(member, inclusionPatterns, exclusionPatterns)) {
hasIncluded = true;
IPackageFragment pkg = getPackageFragment(pkgName);
vChildren.add(pkg);
}
break;
}
}
}
} catch(IllegalArgumentException e){
throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public void copy(
IPath destination,
int updateResourceFlags,
int updateModelFlags,
IClasspathEntry sibling,
IProgressMonitor monitor)
throws JavaModelException {
CopyPackageFragmentRootOperation op =
new CopyPackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IPackageFragment createPackageFragment(String pkgName, boolean force, IProgressMonitor monitor) throws JavaModelException {
CreatePackageFragmentOperation op = new CreatePackageFragmentOperation(this, pkgName, force);
op.runOperation(monitor);
return getPackageFragment(op.pkgName);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
protected int determineKind(IResource underlyingResource) throws JavaModelException {
IClasspathEntry entry = ((JavaProject)getJavaProject()).getClasspathEntryFor(underlyingResource.getFullPath());
if (entry != null) {
return entry.getContentKind();
}
return IPackageFragmentRoot.K_SOURCE;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public int getKind() throws JavaModelException {
return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
int internalKind() throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
PackageFragmentRootInfo info = (PackageFragmentRootInfo) manager.peekAtInfo(this);
if (info == null) {
info = (PackageFragmentRootInfo) openWhenClosed(createElementInfo(), null);
}
return info.getRootKind();
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public Object[] getNonJavaResources() throws JavaModelException {
return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(getJavaProject(), resource(), this);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IClasspathEntry getRawClasspathEntry() throws JavaModelException {
IClasspathEntry rawEntry = null;
JavaProject project = (JavaProject)getJavaProject();
project.getResolvedClasspath(); // force the reverse rawEntry cache to be populated
Map rootPathToRawEntries = project.getPerProjectInfo().rootPathToRawEntries;
if (rootPathToRawEntries != null) {
rawEntry = (IClasspathEntry) rootPathToRawEntries.get(getPath());
}
if (rawEntry == null) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this));
}
return rawEntry;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IClasspathEntry getResolvedClasspathEntry() throws JavaModelException {
IClasspathEntry resolvedEntry = null;
JavaProject project = (JavaProject)getJavaProject();
project.getResolvedClasspath(); // force the resolved entry cache to be populated
Map rootPathToResolvedEntries = project.getPerProjectInfo().rootPathToResolvedEntries;
if (rootPathToResolvedEntries != null) {
resolvedEntry = (IClasspathEntry) rootPathToResolvedEntries.get(getPath());
}
if (resolvedEntry == null) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this));
}
return resolvedEntry;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IPath getSourceAttachmentPath() throws JavaModelException {
if (getKind() != K_BINARY) return null;
// 1) look source attachment property (set iff attachSource(...) was called
IPath path = getPath();
String serverPathString= Util.getSourceAttachmentProperty(path);
if (serverPathString != null) {
int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
if (index < 0) {
// no root path specified
return new Path(serverPathString);
} else {
String serverSourcePathString= serverPathString.substring(0, index);
return new Path(serverSourcePathString);
}
}
// 2) look at classpath entry
IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
IPath sourceAttachmentPath;
if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null)
return sourceAttachmentPath;
// 3) look for a recommendation
entry = findSourceAttachmentRecommendation();
if (entry != null && (sourceAttachmentPath = entry.getSourceAttachmentPath()) != null) {
return sourceAttachmentPath;
}
return null;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public void setSourceMapper(SourceMapper mapper) throws JavaModelException {
((PackageFragmentRootInfo) getElementInfo()).setSourceMapper(mapper);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IPath getSourceAttachmentRootPath() throws JavaModelException {
if (getKind() != K_BINARY) return null;
// 1) look source attachment property (set iff attachSource(...) was called
IPath path = getPath();
String serverPathString= Util.getSourceAttachmentProperty(path);
if (serverPathString != null) {
int index = serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
if (index == -1) return null;
String serverRootPathString= IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH;
if (index != serverPathString.length() - 1) {
serverRootPathString= serverPathString.substring(index + 1);
}
return new Path(serverRootPathString);
}
// 2) look at classpath entry
IClasspathEntry entry = ((JavaProject) getParent()).getClasspathEntryFor(path);
IPath sourceAttachmentRootPath;
if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
return sourceAttachmentRootPath;
// 3) look for a recomendation
entry = findSourceAttachmentRecommendation();
if (entry != null && (sourceAttachmentRootPath = entry.getSourceAttachmentRootPath()) != null)
return sourceAttachmentRootPath;
return null;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public IResource getUnderlyingResource() throws JavaModelException {
if (!exists()) throw newNotPresentException();
return resource();
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public boolean hasChildren() throws JavaModelException {
// a package fragment root always has the default package as a child
return true;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
public void move(
IPath destination,
int updateResourceFlags,
int updateModelFlags,
IClasspathEntry sibling,
IProgressMonitor monitor)
throws JavaModelException {
MovePackageFragmentRootOperation op =
new MovePackageFragmentRootOperation(this, destination, updateResourceFlags, updateModelFlags, sibling);
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
protected void verifyAttachSource(IPath sourcePath) throws JavaModelException {
if (!exists()) {
throw newNotPresentException();
} else if (getKind() != K_BINARY) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
} else if (sourcePath != null && !sourcePath.isAbsolute()) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, sourcePath));
}
}
// in model/org/eclipse/jdt/internal/core/ExternalPackageFragmentRoot.java
int internalKind() throws JavaModelException {
return IPackageFragmentRoot.K_BINARY;
}
// in model/org/eclipse/jdt/internal/core/ExternalPackageFragmentRoot.java
public IResource getUnderlyingResource() throws JavaModelException {
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
} else {
runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
new DeleteResourceElementsOperation(elements, force).runOperation(monitor);
} else {
new DeleteElementsOperation(elements, force).runOperation(monitor);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public IJavaProject[] getJavaProjects() throws JavaModelException {
ArrayList list = getChildrenOfType(JAVA_PROJECT);
IJavaProject[] array= new IJavaProject[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public Object[] getNonJavaResources() throws JavaModelException {
return ((JavaModelInfo) getElementInfo()).getNonJavaResources();
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
} else {
runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public void refreshExternalArchives(IJavaElement[] elementsScope, IProgressMonitor monitor) throws JavaModelException {
if (elementsScope == null){
elementsScope = new IJavaElement[] { this };
}
JavaModelManager.getJavaModelManager().getDeltaProcessor().checkExternalArchiveChanges(elementsScope, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
public void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
MultiOperation op;
if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
op = new RenameResourceElementsOperation(elements, destinations, renamings, force);
} else {
op = new RenameElementsOperation(elements, destinations, renamings, force);
}
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaModel.java
protected void runOperation(MultiOperation op, IJavaElement[] elements, IJavaElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaModelException {
op.setRenamings(renamings);
if (siblings != null) {
for (int i = 0; i < elements.length; i++) {
op.setInsertBefore(elements[i], siblings[i]);
}
}
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public UndoEdit applyTextEdit(TextEdit edit, IProgressMonitor monitor) throws JavaModelException {
IBuffer buffer = getBuffer();
if (buffer instanceof IBuffer.ITextEditCapability) {
return ((IBuffer.ITextEditCapability) buffer).applyTextEdit(edit, monitor);
} else if (buffer != null) {
IDocument document = buffer instanceof IDocument ? (IDocument) buffer : new DocumentAdapter(buffer);
try {
UndoEdit undoEdit= edit.apply(document);
return undoEdit;
} catch (MalformedTreeException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION);
} catch (BadLocationException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION);
}
}
return null; // can not happen, there are no compilation units without buffer
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
if (perWorkingCopyInfo == null) {
// close cu and its children
close();
BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor);
operation.runOperation(monitor);
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void becomeWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
IProblemRequestor requestor = this.owner == null ? null : this.owner.getProblemRequestor(this);
becomeWorkingCopy(requestor, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
// ensure buffer is opened
IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
if (buffer == null) {
openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
}
// generate structure and compute syntax problems if needed
CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
IJavaProject project = getJavaProject();
boolean createAST;
boolean resolveBindings;
int reconcileFlags;
HashMap problems;
if (info instanceof ASTHolderCUInfo) {
ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
createAST = astHolder.astLevel != NO_AST;
resolveBindings = astHolder.resolveBindings;
reconcileFlags = astHolder.reconcileFlags;
problems = astHolder.problems;
} else {
createAST = false;
resolveBindings = false;
reconcileFlags = 0;
problems = null;
}
boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null && JavaProject.hasJavaNature(project.getProject());
IProblemFactory problemFactory = new DefaultProblemFactory();
Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
if (!computeProblems) {
// disable task tags checking to speed up parsing
options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
}
CompilerOptions compilerOptions = new CompilerOptions(options);
compilerOptions.ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
SourceElementParser parser = new SourceElementParser(
requestor,
problemFactory,
compilerOptions,
true/*report local declarations*/,
!createAST /*optimize string literals only if not creating a DOM AST*/);
parser.reportOnlyOneSyntaxError = !computeProblems;
parser.setMethodsFullRecovery(true);
parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast
parser.javadocParser.checkDocComment = false;
requestor.parser = parser;
// update timestamp (might be IResource.NULL_STAMP if original does not exist)
if (underlyingResource == null) {
underlyingResource = getResource();
}
// underlying resource is null in the case of a working copy on a class file in a jar
if (underlyingResource != null)
unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp();
// compute other problems if needed
CompilationUnitDeclaration compilationUnitDeclaration = null;
CompilationUnit source = cloneCachingContents();
try {
if (computeProblems) {
if (problems == null) {
// report problems to the problem requestor
problems = new HashMap();
compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
try {
perWorkingCopyInfo.beginReporting();
for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
if (categorizedProblems == null) continue;
for (int i = 0, length = categorizedProblems.length; i < length; i++) {
perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
}
}
} finally {
perWorkingCopyInfo.endReporting();
}
} else {
// collect problems
compilationUnitDeclaration = CompilationUnitProblemFinder.process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
}
} else {
compilationUnitDeclaration = parser.parseCompilationUnit(source, true /*full parse to find local elements*/, pm);
}
if (createAST) {
int astLevel = ((ASTHolderCUInfo) info).astLevel;
org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel, compilationUnitDeclaration, options, computeProblems, source, reconcileFlags, pm);
((ASTHolderCUInfo) info).ast = cu;
}
} finally {
if (compilationUnitDeclaration != null) {
compilationUnitDeclaration.cleanUp();
}
}
return unitInfo.isStructureKnown();
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void close() throws JavaModelException {
if (getPerWorkingCopyInfo() != null) return; // a working copy must remain opened until it is discarded
super.close();
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, ICompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
codeComplete(offset, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), workingCopyOwner);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, final ICodeCompletionRequestor requestor) throws JavaModelException {
if (requestor == null){
codeComplete(offset, (ICompletionRequestor)null);
return;
}
codeComplete(
offset,
new ICompletionRequestor(){
public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
}
public void acceptError(IProblem error) {
// was disabled in 1.0
}
public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
requestor.acceptField(declaringTypePackageName, declaringTypeName, fieldName, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
requestor.acceptKeyword(keywordName, completionStart, completionEnd);
}
public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
requestor.acceptLabel(labelName, completionStart, completionEnd);
}
public void acceptLocalVariable(char[] localVarName,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// skip parameter names
requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
}
public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
// ignore
}
public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
requestor.acceptModifier(modifierName, completionStart, completionEnd);
}
public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
}
public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
}
public void acceptVariableName(char[] typePackageName,char[] typeName,char[] varName,char[] completionName,int completionStart,int completionEnd, int relevance){
// ignore
}
});
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, CompletionRequestor requestor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, CompletionRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
codeComplete(offset, requestor, workingCopyOwner, null);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) throws JavaModelException {
codeComplete(
this,
isWorkingCopy() ? (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this,
offset,
requestor,
workingCopyOwner,
this,
monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
return super.codeSelect(this, offset, length, workingCopyOwner);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException {
commitWorkingCopy(force, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException {
CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force);
op.runOperation(monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements = new IJavaElement[] {this};
IJavaElement[] containers = new IJavaElement[] {container};
String[] renamings = null;
if (rename != null) {
renamings = new String[] {rename};
}
getJavaModel().copy(elements, containers, null, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IImportDeclaration createImport(String importName, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
return createImport(importName, sibling, Flags.AccDefault, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IImportDeclaration createImport(String importName, IJavaElement sibling, int flags, IProgressMonitor monitor) throws JavaModelException {
CreateImportOperation op = new CreateImportOperation(importName, this, flags);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return getImport(importName);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IPackageDeclaration createPackageDeclaration(String pkg, IProgressMonitor monitor) throws JavaModelException {
CreatePackageDeclarationOperation op= new CreatePackageDeclarationOperation(pkg, this);
op.runOperation(monitor);
return getPackageDeclaration(pkg);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IType createType(String content, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (!exists()) {
//autogenerate this compilation unit
IPackageFragment pkg = (IPackageFragment) getParent();
String source = ""; //$NON-NLS-1$
if (!pkg.isDefaultPackage()) {
//not the default package...add the package declaration
String lineSeparator = Util.getLineSeparator(null/*no existing source*/, getJavaProject());
source = "package " + pkg.getElementName() + ";" + lineSeparator + lineSeparator; //$NON-NLS-1$ //$NON-NLS-2$
}
CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, this.name, source, force);
op.runOperation(monitor);
}
CreateTypeOperation op = new CreateTypeOperation(this, content, force);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return (IType) op.getResultElements()[0];
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
IJavaElement[] elements= new IJavaElement[] {this};
getJavaModel().delete(elements, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void discardWorkingCopy() throws JavaModelException {
// discard working copy and its children
DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this);
op.runOperation(null);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IType[] getAllTypes() throws JavaModelException {
IJavaElement[] types = getTypes();
int i;
ArrayList allTypes = new ArrayList(types.length);
ArrayList typesToTraverse = new ArrayList(types.length);
for (i = 0; i < types.length; i++) {
typesToTraverse.add(types[i]);
}
while (!typesToTraverse.isEmpty()) {
IType type = (IType) typesToTraverse.get(0);
typesToTraverse.remove(type);
allTypes.add(type);
types = type.getTypes();
for (i = 0; i < types.length; i++) {
typesToTraverse.add(types[i]);
}
}
IType[] arrayOfAllTypes = new IType[allTypes.size()];
allTypes.toArray(arrayOfAllTypes);
return arrayOfAllTypes;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IResource getCorrespondingResource() throws JavaModelException {
PackageFragmentRoot root = getPackageFragmentRoot();
if (root == null || root.isArchive()) {
return null;
} else {
return getUnderlyingResource();
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement getElementAt(int position) throws JavaModelException {
IJavaElement e= getSourceElementAt(position);
if (e == this) {
return null;
} else {
return e;
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IImportDeclaration[] getImports() throws JavaModelException {
IImportContainer container= getImportContainer();
JavaModelManager manager = JavaModelManager.getJavaModelManager();
Object info = manager.getInfo(container);
if (info == null) {
if (manager.getInfo(this) != null)
// CU was opened, but no import container, then no imports
return NO_IMPORTS;
else {
open(null); // force opening of CU
info = manager.getInfo(container);
if (info == null)
// after opening, if no import container, then no imports
return NO_IMPORTS;
}
}
IJavaElement[] elements = ((ImportContainerInfo) info).children;
int length = elements.length;
IImportDeclaration[] imports = new IImportDeclaration[length];
System.arraycopy(elements, 0, imports, 0, length);
return imports;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IPackageDeclaration[] getPackageDeclarations() throws JavaModelException {
ArrayList list = getChildrenOfType(PACKAGE_DECLARATION);
IPackageDeclaration[] array= new IPackageDeclaration[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public String getSource() throws JavaModelException {
IBuffer buffer = getBuffer();
if (buffer == null) return ""; //$NON-NLS-1$
return buffer.getContents();
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public ISourceRange getSourceRange() throws JavaModelException {
return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange();
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IType[] getTypes() throws JavaModelException {
ArrayList list = getChildrenOfType(TYPE);
IType[] array= new IType[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IResource getUnderlyingResource() throws JavaModelException {
if (isWorkingCopy() && !isPrimary()) return null;
return super.getUnderlyingResource();
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
// if factory is null, default factory must be used
if (factory == null) factory = getBufferManager().getDefaultBufferFactory();
return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement getWorkingCopy() throws JavaModelException {
return getWorkingCopy(null);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) throws JavaModelException {
return getWorkingCopy(workingCopyOwner, null, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
if (!isPrimary()) return this;
JavaModelManager manager = JavaModelManager.getJavaModelManager();
CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(), workingCopyOwner);
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
if (perWorkingCopyInfo != null) {
return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
}
BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
op.runOperation(monitor);
return workingCopy;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
makeConsistent(NO_AST, false/*don't resolve bindings*/, 0 /* don't perform statements recovery */, null/*don't collect problems but report them*/, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(int astLevel, boolean resolveBindings, int reconcileFlags, HashMap problems, IProgressMonitor monitor) throws JavaModelException {
if (isConsistent()) return null;
try {
JavaModelManager.getJavaModelManager().abortOnMissingSource.set(Boolean.TRUE);
// create a new info and make it the current info
// (this will remove the info and its children just before storing the new infos)
if (astLevel != NO_AST || problems != null) {
ASTHolderCUInfo info = new ASTHolderCUInfo();
info.astLevel = astLevel;
info.resolveBindings = resolveBindings;
info.reconcileFlags = reconcileFlags;
info.problems = problems;
openWhenClosed(info, monitor);
org.eclipse.jdt.core.dom.CompilationUnit result = info.ast;
info.ast = null;
return result;
} else {
openWhenClosed(createElementInfo(), monitor);
return null;
}
} finally {
JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null);
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] containers= new IJavaElement[] {container};
String[] renamings= null;
if (rename != null) {
renamings= new String[] {rename};
}
getJavaModel().move(elements, containers, null, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
// create buffer
BufferManager bufManager = getBufferManager();
boolean isWorkingCopy = isWorkingCopy();
IBuffer buffer =
isWorkingCopy
? this.owner.createBuffer(this)
: BufferManager.createBuffer(this);
if (buffer == null) return null;
ICompilationUnit original = null;
boolean mustSetToOriginalContent = false;
if (isWorkingCopy) {
// ensure that isOpen() is called outside the bufManager synchronized block
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=237772
mustSetToOriginalContent = !isPrimary() && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen() ;
}
// synchronize to ensure that 2 threads are not putting 2 different buffers at the same time
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331
synchronized(bufManager) {
IBuffer existingBuffer = bufManager.getBuffer(this);
if (existingBuffer != null)
return existingBuffer;
// set the buffer source
if (buffer.getCharacters() == null) {
if (isWorkingCopy) {
if (mustSetToOriginalContent) {
buffer.setContents(original.getSource());
} else {
IFile file = (IFile)getResource();
if (file == null || !file.exists()) {
// initialize buffer with empty contents
buffer.setContents(CharOperation.NO_CHAR);
} else {
buffer.setContents(Util.getResourceContentsAsCharArray(file));
}
}
} else {
IFile file = (IFile)getResource();
if (file == null || !file.exists()) throw newNotPresentException();
buffer.setContents(Util.getResourceContentsAsCharArray(file));
}
}
// add buffer to buffer cache
// note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer
// can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block.
bufManager.addBuffer(buffer);
// listen to buffer changes
buffer.addBufferChangedListener(this);
}
return buffer;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
protected void openAncestors(HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
if (!isWorkingCopy()) {
super.openAncestors(newElements, monitor);
}
// else don't open ancestors for a working copy to speed up the first becomeWorkingCopy
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89411)
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public IMarker[] reconcile() throws JavaModelException {
reconcile(NO_AST, false/*don't force problem detection*/, false, null/*use primary owner*/, null/*no progress monitor*/);
return null;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException {
reconcile(NO_AST, forceProblemDetection? ICompilationUnit.FORCE_PROBLEM_DETECTION : 0, null/*use primary owner*/, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
int astLevel,
boolean forceProblemDetection,
WorkingCopyOwner workingCopyOwner,
IProgressMonitor monitor) throws JavaModelException {
return reconcile(astLevel, forceProblemDetection? ICompilationUnit.FORCE_PROBLEM_DETECTION : 0, workingCopyOwner, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
int astLevel,
boolean forceProblemDetection,
boolean enableStatementsRecovery,
WorkingCopyOwner workingCopyOwner,
IProgressMonitor monitor) throws JavaModelException {
int flags = 0;
if (forceProblemDetection) flags |= ICompilationUnit.FORCE_PROBLEM_DETECTION;
if (enableStatementsRecovery) flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
return reconcile(astLevel, flags, workingCopyOwner, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
int astLevel,
int reconcileFlags,
WorkingCopyOwner workingCopyOwner,
IProgressMonitor monitor)
throws JavaModelException {
if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies
if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
PerformanceStats stats = null;
if(ReconcileWorkingCopyOperation.PERF) {
stats = PerformanceStats.getStats(JavaModelManager.RECONCILE_PERF, this);
stats.startRun(new String(getFileName()));
}
ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, astLevel, reconcileFlags, workingCopyOwner);
JavaModelManager manager = JavaModelManager.getJavaModelManager();
try {
manager.cacheZipFiles(this); // cache zip files for performance (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=134172)
op.runOperation(monitor);
} finally {
manager.flushZipFiles(this);
}
if(ReconcileWorkingCopyOperation.PERF) {
stats.endRun();
}
return op.ast;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (newName == null) {
throw new IllegalArgumentException(Messages.operation_nullName);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] dests= new IJavaElement[] {getParent()};
String[] renamings= new String[] {newName};
getJavaModel().rename(elements, dests, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void restore() throws JavaModelException {
if (!isWorkingCopy()) return;
CompilationUnit original = (CompilationUnit) getOriginalElement();
IBuffer buffer = getBuffer();
if (buffer == null) return;
buffer.setContents(original.getContents());
updateTimeStamp(original);
makeConsistent(null);
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
if (isWorkingCopy()) {
// no need to save the buffer for a working copy (this is a noop)
reconcile(); // not simply makeConsistent, also computes fine-grain deltas
// in case the working copy is being reconciled already (if not it would miss
// one iteration of deltas).
} else {
super.save(pm, force);
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
protected void updateTimeStamp(CompilationUnit original) throws JavaModelException {
long timeStamp =
((IFile) original.getResource()).getModificationStamp();
if (timeStamp == IResource.NULL_STAMP) {
throw new JavaModelException(
new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
}
((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp;
}
// in model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
private void deleteElement(IJavaElement elementToRemove, ICompilationUnit cu) throws JavaModelException {
// ensure cu is consistent (noop if already consistent)
cu.makeConsistent(this.progressMonitor);
this.parser.setSource(cu);
CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
ASTNode node = ((JavaElement) elementToRemove).findNode(astCU);
if (node == null)
Assert.isTrue(false, "Failed to locate " + elementToRemove.getElementName() + " in " + cu.getElementName()); //$NON-NLS-1$//$NON-NLS-2$
AST ast = astCU.getAST();
ASTRewrite rewriter = ASTRewrite.create(ast);
rewriter.remove(node, null);
TextEdit edits = rewriter.rewriteAST();
applyTextEdit(cu, edits);
}
// in model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
protected void groupElements() throws JavaModelException {
this.childrenToRemove = new HashMap(1);
int uniqueCUs = 0;
for (int i = 0, length = this.elementsToProcess.length; i < length; i++) {
IJavaElement e = this.elementsToProcess[i];
ICompilationUnit cu = getCompilationUnitFor(e);
if (cu == null) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, e));
} else {
IRegion region = (IRegion) this.childrenToRemove.get(cu);
if (region == null) {
region = new Region();
this.childrenToRemove.put(cu, region);
uniqueCUs += 1;
}
region.add(e);
}
}
this.elementsToProcess = new IJavaElement[uniqueCUs];
Iterator iter = this.childrenToRemove.keySet().iterator();
int i = 0;
while (iter.hasNext()) {
this.elementsToProcess[i++] = (IJavaElement) iter.next();
}
}
// in model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
protected void processElement(IJavaElement element) throws JavaModelException {
ICompilationUnit cu = (ICompilationUnit) element;
// keep track of the import statements - if all are removed, delete
// the import container (and report it in the delta)
int numberOfImports = cu.getImports().length;
JavaElementDelta delta = new JavaElementDelta(cu);
IJavaElement[] cuElements = ((IRegion) this.childrenToRemove.get(cu)).getElements();
for (int i = 0, length = cuElements.length; i < length; i++) {
IJavaElement e = cuElements[i];
if (e.exists()) {
deleteElement(e, cu);
delta.removed(e);
if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) {
numberOfImports--;
if (numberOfImports == 0) {
delta.removed(cu.getImportContainer());
}
}
}
}
if (delta.getAffectedChildren().length > 0) {
cu.save(getSubProgressMonitor(1), this.force);
if (!cu.isWorkingCopy()) { // if unit is working copy, then save will have already fired the delta
addDelta(delta);
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
}
}
}
// in model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
protected void processElements() throws JavaModelException {
groupElements();
super.processElements();
}
// in model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
IJavaElement[] children = ((IRegion) this.childrenToRemove.get(element)).getElements();
for (int i = 0; i < children.length; i++) {
IJavaElement child = children[i];
if (child.getCorrespondingResource() != null)
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, child);
if (child.isReadOnly())
error(IJavaModelStatusConstants.READ_ONLY, child);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public boolean writeAndCacheClasspath(
JavaProject javaProject,
final IClasspathEntry[] newRawClasspath,
IClasspathEntry[] newReferencedEntries,
final IPath newOutputLocation) throws JavaModelException {
try {
this.writtingRawClasspath = true;
if (newReferencedEntries == null) newReferencedEntries = this.referencedEntries;
// write .classpath
if (!javaProject.writeFileEntries(newRawClasspath, newReferencedEntries, newOutputLocation)) {
return false;
}
// store new raw classpath, new output and new status, and null out resolved info
setRawClasspath(newRawClasspath, newReferencedEntries, newOutputLocation, JavaModelStatus.VERIFIED_OK);
} finally {
this.writtingRawClasspath = false;
}
return true;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public boolean writeAndCacheClasspath(JavaProject javaProject, final IClasspathEntry[] newRawClasspath, final IPath newOutputLocation) throws JavaModelException {
return writeAndCacheClasspath(javaProject, newRawClasspath, null, newOutputLocation);
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException {
// create the delta builder (this remembers the current content of the working copy)
// outside the perWorkingCopyInfos lock (see bug 50667)
JavaElementDeltaBuilder deltaBuilder = null;
if (workingCopy.isPrimary() && workingCopy.hasUnsavedChanges()) {
deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
}
PerWorkingCopyInfo info = null;
synchronized(this.perWorkingCopyInfos) {
WorkingCopyOwner owner = workingCopy.owner;
Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
if (workingCopyToInfos == null) return -1;
info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
if (info == null) return -1;
if (--info.useCount == 0) {
// remove per working copy info
workingCopyToInfos.remove(workingCopy);
if (workingCopyToInfos.isEmpty()) {
this.perWorkingCopyInfos.remove(owner);
}
}
}
if (info.useCount == 0) { // info cannot be null here (check was done above)
// remove infos + close buffer (since no longer working copy)
// outside the perWorkingCopyInfos lock (see bug 50667)
removeInfoAndChildren(workingCopy);
workingCopy.closeBuffer();
// compute the delta if needed and register it if there are changes
if (deltaBuilder != null) {
deltaBuilder.buildDeltas();
if (deltaBuilder.delta != null) {
getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
}
}
}
return info.useCount;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public IClasspathContainer getClasspathContainer(final IPath containerPath, final IJavaProject project) throws JavaModelException {
IClasspathContainer container = containerGet(project, containerPath);
if (container == null) {
if (batchContainerInitializations()) {
// avoid deep recursion while initializing container on workspace restart
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=60437)
try {
container = initializeAllContainers(project, containerPath);
} finally {
batchInitializationFinished();
}
} else {
container = initializeContainer(project, containerPath);
containerBeingInitializedRemove(project, containerPath);
SetContainerOperation operation = new SetContainerOperation(containerPath, new IJavaProject[] {project}, new IClasspathContainer[] {container});
operation.runOperation(null);
}
}
return container;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public PerProjectInfo getPerProjectInfoCheckExistence(IProject project) throws JavaModelException {
JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */);
if (info == null) {
if (!JavaProject.hasJavaNature(project)) {
throw ((JavaProject)JavaCore.create(project)).newNotPresentException();
}
info = getPerProjectInfo(project, true /* create info */);
}
return info;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathContainer initializeAllContainers(IJavaProject javaProjectToInit, IPath containerToInit) throws JavaModelException {
if (CP_RESOLVE_VERBOSE_ADVANCED)
verbose_batching_containers_initialization(javaProjectToInit, containerToInit);
// collect all container paths
final HashMap allContainerPaths = new HashMap();
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (int i = 0, length = projects.length; i < length; i++) {
IProject project = projects[i];
if (!JavaProject.hasJavaNature(project)) continue;
IJavaProject javaProject = new JavaProject(project, getJavaModel());
HashSet paths = (HashSet) allContainerPaths.get(javaProject);
IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
for (int j = 0, length2 = rawClasspath.length; j < length2; j++) {
IClasspathEntry entry = rawClasspath[j];
IPath path = entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER
&& containerGet(javaProject, path) == null) {
if (paths == null) {
paths = new HashSet();
allContainerPaths.put(javaProject, paths);
}
paths.add(path);
}
}
/* TODO (frederic) put back when JDT/UI dummy project will be thrown away...
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97524
*
if (javaProject.equals(javaProjectToInit)) {
if (paths == null) {
paths = new HashSet();
allContainerPaths.put(javaProject, paths);
}
paths.add(containerToInit);
}
*/
}
// TODO (frederic) remove following block when JDT/UI dummy project will be thrown away...
if (javaProjectToInit != null) {
HashSet containerPaths = (HashSet) allContainerPaths.get(javaProjectToInit);
if (containerPaths == null) {
containerPaths = new HashSet();
allContainerPaths.put(javaProjectToInit, containerPaths);
}
containerPaths.add(containerToInit);
}
// end block
// initialize all containers
boolean ok = false;
try {
// if possible run inside an IWokspaceRunnable with AVOID_UPATE to avoid unwanted builds
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=118507)
IWorkspaceRunnable runnable =
new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
try {
// Collect all containers
Set entrySet = allContainerPaths.entrySet();
int length = entrySet.size();
if (monitor != null)
monitor.beginTask("", length); //$NON-NLS-1$
Map.Entry[] entries = new Map.Entry[length]; // clone as the following will have a side effect
entrySet.toArray(entries);
for (int i = 0; i < length; i++) {
Map.Entry entry = entries[i];
IJavaProject javaProject = (IJavaProject) entry.getKey();
HashSet pathSet = (HashSet) entry.getValue();
if (pathSet == null) continue;
int length2 = pathSet.size();
IPath[] paths = new IPath[length2];
pathSet.toArray(paths); // clone as the following will have a side effect
for (int j = 0; j < length2; j++) {
IPath path = paths[j];
initializeContainer(javaProject, path);
IClasspathContainer container = containerBeingInitializedGet(javaProject, path);
if (container != null) {
containerPut(javaProject, path, container);
}
}
if (monitor != null)
monitor.worked(1);
}
// Set all containers
Map perProjectContainers = (Map) JavaModelManager.this.containersBeingInitialized.get();
if (perProjectContainers != null) {
Iterator entriesIterator = perProjectContainers.entrySet().iterator();
while (entriesIterator.hasNext()) {
Map.Entry entry = (Map.Entry) entriesIterator.next();
IJavaProject project = (IJavaProject) entry.getKey();
HashMap perPathContainers = (HashMap) entry.getValue();
Iterator containersIterator = perPathContainers.entrySet().iterator();
while (containersIterator.hasNext()) {
Map.Entry containerEntry = (Map.Entry) containersIterator.next();
IPath containerPath = (IPath) containerEntry.getKey();
IClasspathContainer container = (IClasspathContainer) containerEntry.getValue();
SetContainerOperation operation = new SetContainerOperation(containerPath, new IJavaProject[] {project}, new IClasspathContainer[] {container});
operation.runOperation(monitor);
}
}
JavaModelManager.this.containersBeingInitialized.set(null);
}
} finally {
if (monitor != null)
monitor.done();
}
}
};
IProgressMonitor monitor = this.batchContainerInitializationsProgress;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
if (workspace.isTreeLocked())
runnable.run(monitor);
else
workspace.run(
runnable,
null/*don't take any lock*/,
IWorkspace.AVOID_UPDATE,
monitor);
ok = true;
} catch (CoreException e) {
// ignore
Util.log(e, "Exception while initializing all containers"); //$NON-NLS-1$
} finally {
if (!ok) {
// if we're being traversed by an exception, ensure that that containers are
// no longer marked as initialization in progress
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=66437)
this.containerInitializationInProgress.set(null);
}
}
return containerGet(javaProjectToInit, containerToInit);
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
IClasspathContainer initializeContainer(IJavaProject project, IPath containerPath) throws JavaModelException {
IProgressMonitor monitor = this.batchContainerInitializationsProgress;
if (monitor != null && monitor.isCanceled())
throw new OperationCanceledException();
IClasspathContainer container = null;
final ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
if (initializer != null){
if (CP_RESOLVE_VERBOSE)
verbose_triggering_container_initialization(project, containerPath, initializer);
if (CP_RESOLVE_VERBOSE_ADVANCED)
verbose_triggering_container_initialization_invocation_trace();
PerformanceStats stats = null;
if(JavaModelManager.PERF_CONTAINER_INITIALIZER) {
stats = PerformanceStats.getStats(JavaModelManager.CONTAINER_INITIALIZER_PERF, this);
stats.startRun(containerPath + " of " + project.getPath()); //$NON-NLS-1$
}
containerPut(project, containerPath, CONTAINER_INITIALIZATION_IN_PROGRESS); // avoid initialization cycles
boolean ok = false;
try {
if (monitor != null)
monitor.subTask(Messages.bind(Messages.javamodel_configuring, initializer.getDescription(containerPath, project)));
// let OperationCanceledException go through
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59363)
initializer.initialize(containerPath, project);
if (monitor != null)
monitor.subTask(""); //$NON-NLS-1$
// retrieve value (if initialization was successful)
container = containerBeingInitializedGet(project, containerPath);
if (container == null && containerGet(project, containerPath) == CONTAINER_INITIALIZATION_IN_PROGRESS) {
// initializer failed to do its job: redirect to the failure container
container = initializer.getFailureContainer(containerPath, project);
if (container == null) {
if (CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE)
verbose_container_null_failure_container(project, containerPath, initializer);
return null; // break cycle
}
if (CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE)
verbose_container_using_failure_container(project, containerPath, initializer);
containerPut(project, containerPath, container);
}
ok = true;
} catch (CoreException e) {
if (e instanceof JavaModelException) {
throw (JavaModelException) e;
} else {
throw new JavaModelException(e);
}
} catch (RuntimeException e) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE)
e.printStackTrace();
throw e;
} catch (Error e) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE)
e.printStackTrace();
throw e;
} finally {
if(JavaModelManager.PERF_CONTAINER_INITIALIZER) {
stats.endRun();
}
if (!ok) {
// just remove initialization in progress and keep previous session container so as to avoid a full build
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=92588
containerRemoveInitializationInProgress(project, containerPath);
if (CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE)
verbose_container_initialization_failed(project, containerPath, container, initializer);
}
}
if (CP_RESOLVE_VERBOSE_ADVANCED)
verbose_container_value_after_initialization(project, containerPath, container);
} else {
// create a dummy initializer and get the default failure container
container = (new ClasspathContainerInitializer() {
public void initialize(IPath path, IJavaProject javaProject) throws CoreException {
// not used
}
}).getFailureContainer(containerPath, project);
if (CP_RESOLVE_VERBOSE_ADVANCED || CP_RESOLVE_VERBOSE_FAILURE)
verbose_no_container_initializer_found(project, containerPath);
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
Object info = this.cache.peekAtInfo(element);
if (info != null) {
boolean wasVerbose = false;
try {
if (JavaModelCache.VERBOSE) {
String elementType;
switch (element.getElementType()) {
case IJavaElement.JAVA_PROJECT:
elementType = "project"; //$NON-NLS-1$
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
elementType = "root"; //$NON-NLS-1$
break;
case IJavaElement.PACKAGE_FRAGMENT:
elementType = "package"; //$NON-NLS-1$
break;
case IJavaElement.CLASS_FILE:
elementType = "class file"; //$NON-NLS-1$
break;
case IJavaElement.COMPILATION_UNIT:
elementType = "compilation unit"; //$NON-NLS-1$
break;
default:
elementType = "element"; //$NON-NLS-1$
}
System.out.println(Thread.currentThread() + " CLOSING "+ elementType + " " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
wasVerbose = true;
JavaModelCache.VERBOSE = false;
}
element.closing(info);
if (element instanceof IParent) {
closeChildren(info);
}
this.cache.removeInfo(element);
if (wasVerbose) {
System.out.println(this.cache.toStringFillingRation("-> ")); //$NON-NLS-1$
}
} finally {
JavaModelCache.VERBOSE = wasVerbose;
}
return info;
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
void save(ISaveContext context) throws IOException, JavaModelException {
saveProjects(getJavaModel().getJavaProjects());
// remove variables that should not be saved
HashMap varsToSave = null;
Iterator iterator = JavaModelManager.this.variables.entrySet().iterator();
IEclipsePreferences defaultPreferences = getDefaultPreferences();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
String varName = (String) entry.getKey();
if (defaultPreferences.get(CP_VARIABLE_PREFERENCES_PREFIX + varName, null) != null // don't save classpath variables from the default preferences as there is no delta if they are removed
|| CP_ENTRY_IGNORE_PATH.equals(entry.getValue())) {
if (varsToSave == null)
varsToSave = new HashMap(JavaModelManager.this.variables);
varsToSave.remove(varName);
}
}
saveVariables(varsToSave != null ? varsToSave : JavaModelManager.this.variables);
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveProjects(IJavaProject[] projects) throws IOException,
JavaModelException {
int count = projects.length;
saveInt(count);
for (int i = 0; i < count; ++i) {
IJavaProject project = projects[i];
saveString(project.getElementName());
Map containerMap = (Map) JavaModelManager.this.containers.get(project);
if (containerMap == null) {
containerMap = Collections.EMPTY_MAP;
} else {
// clone while iterating
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59638)
containerMap = new HashMap(containerMap);
}
saveContainers(project, containerMap);
}
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public Map secondaryTypes(IJavaProject project, boolean waitForIndexes, IProgressMonitor monitor) throws JavaModelException {
if (VERBOSE) {
StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypes("); //$NON-NLS-1$
buffer.append(project.getElementName());
buffer.append(',');
buffer.append(waitForIndexes);
buffer.append(')');
Util.verbose(buffer.toString());
}
// Return cache if not empty and there's no new secondary types created during indexing
final PerProjectInfo projectInfo = getPerProjectInfoCheckExistence(project.getProject());
Map indexingSecondaryCache = projectInfo.secondaryTypes == null ? null : (Map) projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES);
if (projectInfo.secondaryTypes != null && indexingSecondaryCache == null) {
return projectInfo.secondaryTypes;
}
// Perform search request only if secondary types cache is not initialized yet (this will happen only once!)
if (projectInfo.secondaryTypes == null) {
return secondaryTypesSearching(project, waitForIndexes, monitor, projectInfo);
}
// New secondary types have been created while indexing secondary types cache
// => need to know whether the indexing is finished or not
boolean indexing = this.indexManager.awaitingJobsCount() > 0;
if (indexing) {
if (!waitForIndexes) {
// Indexing is running but caller cannot wait => return current cache
return projectInfo.secondaryTypes;
}
// Wait for the end of indexing or a cancel
while (this.indexManager.awaitingJobsCount() > 0) {
if (monitor != null && monitor.isCanceled()) {
return projectInfo.secondaryTypes;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return projectInfo.secondaryTypes;
}
}
}
// Indexing is finished => merge caches and return result
return secondaryTypesMerging(projectInfo.secondaryTypes);
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private Map secondaryTypesSearching(IJavaProject project, boolean waitForIndexes, IProgressMonitor monitor, final PerProjectInfo projectInfo) throws JavaModelException {
if (VERBOSE || BasicSearchEngine.VERBOSE) {
StringBuffer buffer = new StringBuffer("JavaModelManager.secondaryTypesSearch("); //$NON-NLS-1$
buffer.append(project.getElementName());
buffer.append(',');
buffer.append(waitForIndexes);
buffer.append(')');
Util.verbose(buffer.toString());
}
final Hashtable secondaryTypes = new Hashtable(3);
IRestrictedAccessTypeRequestor nameRequestor = new IRestrictedAccessTypeRequestor() {
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
String key = packageName==null ? "" : new String(packageName); //$NON-NLS-1$
HashMap types = (HashMap) secondaryTypes.get(key);
if (types == null) types = new HashMap(3);
types.put(new String(simpleTypeName), path);
secondaryTypes.put(key, types);
}
};
// Build scope using prereq projects but only source folders
IPackageFragmentRoot[] allRoots = project.getAllPackageFragmentRoots();
int length = allRoots.length, size = 0;
IPackageFragmentRoot[] allSourceFolders = new IPackageFragmentRoot[length];
for (int i=0; i<length; i++) {
if (allRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
allSourceFolders[size++] = allRoots[i];
}
}
if (size < length) {
System.arraycopy(allSourceFolders, 0, allSourceFolders = new IPackageFragmentRoot[size], 0, size);
}
// Search all secondary types on scope
new BasicSearchEngine().searchAllSecondaryTypeNames(allSourceFolders, nameRequestor, waitForIndexes, monitor);
// Build types from paths
Iterator packages = secondaryTypes.values().iterator();
while (packages.hasNext()) {
HashMap types = (HashMap) packages.next();
Iterator names = types.entrySet().iterator();
while (names.hasNext()) {
Map.Entry entry = (Map.Entry) names.next();
String typeName = (String) entry.getKey();
String path = (String) entry.getValue();
if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(path)) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
ICompilationUnit unit = JavaModelManager.createCompilationUnitFrom(file, null);
IType type = unit.getType(typeName);
types.put(typeName, type); // replace stored path with type itself
} else {
names.remove();
}
}
}
// Store result in per project info cache if still null or there's still an indexing cache (may have been set by another thread...)
if (projectInfo.secondaryTypes == null || projectInfo.secondaryTypes.get(INDEXED_SECONDARY_TYPES) != null) {
projectInfo.secondaryTypes = secondaryTypes;
if (VERBOSE || BasicSearchEngine.VERBOSE) {
System.out.print(Thread.currentThread() + " -> secondary paths stored in cache: "); //$NON-NLS-1$
System.out.println();
Iterator entries = secondaryTypes.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String qualifiedName = (String) entry.getKey();
Util.verbose(" - "+qualifiedName+'-'+ entry.getValue()); //$NON-NLS-1$
}
}
}
return projectInfo.secondaryTypes;
}
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected void setBuildOrder(String[] javaBuildOrder) throws JavaModelException {
// optional behaviour
// possible value of index 0 is Compute
if (!JavaCore.COMPUTE.equals(JavaCore.getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceDescription description = workspace.getDescription();
String[] wksBuildOrder = description.getBuildOrder();
String[] newOrder;
if (wksBuildOrder == null){
newOrder = javaBuildOrder;
} else {
// remove projects which are already mentionned in java builder order
int javaCount = javaBuildOrder.length;
HashMap newSet = new HashMap(javaCount); // create a set for fast check
for (int i = 0; i < javaCount; i++){
newSet.put(javaBuildOrder[i], javaBuildOrder[i]);
}
int removed = 0;
int oldCount = wksBuildOrder.length;
for (int i = 0; i < oldCount; i++){
if (newSet.containsKey(wksBuildOrder[i])){
wksBuildOrder[i] = null;
removed++;
}
}
// add Java ones first
newOrder = new String[oldCount - removed + javaCount];
System.arraycopy(javaBuildOrder, 0, newOrder, 0, javaCount); // java projects are built first
// copy previous items in their respective order
int index = javaCount;
for (int i = 0; i < oldCount; i++){
if (wksBuildOrder[i] != null){
newOrder[index++] = wksBuildOrder[i];
}
}
}
// commit the new build order out
description.setBuildOrder(newOrder);
try {
workspace.setDescription(description);
} catch(CoreException e){
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/Annotation.java
public IMemberValuePair[] getMemberValuePairs() throws JavaModelException {
Object info = getElementInfo();
if (info instanceof AnnotationInfo)
return ((AnnotationInfo) info).members;
IBinaryElementValuePair[] binaryAnnotations = ((IBinaryAnnotation) info).getElementValuePairs();
int length = binaryAnnotations.length;
IMemberValuePair[] result = new IMemberValuePair[length];
for (int i = 0; i < length; i++) {
IBinaryElementValuePair binaryAnnotation = binaryAnnotations[i];
MemberValuePair memberValuePair = new MemberValuePair(new String(binaryAnnotation.getName()));
memberValuePair.value = Util.getAnnotationMemberValue(this, memberValuePair, binaryAnnotation.getValue());
result[i] = memberValuePair;
}
return result;
}
// in model/org/eclipse/jdt/internal/core/Annotation.java
public ISourceRange getNameRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
ClassFile classFile = (ClassFile)getClassFile();
if (classFile != null) {
// ensure the class file's buffer is open so that source ranges are computed
classFile.getBuffer();
return mapper.getNameRange(this);
}
}
Object info = getElementInfo();
if (info instanceof AnnotationInfo) {
AnnotationInfo annotationInfo = (AnnotationInfo) info;
return new SourceRange(annotationInfo.nameStart, annotationInfo.nameEnd - annotationInfo.nameStart + 1);
}
return null;
}
// in model/org/eclipse/jdt/internal/core/Annotation.java
public ISourceRange getSourceRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
ClassFile classFile = (ClassFile)getClassFile();
if (classFile != null) {
classFile.getBuffer();
return mapper.getSourceRange(this);
}
}
return super.getSourceRange();
}
// in model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java
public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
}
// in model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java
public IBuffer getBuffer() throws JavaModelException {
if (isWorkingCopy())
return super.getBuffer();
else
return this.classFile.getBuffer();
}
// in model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
// create buffer
IBuffer buffer = BufferManager.createBuffer(this);
// set the buffer source
IBuffer classFileBuffer = this.classFile.getBuffer();
if (classFileBuffer != null) {
buffer.setContents(classFileBuffer.getCharacters());
} else {
// Disassemble
IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile, IClassFileReader.ALL);
Disassembler disassembler = new Disassembler();
String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), ClassFileBytesDisassembler.WORKING_COPY); //$NON-NLS-1$
buffer.setContents(contents);
}
// add buffer to buffer cache
BufferManager bufManager = getBufferManager();
bufManager.addBuffer(buffer);
// listen to buffer changes
buffer.addBufferChangedListener(this);
return buffer;
}
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
IResource[] nonJavaResources = new IResource[5];
int nonJavaResourcesCounter = 0;
JavaProject project = (JavaProject) root.getJavaProject();
try {
IClasspathEntry[] classpath = project.getResolvedClasspath();
IResource[] members = folder.members();
int length = members.length;
if (length > 0) {
String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
nextResource: for (int i = 0; i < length; i++) {
IResource member = members[i];
switch (member.getType()) {
case IResource.FILE :
String fileName = member.getName();
// ignore .java files that are not excluded
if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel) && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
continue nextResource;
// ignore .class files
if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
continue nextResource;
// ignore .zip or .jar file on classpath
if (isClasspathEntry(member.getFullPath(), classpath))
continue nextResource;
break;
case IResource.FOLDER :
// ignore valid packages or excluded folders that correspond to a nested pkg fragment root
if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
&& (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
|| isClasspathEntry(member.getFullPath(), classpath)))
continue nextResource;
break;
}
if (nonJavaResources.length == nonJavaResourcesCounter) {
// resize
System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
}
nonJavaResources[nonJavaResourcesCounter++] = member;
}
}
if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
for (int i = 0; i < nonJavaResourcesCounter; i++) {
jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
}
return jarEntryResources;
} else if (nonJavaResources.length != nonJavaResourcesCounter) {
System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
}
return nonJavaResources;
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/BinaryTypeConverter.java
public TypeDeclaration buildTypeDeclaration(IType type, CompilationUnitDeclaration compilationUnit) throws JavaModelException {
PackageFragment pkg = (PackageFragment) type.getPackageFragment();
char[][] packageName = Util.toCharArrays(pkg.names);
if (packageName.length > 0) {
compilationUnit.currentPackage = new ImportReference(packageName, new long[]{0}, false, ClassFileConstants.AccDefault);
}
/* convert type */
TypeDeclaration typeDeclaration = convert(type, null, null);
IType alreadyComputedMember = type;
IType parent = type.getDeclaringType();
TypeDeclaration previousDeclaration = typeDeclaration;
while(parent != null) {
TypeDeclaration declaration = convert(parent, alreadyComputedMember, previousDeclaration);
alreadyComputedMember = parent;
previousDeclaration = declaration;
parent = parent.getDeclaringType();
}
compilationUnit.types = new TypeDeclaration[]{previousDeclaration};
return typeDeclaration;
}
// in model/org/eclipse/jdt/internal/core/BinaryTypeConverter.java
private FieldDeclaration convert(IField field, IType type) throws JavaModelException {
TypeReference typeReference = createTypeReference(field.getTypeSignature());
if (typeReference == null) return null;
FieldDeclaration fieldDeclaration = new FieldDeclaration();
fieldDeclaration.name = field.getElementName().toCharArray();
fieldDeclaration.type = typeReference;
fieldDeclaration.modifiers = field.getFlags();
return fieldDeclaration;
}
// in model/org/eclipse/jdt/internal/core/BinaryTypeConverter.java
private AbstractMethodDeclaration convert(IMethod method, IType type) throws JavaModelException {
AbstractMethodDeclaration methodDeclaration;
org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = null;
// convert 1.5 specific constructs only if compliance is 1.5 or above
if (this.has1_5Compliance) {
/* convert type parameters */
ITypeParameter[] typeParameters = method.getTypeParameters();
if (typeParameters != null && typeParameters.length > 0) {
int parameterCount = typeParameters.length;
typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
ITypeParameter typeParameter = typeParameters[i];
typeParams[i] =
createTypeParameter(
typeParameter.getElementName().toCharArray(),
stringArrayToCharArray(typeParameter.getBounds()),
0,
0);
}
}
}
if (method.isConstructor()) {
ConstructorDeclaration decl = new ConstructorDeclaration(this.compilationResult);
decl.bits &= ~ASTNode.IsDefaultConstructor;
decl.typeParameters = typeParams;
methodDeclaration = decl;
} else {
MethodDeclaration decl = type.isAnnotation() ? new AnnotationMethodDeclaration(this.compilationResult) : new MethodDeclaration(this.compilationResult);
/* convert return type */
TypeReference typeReference = createTypeReference(method.getReturnType());
if (typeReference == null) return null;
decl.returnType = typeReference;
decl.typeParameters = typeParams;
methodDeclaration = decl;
}
methodDeclaration.selector = method.getElementName().toCharArray();
int flags = method.getFlags();
boolean isVarargs = Flags.isVarargs(flags);
methodDeclaration.modifiers = flags & ~Flags.AccVarargs;
/* convert arguments */
String[] argumentTypeNames = method.getParameterTypes();
String[] argumentNames = method.getParameterNames();
int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length;
// Ignore synthetic arguments (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=212224)
int startIndex = (method.isConstructor() && type.isMember() && !Flags.isStatic(type.getFlags())) ? 1 : 0;
argumentCount -= startIndex;
methodDeclaration.arguments = new Argument[argumentCount];
for (int i = 0; i < argumentCount; i++) {
String argumentTypeName = argumentTypeNames[startIndex+i];
TypeReference typeReference = createTypeReference(argumentTypeName);
if (typeReference == null) return null;
if (isVarargs && i == argumentCount-1) {
typeReference.bits |= ASTNode.IsVarArgs;
}
methodDeclaration.arguments[i] = new Argument(
argumentNames[i].toCharArray(),
0,
typeReference,
ClassFileConstants.AccDefault);
// do not care whether was final or not
}
/* convert thrown exceptions */
String[] exceptionTypeNames = method.getExceptionTypes();
int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
if(exceptionCount > 0) {
methodDeclaration.thrownExceptions = new TypeReference[exceptionCount];
for (int i = 0; i < exceptionCount; i++) {
TypeReference typeReference = createTypeReference(exceptionTypeNames[i]);
if (typeReference == null) return null;
methodDeclaration.thrownExceptions[i] = typeReference;
}
}
return methodDeclaration;
}
// in model/org/eclipse/jdt/internal/core/BinaryTypeConverter.java
private TypeDeclaration convert(IType type, IType alreadyComputedMember,TypeDeclaration alreadyComputedMemberDeclaration) throws JavaModelException {
/* create type declaration - can be member type */
TypeDeclaration typeDeclaration = new TypeDeclaration(this.compilationResult);
if (type.getDeclaringType() != null) {
typeDeclaration.bits |= ASTNode.IsMemberType;
}
typeDeclaration.name = type.getElementName().toCharArray();
typeDeclaration.modifiers = type.getFlags();
/* set superclass and superinterfaces */
if (type.getSuperclassName() != null) {
TypeReference typeReference = createTypeReference(type.getSuperclassTypeSignature());
if (typeReference != null) {
typeDeclaration.superclass = typeReference;
typeDeclaration.superclass.bits |= ASTNode.IsSuperType;
}
}
String[] interfaceTypes = type.getSuperInterfaceTypeSignatures();
int interfaceCount = interfaceTypes == null ? 0 : interfaceTypes.length;
typeDeclaration.superInterfaces = new TypeReference[interfaceCount];
int count = 0;
for (int i = 0; i < interfaceCount; i++) {
TypeReference typeReference = createTypeReference(interfaceTypes[i]);
if (typeReference != null) {
typeDeclaration.superInterfaces[count] = typeReference;
typeDeclaration.superInterfaces[count++].bits |= ASTNode.IsSuperType;
}
}
if (count != interfaceCount) {
System.arraycopy(typeDeclaration.fields, 0, typeDeclaration.superInterfaces = new TypeReference[interfaceCount], 0, interfaceCount);
}
// convert 1.5 specific constructs only if compliance is 1.5 or above
if (this.has1_5Compliance) {
/* convert type parameters */
ITypeParameter[] typeParameters = type.getTypeParameters();
if (typeParameters != null && typeParameters.length > 0) {
int parameterCount = typeParameters.length;
org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
ITypeParameter typeParameter = typeParameters[i];
typeParams[i] =
createTypeParameter(
typeParameter.getElementName().toCharArray(),
stringArrayToCharArray(typeParameter.getBounds()),
0,
0);
}
typeDeclaration.typeParameters = typeParams;
}
}
/* convert member types */
IType[] memberTypes = type.getTypes();
int memberTypeCount = memberTypes == null ? 0 : memberTypes.length;
typeDeclaration.memberTypes = new TypeDeclaration[memberTypeCount];
for (int i = 0; i < memberTypeCount; i++) {
if(alreadyComputedMember != null && alreadyComputedMember.getFullyQualifiedName().equals(memberTypes[i].getFullyQualifiedName())) {
typeDeclaration.memberTypes[i] = alreadyComputedMemberDeclaration;
} else {
typeDeclaration.memberTypes[i] = convert(memberTypes[i], null, null);
}
typeDeclaration.memberTypes[i].enclosingType = typeDeclaration;
}
/* convert fields */
IField[] fields = type.getFields();
int fieldCount = fields == null ? 0 : fields.length;
typeDeclaration.fields = new FieldDeclaration[fieldCount];
count = 0;
for (int i = 0; i < fieldCount; i++) {
FieldDeclaration fieldDeclaration = convert(fields[i], type);
if (fieldDeclaration != null) {
typeDeclaration.fields[count++] = fieldDeclaration;
}
}
if (count != fieldCount) {
System.arraycopy(typeDeclaration.fields, 0, typeDeclaration.fields = new FieldDeclaration[count], 0, count);
}
/* convert methods - need to add default constructor if necessary */
IMethod[] methods = type.getMethods();
int methodCount = methods == null ? 0 : methods.length;
/* source type has a constructor ? */
/* by default, we assume that one is needed. */
int neededCount = 1;
for (int i = 0; i < methodCount; i++) {
if (methods[i].isConstructor()) {
neededCount = 0;
// Does not need the extra constructor since one constructor already exists.
break;
}
}
boolean isInterface = type.isInterface();
neededCount = isInterface ? 0 : neededCount;
typeDeclaration.methods = new AbstractMethodDeclaration[methodCount + neededCount];
if (neededCount != 0) { // add default constructor in first position
typeDeclaration.methods[0] = typeDeclaration.createDefaultConstructor(false, false);
}
boolean hasAbstractMethods = false;
count = 0;
for (int i = 0; i < methodCount; i++) {
AbstractMethodDeclaration method = convert(methods[i], type);
if (method != null) {
boolean isAbstract;
if ((isAbstract = method.isAbstract()) || isInterface) { // fix-up flag
method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
}
if (isAbstract) {
hasAbstractMethods = true;
}
typeDeclaration.methods[neededCount + (count++)] = method;
}
}
if (count != methodCount) {
System.arraycopy(typeDeclaration.methods, 0, typeDeclaration.methods = new AbstractMethodDeclaration[count + neededCount], 0, count + neededCount);
}
if (hasAbstractMethods) {
typeDeclaration.bits |= ASTNode.HasAbstractMethods;
}
return typeDeclaration;
}
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected boolean isExcludedFromProject(IPath childPath) throws JavaModelException {
// answer whether the folder should be ignored when walking the project as a source folder
if (childPath.segmentCount() > 2) return false; // is a subfolder of a package
for (int j = 0, k = this.sourceLocations.length; j < k; j++) {
if (childPath.equals(this.sourceLocations[j].binaryFolder.getFullPath())) return true;
if (childPath.equals(this.sourceLocations[j].sourceFolder.getFullPath())) return true;
}
// skip default output folder which may not be used by any source folder
return childPath.equals(this.javaBuilder.javaProject.getOutputLocation());
}
// in model/org/eclipse/jdt/internal/core/DiscardWorkingCopyOperation.java
protected void executeOperation() throws JavaModelException {
CompilationUnit workingCopy = getWorkingCopy();
JavaModelManager manager = JavaModelManager.getJavaModelManager();
int useCount = manager.discardPerWorkingCopyInfo(workingCopy);
if (useCount == 0) {
IJavaProject javaProject = workingCopy.getJavaProject();
if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(javaProject.getElementName())) {
manager.removePerProjectInfo((JavaProject) javaProject, true /* remove external jar files indexes and timestamps*/);
manager.containerRemove(javaProject);
}
if (!workingCopy.isPrimary()) {
// report removed java delta for a non-primary working copy
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.removed(workingCopy);
addDelta(delta);
removeReconcileDelta(workingCopy);
} else {
if (workingCopy.getResource().isAccessible()) {
// report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
addDelta(delta);
} else {
// report a REMOVED delta
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.removed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
addDelta(delta);
}
}
}
}
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
protected void executeOperation() throws JavaModelException {
try {
beginTask(Messages.operation_sortelements, getMainAmountOfWork());
CompilationUnit copy = (CompilationUnit) this.elementsToProcess[0];
ICompilationUnit unit = copy.getPrimary();
IBuffer buffer = copy.getBuffer();
if (buffer == null) {
return;
}
char[] bufferContents = buffer.getCharacters();
String result = processElement(unit, bufferContents);
if (!CharOperation.equals(result.toCharArray(), bufferContents)) {
copy.getBuffer().setContents(result);
}
worked(1);
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
public TextEdit calculateEdit(org.eclipse.jdt.core.dom.CompilationUnit unit, TextEditGroup group) throws JavaModelException {
if (this.elementsToProcess.length != 1)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS));
if (!(this.elementsToProcess[0] instanceof ICompilationUnit))
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0]));
try {
beginTask(Messages.operation_sortelements, getMainAmountOfWork());
ICompilationUnit cu= (ICompilationUnit)this.elementsToProcess[0];
String content= cu.getBuffer().getContents();
ASTRewrite rewrite= sortCompilationUnit(unit, group);
if (rewrite == null) {
return null;
}
Document document= new Document(content);
return rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public IAnnotation[] getAnnotations() throws JavaModelException {
IBinaryField info = (IBinaryField) getElementInfo();
IBinaryAnnotation[] binaryAnnotations = info.getAnnotations();
return getAnnotations(binaryAnnotations, info.getTagBits());
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public Object getConstant() throws JavaModelException {
IBinaryField info = (IBinaryField) getElementInfo();
return convertConstant(info.getConstant());
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public int getFlags() throws JavaModelException {
IBinaryField info = (IBinaryField) getElementInfo();
return info.getModifiers();
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public String getKey(boolean forceOpen) throws JavaModelException {
return getKey(this, forceOpen);
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public String getTypeSignature() throws JavaModelException {
IBinaryField info = (IBinaryField) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature != null) {
return new String(ClassFile.translatedName(genericSignature));
}
return new String(ClassFile.translatedName(info.getTypeName()));
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public boolean isEnumConstant() throws JavaModelException {
return Flags.isEnum(getFlags());
}
// in model/org/eclipse/jdt/internal/core/BinaryField.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
JavadocContents javadocContents = ((BinaryType) this.getDeclaringType()).getJavadocContents(monitor);
if (javadocContents == null) return null;
return javadocContents.getFieldDoc(this);
}
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public void createPendingFolders(IProgressMonitor monitor) throws JavaModelException{
if (this.pendingFolders == null || this.pendingFolders.isEmpty()) return;
IProject externalFoldersProject = null;
try {
externalFoldersProject = createExternalFoldersProject(monitor);
}
catch(CoreException e) {
throw new JavaModelException(e);
}
Iterator iterator = this.pendingFolders.iterator();
while (iterator.hasNext()) {
Object folderPath = iterator.next();
try {
createLinkFolder((IPath) folderPath, false, externalFoldersProject, monitor);
} catch (CoreException e) {
Util.log(e, "Error while creating a link for external folder :" + folderPath); //$NON-NLS-1$
}
}
this.pendingFolders.clear();
}
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
protected void executeOperation() throws JavaModelException {
try {
beginTask(Messages.operation_createUnitProgress, 2);
JavaElementDelta delta = newJavaElementDelta();
ICompilationUnit unit = getCompilationUnit();
IPackageFragment pkg = (IPackageFragment) getParentElement();
IContainer folder = (IContainer) pkg.getResource();
worked(1);
IFile compilationUnitFile = folder.getFile(new Path(this.name));
if (compilationUnitFile.exists()) {
// update the contents of the existing unit if fForce is true
if (this.force) {
IBuffer buffer = unit.getBuffer();
if (buffer == null) return;
buffer.setContents(this.source);
unit.save(new NullProgressMonitor(), false);
this.resultElements = new IJavaElement[] {unit};
if (!Util.isExcluded(unit)
&& unit.getParent().exists()) {
for (int i = 0; i < this.resultElements.length; i++) {
delta.changed(this.resultElements[i], IJavaElementDelta.F_CONTENT);
}
addDelta(delta);
}
} else {
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Messages.bind(Messages.status_nameCollision, compilationUnitFile.getFullPath().toString())));
}
} else {
try {
String encoding = null;
try {
encoding = folder.getDefaultCharset(); // get folder encoding as file is not accessible
}
catch (CoreException ce) {
// use no encoding
}
InputStream stream = new ByteArrayInputStream(encoding == null ? this.source.getBytes() : this.source.getBytes(encoding));
createFile(folder, unit.getElementName(), stream, this.force);
this.resultElements = new IJavaElement[] {unit};
if (!Util.isExcluded(unit)
&& unit.getParent().exists()) {
for (int i = 0; i < this.resultElements.length; i++) {
delta.added(this.resultElements[i]);
}
addDelta(delta);
}
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
worked(1);
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private IResource[] collectResourcesOfInterest(IPackageFragment source) throws JavaModelException {
IJavaElement[] children = source.getChildren();
int childOfInterest = IJavaElement.COMPILATION_UNIT;
if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
childOfInterest = IJavaElement.CLASS_FILE;
}
ArrayList correctKindChildren = new ArrayList(children.length);
for (int i = 0; i < children.length; i++) {
IJavaElement child = children[i];
if (child.getElementType() == childOfInterest) {
correctKindChildren.add(((JavaElement) child).resource());
}
}
// Gather non-java resources
Object[] nonJavaResources = source.getNonJavaResources();
int actualNonJavaResourceCount = 0;
for (int i = 0, max = nonJavaResources.length; i < max; i++){
if (nonJavaResources[i] instanceof IResource) actualNonJavaResourceCount++;
}
IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount];
for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
}
if (actualNonJavaResourceCount != 0) {
int correctKindChildrenSize = correctKindChildren.size();
IResource[] result = new IResource[correctKindChildrenSize + actualNonJavaResourceCount];
correctKindChildren.toArray(result);
System.arraycopy(actualNonJavaResources, 0, result, correctKindChildrenSize, actualNonJavaResourceCount);
return result;
} else {
IResource[] result = new IResource[correctKindChildren.size()];
correctKindChildren.toArray(result);
return result;
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private boolean createNeededPackageFragments(IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName, boolean moveFolder) throws JavaModelException {
boolean containsReadOnlyPackageFragment = false;
IContainer parentFolder = (IContainer) root.resource();
JavaElementDelta projectDelta = null;
String[] sideEffectPackageName = null;
char[][] inclusionPatterns = root.fullInclusionPatternChars();
char[][] exclusionPatterns = root.fullExclusionPatternChars();
for (int i = 0; i < newFragName.length; i++) {
String subFolderName = newFragName[i];
sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
IResource subFolder = parentFolder.findMember(subFolderName);
if (subFolder == null) {
// create deepest folder only if not a move (folder will be moved in processPackageFragmentResource)
if (!(moveFolder && i == newFragName.length-1)) {
createFolder(parentFolder, subFolderName, this.force);
}
parentFolder = parentFolder.getFolder(new Path(subFolderName));
sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
if (Util.isReadOnly(sourceFolder)) {
containsReadOnlyPackageFragment = true;
}
IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName);
if (i < newFragName.length - 1 // all but the last one are side effect packages
&& !Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
if (projectDelta == null) {
projectDelta = getDeltaFor(root.getJavaProject());
}
projectDelta.added(sideEffectPackage);
}
this.createdElements.add(sideEffectPackage);
} else {
parentFolder = (IContainer) subFolder;
}
}
return containsReadOnlyPackageFragment;
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private void processCompilationUnitResource(ICompilationUnit source, PackageFragment dest) throws JavaModelException {
String newCUName = getNewNameFor(source);
String destName = (newCUName != null) ? newCUName : source.getElementName();
TextEdit edit = updateContent(source, dest, newCUName); // null if unchanged
// TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
// store encoding (fix bug 66898)
IFile sourceResource = (IFile)source.getResource();
String sourceEncoding = null;
try {
sourceEncoding = sourceResource.getCharset(false);
}
catch (CoreException ce) {
// no problem, use default encoding
}
// end todo
// copy resource
IContainer destFolder = (IContainer)dest.getResource(); // can be an IFolder or an IProject
IFile destFile = destFolder.getFile(new Path(destName));
org.eclipse.jdt.internal.core.CompilationUnit destCU = new org.eclipse.jdt.internal.core.CompilationUnit(dest, destName, DefaultWorkingCopyOwner.PRIMARY);
if (!destFile.equals(sourceResource)) {
try {
if (!destCU.isWorkingCopy()) {
if (destFile.exists()) {
if (this.force) {
// we can remove it
deleteResource(destFile, IResource.KEEP_HISTORY);
destCU.close(); // ensure the in-memory buffer for the dest CU is closed
} else {
// abort
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString())));
}
}
int flags = this.force ? IResource.FORCE : IResource.NONE;
if (isMove()) {
flags |= IResource.KEEP_HISTORY;
sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1));
} else {
if (edit != null) flags |= IResource.KEEP_HISTORY;
sourceResource.copy(destFile.getFullPath(), flags, getSubProgressMonitor(1));
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} else {
destCU.getBuffer().setContents(source.getBuffer().getContents());
}
} catch (JavaModelException e) {
throw e;
} catch (CoreException e) {
throw new JavaModelException(e);
}
// update new resource content
if (edit != null){
boolean wasReadOnly = destFile.isReadOnly();
try {
saveContent(dest, destName, edit, sourceEncoding, destFile);
} catch (CoreException e) {
if (e instanceof JavaModelException) throw (JavaModelException) e;
throw new JavaModelException(e);
} finally {
Util.setReadOnly(destFile, wasReadOnly);
}
}
// register the correct change deltas
prepareDeltas(source, destCU, isMove());
if (newCUName != null) {
//the main type has been renamed
String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName());
String newName = Util.getNameWithoutJavaLikeExtension(newCUName);
prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove());
}
} else {
if (!this.force) {
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString())));
}
// update new resource content
// in case we do a saveas on the same resource we have to simply update the contents
// see http://dev.eclipse.org/bugs/show_bug.cgi?id=9351
if (edit != null){
saveContent(dest, destName, edit, sourceEncoding, destFile);
}
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
protected void processElement(IJavaElement element) throws JavaModelException {
IJavaElement dest = getDestinationParent(element);
switch (element.getElementType()) {
case IJavaElement.COMPILATION_UNIT :
processCompilationUnitResource((ICompilationUnit) element, (PackageFragment) dest);
this.createdElements.add(((IPackageFragment) dest).getCompilationUnit(element.getElementName()));
break;
case IJavaElement.PACKAGE_FRAGMENT :
processPackageFragmentResource((PackageFragment) element, (PackageFragmentRoot) dest, getNewNameFor(element));
break;
default :
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
protected void processElements() throws JavaModelException {
this.createdElements = new ArrayList(this.elementsToProcess.length);
try {
super.processElements();
} catch (JavaModelException jme) {
throw jme;
} finally {
this.resultElements = new IJavaElement[this.createdElements.size()];
this.createdElements.toArray(this.resultElements);
processDeltas();
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private void processPackageFragmentResource(PackageFragment source, PackageFragmentRoot root, String newName) throws JavaModelException {
try {
String[] newFragName = (newName == null) ? source.names : Util.getTrimmedSimpleNames(newName);
PackageFragment newFrag = root.getPackageFragment(newFragName);
IResource[] resources = collectResourcesOfInterest(source);
// if isMove() can we move the folder itself ? (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=22458)
boolean shouldMoveFolder = isMove() && !newFrag.resource().exists(); // if new pkg fragment exists, it is an override
IFolder srcFolder = (IFolder)source.resource();
IPath destPath = newFrag.getPath();
if (shouldMoveFolder) {
// check if destination is not included in source
if (srcFolder.getFullPath().isPrefixOf(destPath)) {
shouldMoveFolder = false;
} else {
// check if there are no sub-packages
IResource[] members = srcFolder.members();
for (int i = 0; i < members.length; i++) {
if ( members[i] instanceof IFolder) {
shouldMoveFolder = false;
break;
}
}
}
}
boolean containsReadOnlySubPackageFragments = createNeededPackageFragments((IContainer) source.parent.resource(), root, newFragName, shouldMoveFolder);
boolean sourceIsReadOnly = Util.isReadOnly(srcFolder);
// Process resources
if (shouldMoveFolder) {
// move underlying resource
// TODO Revisit once bug 43044 is fixed
if (sourceIsReadOnly) {
Util.setReadOnly(srcFolder, false);
}
srcFolder.move(destPath, this.force, true /* keep history */, getSubProgressMonitor(1));
if (sourceIsReadOnly) {
Util.setReadOnly(srcFolder, true);
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} else {
// process the leaf resources
if (resources.length > 0) {
if (isRename()) {
if (! destPath.equals(source.getPath())) {
moveResources(resources, destPath);
}
} else if (isMove()) {
// we need to delete this resource if this operation wants to override existing resources
for (int i = 0, max = resources.length; i < max; i++) {
IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
if (destinationResource != null) {
if (this.force) {
deleteResource(destinationResource, IResource.KEEP_HISTORY);
} else {
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Messages.bind(Messages.status_nameCollision, destinationResource.getFullPath().toString())));
}
}
}
moveResources(resources, destPath);
} else {
// we need to delete this resource if this operation wants to override existing resources
for (int i = 0, max = resources.length; i < max; i++) {
IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
if (destinationResource != null) {
if (this.force) {
// we need to delete this resource if this operation wants to override existing resources
deleteResource(destinationResource, IResource.KEEP_HISTORY);
} else {
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Messages.bind(Messages.status_nameCollision, destinationResource.getFullPath().toString())));
}
}
}
copyResources(resources, destPath);
}
}
}
// Update package statement in compilation unit if needed
if (!Util.equalArraysOrNull(newFragName, source.names)) { // if package has been renamed, update the compilation units
char[][] inclusionPatterns = root.fullInclusionPatternChars();
char[][] exclusionPatterns = root.fullExclusionPatternChars();
for (int i = 0; i < resources.length; i++) {
String resourceName = resources[i].getName();
if (Util.isJavaLikeFileName(resourceName)) {
// we only consider potential compilation units
ICompilationUnit cu = newFrag.getCompilationUnit(resourceName);
if (Util.isExcluded(cu.getPath(), inclusionPatterns, exclusionPatterns, false/*not a folder*/)) continue;
this.parser.setSource(cu);
CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
AST ast = astCU.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
updatePackageStatement(astCU, newFragName, rewrite, cu);
TextEdit edits = rewrite.rewriteAST();
applyTextEdit(cu, edits);
cu.save(null, false);
}
}
}
// Discard empty old package (if still empty after the rename)
boolean isEmpty = true;
if (isMove()) {
// delete remaining files in this package (.class file in the case where Proj=src=bin)
// in case of a copy
updateReadOnlyPackageFragmentsForMove((IContainer) source.parent.resource(), root, newFragName, sourceIsReadOnly);
if (srcFolder.exists()) {
IResource[] remaining = srcFolder.members();
for (int i = 0, length = remaining.length; i < length; i++) {
IResource file = remaining[i];
if (file instanceof IFile) {
if (Util.isReadOnly(file)) {
Util.setReadOnly(file, false);
}
deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
} else {
isEmpty = false;
}
}
}
if (isEmpty) {
IResource rootResource;
// check if source is included in destination
if (destPath.isPrefixOf(srcFolder.getFullPath())) {
rootResource = newFrag.resource();
} else {
rootResource = source.parent.resource();
}
// delete recursively empty folders
deleteEmptyPackageFragment(source, false, rootResource);
}
} else if (containsReadOnlySubPackageFragments) {
// in case of a copy
updateReadOnlyPackageFragmentsForCopy((IContainer) source.parent.resource(), root, newFragName);
}
// workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=24505
if (isEmpty && isMove() && !(Util.isExcluded(source) || Util.isExcluded(newFrag))) {
IJavaProject sourceProject = source.getJavaProject();
getDeltaFor(sourceProject).movedFrom(source, newFrag);
IJavaProject destProject = newFrag.getJavaProject();
getDeltaFor(destProject).movedTo(newFrag, source);
}
} catch (JavaModelException e) {
throw e;
} catch (CoreException ce) {
throw new JavaModelException(ce);
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private void saveContent(PackageFragment dest, String destName, TextEdit edits, String sourceEncoding, IFile destFile) throws JavaModelException {
try {
// TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
// fix bug 66898
if (sourceEncoding != null) destFile.setCharset(sourceEncoding, this.progressMonitor);
// end todo
}
catch (CoreException ce) {
// use no encoding
}
// when the file was copied, its read-only flag was preserved -> temporary set it to false
// note this doesn't interfere with repository providers as this is a new resource that cannot be under
// version control yet
Util.setReadOnly(destFile, false);
ICompilationUnit destCU = dest.getCompilationUnit(destName);
applyTextEdit(destCU, edits);
destCU.save(getSubProgressMonitor(1), this.force);
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName) throws JavaModelException {
String[] currPackageName = ((PackageFragment) cu.getParent()).names;
String[] destPackageName = dest.names;
if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
return null; //nothing to change
} else {
// ensure cu is consistent (noop if already consistent)
cu.makeConsistent(this.progressMonitor);
this.parser.setSource(cu);
CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
AST ast = astCU.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
updatePackageStatement(astCU, destPackageName, rewrite, cu);
return rewrite.rewriteAST();
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private void updatePackageStatement(CompilationUnit astCU, String[] pkgName, ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
boolean defaultPackage = pkgName.length == 0;
AST ast = astCU.getAST();
if (defaultPackage) {
// remove existing package statement
PackageDeclaration pkg = astCU.getPackage();
if (pkg != null) {
int pkgStart;
Javadoc javadoc = pkg.getJavadoc();
if (javadoc != null) {
pkgStart = javadoc.getStartPosition() + javadoc.getLength() + 1;
} else {
pkgStart = pkg.getStartPosition();
}
int extendedStart = astCU.getExtendedStartPosition(pkg);
if (pkgStart != extendedStart) {
// keep the comments associated with package declaration
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=247757
String commentSource = cu.getSource().substring(extendedStart, pkgStart);
ASTNode comment = rewriter.createStringPlaceholder(commentSource, ASTNode.PACKAGE_DECLARATION);
rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, comment, null);
} else {
rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, null, null);
}
}
} else {
org.eclipse.jdt.core.dom.PackageDeclaration pkg = astCU.getPackage();
if (pkg != null) {
// rename package statement
Name name = ast.newName(pkgName);
rewriter.set(pkg, PackageDeclaration.NAME_PROPERTY, name, null);
} else {
// create new package statement
pkg = ast.newPackageDeclaration();
pkg.setName(ast.newName(pkgName));
rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, pkg, null);
}
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
private void updateTypeName(ICompilationUnit cu, CompilationUnit astCU, String oldName, String newName, ASTRewrite rewriter) throws JavaModelException {
if (newName != null) {
String oldTypeName= Util.getNameWithoutJavaLikeExtension(oldName);
String newTypeName= Util.getNameWithoutJavaLikeExtension(newName);
AST ast = astCU.getAST();
// update main type name
IType[] types = cu.getTypes();
for (int i = 0, max = types.length; i < max; i++) {
IType currentType = types[i];
if (currentType.getElementName().equals(oldTypeName)) {
AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
if (typeNode != null) {
// rename type
rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
// rename constructors
Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
while (bodyDeclarations.hasNext()) {
Object bodyDeclaration = bodyDeclarations.next();
if (bodyDeclaration instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
if (methodDeclaration.isConstructor()) {
SimpleName methodName = methodDeclaration.getName();
if (methodName.getIdentifier().equals(oldTypeName)) {
rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
}
}
}
}
}
}
}
}
}
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
if (element == null || !element.exists())
error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
if (element.isReadOnly() && (isRename() || isMove()))
error(IJavaModelStatusConstants.READ_ONLY, element);
IResource resource = ((JavaElement) element).resource();
if (resource instanceof IFolder) {
if (resource.isLinked()) {
error(IJavaModelStatusConstants.INVALID_RESOURCE, element);
}
}
int elementType = element.getElementType();
if (elementType == IJavaElement.COMPILATION_UNIT) {
org.eclipse.jdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.jdt.internal.core.CompilationUnit) element;
if (isMove() && compilationUnit.isWorkingCopy() && !compilationUnit.isPrimary())
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
} else if (elementType != IJavaElement.PACKAGE_FRAGMENT) {
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
JavaElement dest = (JavaElement) getDestinationParent(element);
verifyDestination(element, dest);
if (this.renamings != null) {
verifyRenaming(element);
}
}
// in model/org/eclipse/jdt/internal/core/Buffer.java
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
// determine if saving is required
if (isReadOnly() || this.file == null) {
return;
}
if (!hasUnsavedChanges())
return;
// use a platform operation to update the resource contents
try {
String stringContents = getContents();
if (stringContents == null) return;
// Get encoding
String encoding = null;
try {
encoding = this.file.getCharset();
}
catch (CoreException ce) {
// use no encoding
}
// Create bytes array
byte[] bytes = encoding == null
? stringContents.getBytes()
: stringContents.getBytes(encoding);
// Special case for UTF-8 BOM files
// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=110576
if (encoding != null && encoding.equals(org.eclipse.jdt.internal.compiler.util.Util.UTF_8)) {
IContentDescription description;
try {
description = this.file.getContentDescription();
} catch (CoreException e) {
if (e.getStatus().getCode() != IResourceStatus.RESOURCE_NOT_FOUND)
throw e;
// file no longer exist (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=234307 )
description = null;
}
if (description != null && description.getProperty(IContentDescription.BYTE_ORDER_MARK) != null) {
int bomLength= IContentDescription.BOM_UTF_8.length;
byte[] bytesWithBOM= new byte[bytes.length + bomLength];
System.arraycopy(IContentDescription.BOM_UTF_8, 0, bytesWithBOM, 0, bomLength);
System.arraycopy(bytes, 0, bytesWithBOM, bomLength, bytes.length);
bytes= bytesWithBOM;
}
}
// Set file contents
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
if (this.file.exists()) {
this.file.setContents(
stream,
force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
null);
} else {
this.file.create(stream, force, null);
}
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} catch (CoreException e) {
throw new JavaModelException(e);
}
// the resource no longer has unsaved changes
this.flags &= ~ (F_HAS_UNSAVED_CHANGES);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public IAnnotation[] getAnnotations() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
IBinaryAnnotation[] binaryAnnotations = info.getAnnotations();
return getAnnotations(binaryAnnotations, info.getTagBits());
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public ILocalVariable[] getParameters() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
int length = this.parameterTypes.length;
if (length == 0) {
return LocalVariable.NO_LOCAL_VARIABLES;
}
ILocalVariable[] localVariables = new ILocalVariable[length];
char[][] argumentNames = info.getArgumentNames();
if (argumentNames == null || argumentNames.length < length) {
argumentNames = new char[length][];
for (int j = 0; j < length; j++) {
argumentNames[j] = ("arg" + j).toCharArray(); //$NON-NLS-1$
}
}
for (int i= 0; i < length; i++) {
LocalVariable localVariable = new LocalVariable(
this,
new String(argumentNames[i]),
0,
-1,
0,
-1,
this.parameterTypes[i],
null,
-1,
true);
localVariables[i] = localVariable;
IAnnotation[] annotations = getAnnotations(localVariable, info.getParameterAnnotations(i), info.getTagBits());
localVariable.annotations = annotations;
}
return localVariables;
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public IMemberValuePair getDefaultValue() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
Object defaultValue = info.getDefaultValue();
if (defaultValue == null)
return null;
MemberValuePair memberValuePair = new MemberValuePair(getElementName());
memberValuePair.value = Util.getAnnotationMemberValue(this, memberValuePair, defaultValue);
return memberValuePair;
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String[] getExceptionTypes() throws JavaModelException {
if (this.exceptionTypes == null) {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature != null) {
char[] dotBasedSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
this.exceptionTypes = Signature.getThrownExceptionTypes(new String(dotBasedSignature));
}
if (this.exceptionTypes == null || this.exceptionTypes.length == 0) {
char[][] eTypeNames = info.getExceptionTypeNames();
if (eTypeNames == null || eTypeNames.length == 0) {
this.exceptionTypes = CharOperation.NO_STRINGS;
} else {
eTypeNames = ClassFile.translatedNames(eTypeNames);
this.exceptionTypes = new String[eTypeNames.length];
for (int j = 0, length = eTypeNames.length; j < length; j++) {
// 1G01HRY: ITPJCORE:WINNT - method.getExceptionType not in correct format
int nameLength = eTypeNames[j].length;
char[] convertedName = new char[nameLength + 2];
System.arraycopy(eTypeNames[j], 0, convertedName, 1, nameLength);
convertedName[0] = 'L';
convertedName[nameLength + 1] = ';';
this.exceptionTypes[j] = new String(convertedName);
}
}
}
}
return this.exceptionTypes;
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public int getFlags() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
return info.getModifiers();
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String getKey(boolean forceOpen) throws JavaModelException {
return getKey(this, forceOpen);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String[] getParameterNames() throws JavaModelException {
if (this.parameterNames != null)
return this.parameterNames;
// force source mapping if not already done
IType type = (IType) getParent();
SourceMapper mapper = getSourceMapper();
if (mapper != null) {
char[][] paramNames = mapper.getMethodParameterNames(this);
// map source and try to find parameter names
if(paramNames == null) {
IBinaryType info = (IBinaryType) ((BinaryType) getDeclaringType()).getElementInfo();
char[] source = mapper.findSource(type, info);
if (source != null){
mapper.mapSource(type, source, info);
}
paramNames = mapper.getMethodParameterNames(this);
}
// if parameter names exist, convert parameter names to String array
if(paramNames != null) {
String[] names = new String[paramNames.length];
for (int i = 0; i < paramNames.length; i++) {
names[i] = new String(paramNames[i]);
}
return this.parameterNames = names;
}
}
// try to see if we can retrieve the names from the attached javadoc
IBinaryMethod info = (IBinaryMethod) getElementInfo();
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=316937
// Use Signature#getParameterCount() only if the argument names are not already available.
int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
if (this.isConstructor()) {
final IType declaringType = this.getDeclaringType();
if (declaringType.isMember()
&& !Flags.isStatic(declaringType.getFlags())) {
paramCount--; // remove synthetic argument from constructor param count
}
}
if (paramCount != 0) {
// don't try to look for javadoc for synthetic methods
int modifiers = getFlags();
if ((modifiers & ClassFileConstants.AccSynthetic) != 0) {
return this.parameterNames = getRawParameterNames(paramCount);
}
JavadocContents javadocContents = null;
IType declaringType = getDeclaringType();
PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(getJavaProject().getProject());
synchronized (projectInfo.javadocCache) {
javadocContents = (JavadocContents) projectInfo.javadocCache.get(declaringType);
if (javadocContents == null) {
projectInfo.javadocCache.put(declaringType, BinaryType.EMPTY_JAVADOC);
}
}
String methodDoc = null;
if (javadocContents == null) {
long timeOut = 50; // default value
try {
String option = getJavaProject().getOption(JavaCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, true);
if (option != null) {
timeOut = Long.parseLong(option);
}
} catch(NumberFormatException e) {
// ignore
}
if (timeOut == 0) {
// don't try to fetch the values and don't cache either (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671)
return getRawParameterNames(paramCount);
}
final class ParametersNameCollector {
String javadoc;
public void setJavadoc(String s) {
this.javadoc = s;
}
public String getJavadoc() {
return this.javadoc;
}
}
/*
* The declaring type is not in the cache yet. The thread wil retrieve the javadoc contents
*/
final ParametersNameCollector nameCollector = new ParametersNameCollector();
Thread collect = new Thread() {
public void run() {
try {
// this call has a side-effect on the per project info cache
nameCollector.setJavadoc(BinaryMethod.this.getAttachedJavadoc(null));
} catch (JavaModelException e) {
// ignore
}
synchronized(nameCollector) {
nameCollector.notify();
}
}
};
collect.start();
synchronized(nameCollector) {
try {
nameCollector.wait(timeOut);
} catch (InterruptedException e) {
// ignore
}
}
methodDoc = nameCollector.getJavadoc();
} else if (javadocContents != BinaryType.EMPTY_JAVADOC){
// need to extract the part relative to the binary method since javadoc contains the javadoc for the declaring type
try {
methodDoc = javadocContents.getMethodDoc(this);
} catch(JavaModelException e) {
javadocContents = null;
}
}
if (methodDoc != null) {
final int indexOfOpenParen = methodDoc.indexOf('(');
if (indexOfOpenParen != -1) {
final int indexOfClosingParen = methodDoc.indexOf(')', indexOfOpenParen);
if (indexOfClosingParen != -1) {
final char[] paramsSource =
CharOperation.replace(
methodDoc.substring(indexOfOpenParen + 1, indexOfClosingParen).toCharArray(),
" ".toCharArray(), //$NON-NLS-1$
new char[] {' '});
final char[][] params = splitParameters(paramsSource, paramCount);
final int paramsLength = params.length;
String[] names = new String[paramsLength];
for (int i = 0; i < paramsLength; i++) {
final char[] param = params[i];
int indexOfSpace = CharOperation.lastIndexOf(' ', param);
if (indexOfSpace != -1) {
names[i] = String.valueOf(param, indexOfSpace + 1, param.length - indexOfSpace -1);
} else {
names[i] = "arg" + i; //$NON-NLS-1$
}
}
return this.parameterNames = names;
}
}
}
// let's see if we can retrieve them from the debug infos
char[][] argumentNames = info.getArgumentNames();
if (argumentNames != null && argumentNames.length == paramCount) {
String[] names = new String[paramCount];
for (int i = 0; i < paramCount; i++) {
names[i] = new String(argumentNames[i]);
}
return this.parameterNames = names;
}
}
// If still no parameter names, produce fake ones, but don't cache them (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671)
return getRawParameterNames(paramCount);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public ITypeParameter[] getTypeParameters() throws JavaModelException {
String[] typeParameterSignatures = getTypeParameterSignatures();
int length = typeParameterSignatures.length;
if (length == 0) return TypeParameter.NO_TYPE_PARAMETERS;
ITypeParameter[] typeParameters = new ITypeParameter[length];
for (int i = 0; i < typeParameterSignatures.length; i++) {
String typeParameterName = Signature.getTypeVariable(typeParameterSignatures[i]);
typeParameters[i] = new TypeParameter(this, typeParameterName);
}
return typeParameters;
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String[] getTypeParameterSignatures() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
char[] genericSignature = info.getGenericSignature();
if (genericSignature == null)
return CharOperation.NO_STRINGS;
char[] dotBasedSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
char[][] typeParams = Signature.getTypeParameters(dotBasedSignature);
return CharOperation.toStrings(typeParams);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String[] getRawParameterNames() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
return getRawParameterNames(paramCount);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String getReturnType() throws JavaModelException {
if (this.returnType == null) {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
this.returnType = getReturnType(info);
}
return this.returnType;
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String getSignature() throws JavaModelException {
IBinaryMethod info = (IBinaryMethod) getElementInfo();
return new String(info.getMethodDescriptor());
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public boolean isConstructor() throws JavaModelException {
if (!getElementName().equals(this.parent.getElementName())) {
// faster than reaching the info
return false;
}
IBinaryMethod info = (IBinaryMethod) getElementInfo();
return info.isConstructor();
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public boolean isMainMethod() throws JavaModelException {
return this.isMainMethod(this);
}
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
JavadocContents javadocContents = ((BinaryType) this.getDeclaringType()).getJavadocContents(monitor);
if (javadocContents == null) return null;
return javadocContents.getMethodDoc(this);
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public IAnnotation[] getAnnotations() throws JavaModelException {
return this.annotations;
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
private IAnnotation getAnnotation(final org.eclipse.jdt.internal.compiler.ast.Annotation annotation, JavaElement parentElement) {
final int typeStart = annotation.type.sourceStart();
final int typeEnd = annotation.type.sourceEnd();
final int sourceStart = annotation.sourceStart();
final int sourceEnd = annotation.declarationSourceEnd;
class LocalVarAnnotation extends Annotation {
IMemberValuePair[] memberValuePairs;
public LocalVarAnnotation(JavaElement localVar, String elementName) {
super(localVar, elementName);
}
public IMemberValuePair[] getMemberValuePairs() throws JavaModelException {
return this.memberValuePairs;
}
public ISourceRange getNameRange() throws JavaModelException {
return new SourceRange(typeStart, typeEnd - typeStart + 1);
}
public ISourceRange getSourceRange() throws JavaModelException {
return new SourceRange(sourceStart, sourceEnd - sourceStart + 1);
}
public boolean exists() {
return this.parent.exists();
}
}
String annotationName = new String(CharOperation.concatWith(annotation.type.getTypeName(), '.'));
LocalVarAnnotation localVarAnnotation = new LocalVarAnnotation(parentElement, annotationName);
org.eclipse.jdt.internal.compiler.ast.MemberValuePair[] astMemberValuePairs = annotation.memberValuePairs();
int length;
IMemberValuePair[] memberValuePairs;
if (astMemberValuePairs == null || (length = astMemberValuePairs.length) == 0) {
memberValuePairs = Annotation.NO_MEMBER_VALUE_PAIRS;
} else {
memberValuePairs = new IMemberValuePair[length];
for (int i = 0; i < length; i++) {
org.eclipse.jdt.internal.compiler.ast.MemberValuePair astMemberValuePair = astMemberValuePairs[i];
MemberValuePair memberValuePair = new MemberValuePair(new String(astMemberValuePair.name));
memberValuePair.value = getAnnotationMemberValue(memberValuePair, astMemberValuePair.value, localVarAnnotation);
memberValuePairs[i] = memberValuePair;
}
}
localVarAnnotation.memberValuePairs = memberValuePairs;
return localVarAnnotation;
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public IMemberValuePair[] getMemberValuePairs() throws JavaModelException {
return this.memberValuePairs;
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public ISourceRange getNameRange() throws JavaModelException {
return new SourceRange(typeStart, typeEnd - typeStart + 1);
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public ISourceRange getSourceRange() throws JavaModelException {
return new SourceRange(sourceStart, sourceEnd - sourceStart + 1);
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public String getSource() throws JavaModelException {
IOpenable openable = this.parent.getOpenableParent();
IBuffer buffer = openable.getBuffer();
if (buffer == null) {
return null;
}
ISourceRange range = getSourceRange();
int offset = range.getOffset();
int length = range.getLength();
if (offset == -1 || length == 0 ) {
return null;
}
try {
return buffer.getText(offset, length);
} catch(RuntimeException e) {
return null;
}
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public ISourceRange getSourceRange() throws JavaModelException {
if (this.declarationSourceEnd == -1) {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
ClassFile classFile = (ClassFile)getClassFile();
if (classFile != null) {
classFile.getBuffer();
return mapper.getSourceRange(this);
}
}
return SourceMapper.UNKNOWN_RANGE;
}
return new SourceRange(this.declarationSourceStart, this.declarationSourceEnd-this.declarationSourceStart+1);
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public IResource getUnderlyingResource() throws JavaModelException {
return this.parent.getUnderlyingResource();
}
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
public boolean isStructureKnown() throws JavaModelException {
return true;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
JarPackageFragmentRoot root = (JarPackageFragmentRoot) getParent();
JarPackageFragmentRootInfo parentInfo = (JarPackageFragmentRootInfo) root.getElementInfo();
ArrayList[] entries = (ArrayList[]) parentInfo.rawPackageInfo.get(this.names);
if (entries == null)
throw newNotPresentException();
JarPackageFragmentInfo fragInfo = (JarPackageFragmentInfo) info;
// compute children
fragInfo.setChildren(computeChildren(entries[0/*class files*/]));
// compute non-Java resources
fragInfo.setNonJavaResources(computeNonJavaResources(entries[1/*non Java resources*/]));
newElements.put(this, fragInfo);
return true;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
public boolean containsJavaResources() throws JavaModelException {
return ((JarPackageFragmentInfo) getElementInfo()).containsJavaResources();
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
public ICompilationUnit createCompilationUnit(String cuName, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
public IClassFile[] getClassFiles() throws JavaModelException {
ArrayList list = getChildrenOfType(CLASS_FILE);
IClassFile[] array= new IClassFile[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
public Object[] getNonJavaResources() throws JavaModelException {
if (isDefaultPackage()) {
// We don't want to show non java resources of the default package (see PR #1G58NB8)
return JavaElementInfo.NO_NON_JAVA_RESOURCES;
} else {
return storedNonJavaResources();
}
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
protected Object[] storedNonJavaResources() throws JavaModelException {
return ((JarPackageFragmentInfo) getElementInfo()).getNonJavaResources();
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public void close() throws JavaModelException {
JavaModelManager.getJavaModelManager().removeInfoAndChildren(this);
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public IJavaElement[] getChildren() throws JavaModelException {
Object elementInfo = getElementInfo();
if (elementInfo instanceof JavaElementInfo) {
return ((JavaElementInfo)elementInfo).getChildren();
} else {
return NO_ELEMENTS;
}
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public ArrayList getChildrenOfType(int type) throws JavaModelException {
IJavaElement[] children = getChildren();
int size = children.length;
ArrayList list = new ArrayList(size);
for (int i = 0; i < size; ++i) {
JavaElement elt = (JavaElement)children[i];
if (elt.getElementType() == type) {
list.add(elt);
}
}
return list;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public Object getElementInfo() throws JavaModelException {
return getElementInfo(null);
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
Object info = manager.getInfo(this);
if (info != null) return info;
return openWhenClosed(createElementInfo(), monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
protected IJavaElement getSourceElementAt(int position) throws JavaModelException {
if (this instanceof ISourceReference) {
IJavaElement[] children = getChildren();
for (int i = children.length-1; i >= 0; i--) {
IJavaElement aChild = children[i];
if (aChild instanceof SourceRefElement) {
SourceRefElement child = (SourceRefElement) children[i];
ISourceRange range = child.getSourceRange();
int start = range.getOffset();
int end = start + range.getLength();
if (start <= position && position <= end) {
if (child instanceof IField) {
// check muti-declaration case (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=39943)
int declarationStart = start;
SourceRefElement candidate = null;
do {
// check name range
range = ((IField)child).getNameRange();
if (position <= range.getOffset() + range.getLength()) {
candidate = child;
} else {
return candidate == null ? child.getSourceElementAt(position) : candidate.getSourceElementAt(position);
}
child = --i>=0 ? (SourceRefElement) children[i] : null;
} while (child != null && child.getSourceRange().getOffset() == declarationStart);
// position in field's type: use first field
return candidate.getSourceElementAt(position);
} else if (child instanceof IParent) {
return child.getSourceElementAt(position);
} else {
return child;
}
}
}
}
} else {
// should not happen
Assert.isTrue(false);
}
return this;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public boolean hasChildren() throws JavaModelException {
// if I am not open, return true to avoid opening (case of a Java project, a compilation unit or a class file).
// also see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
Object elementInfo = JavaModelManager.getJavaModelManager().getInfo(this);
if (elementInfo instanceof JavaElementInfo) {
return ((JavaElementInfo)elementInfo).getChildren().length > 0;
} else {
return true;
}
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
protected Object openWhenClosed(Object info, IProgressMonitor monitor) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
boolean hadTemporaryCache = manager.hasTemporaryCache();
try {
HashMap newElements = manager.getTemporaryCache();
generateInfos(info, newElements, monitor);
if (info == null) {
info = newElements.get(this);
}
if (info == null) { // a source ref element could not be opened
// close the buffer that was opened for the openable parent
// close only the openable's buffer (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62854)
Openable openable = (Openable) getOpenable();
if (newElements.containsKey(openable)) {
openable.closeBuffer();
}
throw newNotPresentException();
}
if (!hadTemporaryCache) {
manager.putInfos(this, newElements);
}
} finally {
if (!hadTemporaryCache) {
manager.resetTemporaryCache();
}
}
return info;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
protected URL getJavadocBaseLocation() throws JavaModelException {
IPackageFragmentRoot root= (IPackageFragmentRoot) getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (root == null) {
return null;
}
if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
IClasspathEntry entry= null;
try {
entry= root.getResolvedClasspathEntry();
URL url = getLibraryJavadocLocation(entry);
if (url != null) {
return url;
}
}
catch(JavaModelException jme) {
// Proceed with raw classpath
}
entry= root.getRawClasspathEntry();
switch (entry.getEntryKind()) {
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
return getLibraryJavadocLocation(entry);
default:
return null;
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
protected static URL getLibraryJavadocLocation(IClasspathEntry entry) throws JavaModelException {
switch(entry.getEntryKind()) {
case IClasspathEntry.CPE_LIBRARY :
case IClasspathEntry.CPE_VARIABLE :
break;
default :
throw new IllegalArgumentException("Entry must be of kind CPE_LIBRARY or CPE_VARIABLE"); //$NON-NLS-1$
}
IClasspathAttribute[] extraAttributes= entry.getExtraAttributes();
for (int i= 0; i < extraAttributes.length; i++) {
IClasspathAttribute attrib= extraAttributes[i];
if (IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
String value = attrib.getValue();
try {
return new URL(value);
} catch (MalformedURLException e) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value));
}
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaElement.java
protected String getURLContents(String docUrlValue) throws JavaModelException {
InputStream stream = null;
JarURLConnection connection2 = null;
try {
URL docUrl = new URL(docUrlValue);
URLConnection connection = docUrl.openConnection();
Class[] parameterTypes = new Class[]{int.class};
Integer timeoutVal = new Integer(10000);
// set the connect and read timeouts using reflection since these methods are not available in java 1.4
Class URLClass = connection.getClass();
try {
Method connectTimeoutMethod = URLClass.getDeclaredMethod("setConnectTimeout", parameterTypes); //$NON-NLS-1$
Method readTimeoutMethod = URLClass.getDeclaredMethod("setReadTimeout", parameterTypes); //$NON-NLS-1$
connectTimeoutMethod.invoke(connection, new Object[]{timeoutVal});
readTimeoutMethod.invoke(connection, new Object[]{timeoutVal});
} catch (SecurityException e) {
// ignore
} catch (IllegalArgumentException e) {
// ignore
} catch (NoSuchMethodException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
} catch (InvocationTargetException e) {
// ignore
}
if (connection instanceof JarURLConnection) {
connection2 = (JarURLConnection) connection;
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=156307
connection.setUseCaches(false);
}
try {
stream = new BufferedInputStream(connection.getInputStream());
} catch (IllegalArgumentException e) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
return null;
} catch (NullPointerException e) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
return null;
}
String encoding = connection.getContentEncoding();
byte[] contents = org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, connection.getContentLength());
if (encoding == null) {
int index = getIndexOf(contents, CONTENT_TYPE, 0);
if (index != -1) {
index = getIndexOf(contents, CONTENT, index);
if (index != -1) {
int offset = index + CONTENT.length;
int index2 = getIndexOf(contents, CLOSING_DOUBLE_QUOTE, offset);
if (index2 != -1) {
final int charsetIndex = getIndexOf(contents, CHARSET, offset);
if (charsetIndex != -1) {
int start = charsetIndex + CHARSET.length;
encoding = new String(contents, start, index2 - start, org.eclipse.jdt.internal.compiler.util.Util.UTF_8);
}
}
}
}
}
try {
if (encoding == null) {
encoding = getJavaProject().getProject().getDefaultCharset();
}
} catch (CoreException e) {
// ignore
}
if (contents != null) {
if (encoding != null) {
return new String(contents, encoding);
} else {
// platform encoding is used
return new String(contents);
}
}
} catch (SocketTimeoutException e) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this));
} catch (MalformedURLException e) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this));
} catch (FileNotFoundException e) {
// ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559
} catch(SocketException e) {
// ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
} catch(UnknownHostException e) {
// ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
} catch(ProtocolException e) {
// ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
} catch(IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
if (connection2 != null) {
try {
connection2.getJarFile().close();
} catch(IOException e) {
// ignore
} catch(IllegalStateException e) {
/*
* ignore. Can happen in case the stream.close() did close the jar file
* see https://bugs.eclipse.org/bugs/show_bug.cgi?id=140750
*/
}
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public String[] getCategories() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that categories are computed
((ClassFile)getClassFile()).getBuffer();
if (mapper.categories != null) {
String[] categories = (String[]) mapper.categories.get(this);
if (categories != null)
return categories;
}
}
return CharOperation.NO_STRINGS;
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public ISourceRange getNameRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
((ClassFile)getClassFile()).getBuffer();
return mapper.getNameRange(this);
} else {
return SourceMapper.UNKNOWN_RANGE;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public ISourceRange getSourceRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
((ClassFile)getClassFile()).getBuffer();
return mapper.getSourceRange(this);
} else {
return SourceMapper.UNKNOWN_RANGE;
}
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public boolean isStructureKnown() throws JavaModelException {
return ((IJavaElement)getOpenableParent()).isStructureKnown();
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
public void setContents(String contents, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
// add compilation units/class files from resources
HashSet vChildren = new HashSet();
int kind = getKind();
try {
PackageFragmentRoot root = getPackageFragmentRoot();
char[][] inclusionPatterns = root.fullInclusionPatternChars();
char[][] exclusionPatterns = root.fullExclusionPatternChars();
IResource[] members = ((IContainer) underlyingResource).members();
int length = members.length;
if (length > 0) {
IJavaProject project = getJavaProject();
String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
for (int i = 0; i < length; i++) {
IResource child = members[i];
if (child.getType() != IResource.FOLDER
&& !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
IJavaElement childElement;
if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
vChildren.add(childElement);
} else if (kind == IPackageFragmentRoot.K_BINARY && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
childElement = getClassFile(child.getName());
vChildren.add(childElement);
}
}
}
}
} catch (CoreException e) {
throw new JavaModelException(e);
}
if (kind == IPackageFragmentRoot.K_SOURCE) {
// add primary compilation units
ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
ICompilationUnit primary = primaryCompilationUnits[i];
vChildren.add(primary);
}
}
IJavaElement[] children = new IJavaElement[vChildren.size()];
vChildren.toArray(children);
info.setChildren(children);
return true;
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public boolean containsJavaResources() throws JavaModelException {
return ((PackageFragmentInfo) getElementInfo()).containsJavaResources();
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] containers= new IJavaElement[] {container};
IJavaElement[] siblings= null;
if (sibling != null) {
siblings= new IJavaElement[] {sibling};
}
String[] renamings= null;
if (rename != null) {
renamings= new String[] {rename};
}
getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public ICompilationUnit createCompilationUnit(String cuName, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException {
CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, cuName, contents, force);
op.runOperation(monitor);
return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
IJavaElement[] elements = new IJavaElement[] {this};
getJavaModel().delete(elements, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public IClassFile[] getClassFiles() throws JavaModelException {
if (getKind() == IPackageFragmentRoot.K_SOURCE) {
return NO_CLASSFILES;
}
ArrayList list = getChildrenOfType(CLASS_FILE);
IClassFile[] array= new IClassFile[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
if (getKind() == IPackageFragmentRoot.K_BINARY) {
return NO_COMPILATION_UNITS;
}
ArrayList list = getChildrenOfType(COMPILATION_UNIT);
ICompilationUnit[] array= new ICompilationUnit[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public int getKind() throws JavaModelException {
return ((IPackageFragmentRoot)getParent()).getKind();
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public Object[] getNonJavaResources() throws JavaModelException {
if (isDefaultPackage()) {
// We don't want to show non java resources of the default package (see PR #1G58NB8)
return JavaElementInfo.NO_NON_JAVA_RESOURCES;
} else {
return ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(resource(), getPackageFragmentRoot());
}
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public IResource getUnderlyingResource() throws JavaModelException {
IResource rootResource = this.parent.getUnderlyingResource();
if (rootResource == null) {
//jar package fragment root that has no associated resource
return null;
}
// the underlying resource may be a folder or a project (in the case that the project folder
// is atually the package fragment root)
if (rootResource.getType() == IResource.FOLDER || rootResource.getType() == IResource.PROJECT) {
IContainer folder = (IContainer) rootResource;
String[] segs = this.names;
for (int i = 0; i < segs.length; ++i) {
IResource child = folder.findMember(segs[i]);
if (child == null || child.getType() != IResource.FOLDER) {
throw newNotPresentException();
}
folder = (IFolder) child;
}
return folder;
} else {
return rootResource;
}
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public boolean hasChildren() throws JavaModelException {
return getChildren().length > 0;
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public boolean hasSubpackages() throws JavaModelException {
IJavaElement[] packages= ((IPackageFragmentRoot)getParent()).getChildren();
int namesLength = this.names.length;
nextPackage: for (int i= 0, length = packages.length; i < length; i++) {
String[] otherNames = ((PackageFragment) packages[i]).names;
if (otherNames.length <= namesLength) continue nextPackage;
for (int j = 0; j < namesLength; j++)
if (!this.names[j].equals(otherNames[j]))
continue nextPackage;
return true;
}
return false;
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] containers= new IJavaElement[] {container};
IJavaElement[] siblings= null;
if (sibling != null) {
siblings= new IJavaElement[] {sibling};
}
String[] renamings= null;
if (rename != null) {
renamings= new String[] {rename};
}
getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (newName == null) {
throw new IllegalArgumentException(Messages.element_nullName);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] dests= new IJavaElement[] {getParent()};
String[] renamings= new String[] {newName};
getJavaModel().rename(elements, dests, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public String getAttachedJavadoc(IProgressMonitor monitor) throws JavaModelException {
PerProjectInfo projectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(getJavaProject().getProject());
String cachedJavadoc = null;
synchronized (projectInfo.javadocCache) {
cachedJavadoc = (String) projectInfo.javadocCache.get(this);
}
if (cachedJavadoc != null) {
return cachedJavadoc;
}
URL baseLocation= getJavadocBaseLocation();
if (baseLocation == null) {
return null;
}
StringBuffer pathBuffer = new StringBuffer(baseLocation.toExternalForm());
if (!(pathBuffer.charAt(pathBuffer.length() - 1) == '/')) {
pathBuffer.append('/');
}
String packPath= getElementName().replace('.', '/');
pathBuffer.append(packPath).append('/').append(JavadocConstants.PACKAGE_FILE_NAME);
if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
final String contents = getURLContents(String.valueOf(pathBuffer));
if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException();
if (contents == null) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this));
synchronized (projectInfo.javadocCache) {
projectInfo.javadocCache.put(this, contents);
}
return contents;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
protected boolean computeChildren(OpenableElementInfo info, IResource underlyingResource) throws JavaModelException {
HashtableOfArrayToObject rawPackageInfo = new HashtableOfArrayToObject();
IJavaElement[] children;
ZipFile jar = null;
try {
IJavaProject project = getJavaProject();
String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
String compliance = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
jar = getJar();
// always create the default package
rawPackageInfo.put(CharOperation.NO_STRINGS, new ArrayList[] { EMPTY_LIST, EMPTY_LIST });
for (Enumeration e= jar.entries(); e.hasMoreElements();) {
ZipEntry member= (ZipEntry) e.nextElement();
initRawPackageInfo(rawPackageInfo, member.getName(), member.isDirectory(), sourceLevel, compliance);
}
// loop through all of referenced packages, creating package fragments if necessary
// and cache the entry names in the rawPackageInfo table
children = new IJavaElement[rawPackageInfo.size()];
int index = 0;
for (int i = 0, length = rawPackageInfo.keyTable.length; i < length; i++) {
String[] pkgName = (String[]) rawPackageInfo.keyTable[i];
if (pkgName == null) continue;
children[index++] = getPackageFragment(pkgName);
}
} catch (CoreException e) {
if (e.getCause() instanceof ZipException) {
// not a ZIP archive, leave the children empty
Util.log(IStatus.ERROR, "Invalid ZIP archive: " + toStringWithAncestors()); //$NON-NLS-1$
children = NO_ELEMENTS;
} else if (e instanceof JavaModelException) {
throw (JavaModelException)e;
} else {
throw new JavaModelException(e);
}
} finally {
JavaModelManager.getJavaModelManager().closeZipFile(jar);
}
info.setChildren(children);
((JarPackageFragmentRootInfo) info).rawPackageInfo = rawPackageInfo;
return true;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
int internalKind() throws JavaModelException {
return IPackageFragmentRoot.K_BINARY;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
public Object[] getNonJavaResources() throws JavaModelException {
// We want to show non java resources of the default package at the root (see PR #1G58NB8)
Object[] defaultPkgResources = ((JarPackageFragment) getPackageFragment(CharOperation.NO_STRINGS)).storedNonJavaResources();
int length = defaultPkgResources.length;
if (length == 0)
return defaultPkgResources;
Object[] nonJavaResources = new Object[length];
for (int i = 0; i < length; i++) {
JarEntryResource nonJavaResource = (JarEntryResource) defaultPkgResources[i];
nonJavaResources[i] = nonJavaResource.clone(this);
}
return nonJavaResources;
}
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
public IResource getUnderlyingResource() throws JavaModelException {
if (isExternal()) {
if (!exists()) throw newNotPresentException();
return null;
} else {
return super.getUnderlyingResource();
}
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
public String getTypeDoc() throws JavaModelException {
if (this.content == null) return null;
synchronized (this) {
if (this.typeDocRange == null) {
computeTypeRange();
}
}
if (this.typeDocRange != null) {
if (this.typeDocRange == UNKNOWN_FORMAT) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, this.type));
return String.valueOf(CharOperation.subarray(this.content, this.typeDocRange[0], this.typeDocRange[1]));
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
public String getFieldDoc(IField child) throws JavaModelException {
if (this.content == null) return null;
int[] range = null;
synchronized (this) {
if (this.fieldDocRanges == null) {
this.fieldDocRanges = new HashtableOfObjectToIntArray();
} else {
range = this.fieldDocRanges.get(child);
}
if (range == null) {
range = computeFieldRange(child);
this.fieldDocRanges.put(child, range);
}
}
if (range != null) {
if (range == UNKNOWN_FORMAT) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, child));
return String.valueOf(CharOperation.subarray(this.content, range[0], range[1]));
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
public String getMethodDoc(IMethod child) throws JavaModelException {
if (this.content == null) return null;
int[] range = null;
synchronized (this) {
if (this.methodDocRanges == null) {
this.methodDocRanges = new HashtableOfObjectToIntArray();
} else {
range = this.methodDocRanges.get(child);
}
if (range == null) {
range = computeMethodRange(child);
this.methodDocRanges.put(child, range);
}
}
if (range != null) {
if (range == UNKNOWN_FORMAT) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, child));
}
return String.valueOf(CharOperation.subarray(this.content, range[0], range[1]));
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
private int[] computeChildRange(char[] anchor, int indexOfSectionBottom) throws JavaModelException {
// checks each known anchor locations
if (this.tempAnchorIndexesCount > 0) {
for (int i = 0; i < this.tempAnchorIndexesCount; i++) {
int anchorEndStart = this.tempAnchorIndexes[i];
if (anchorEndStart != -1 && CharOperation.prefixEquals(anchor, this.content, false, anchorEndStart)) {
this.tempAnchorIndexes[i] = -1;
return computeChildRange(anchorEndStart, anchor, indexOfSectionBottom);
}
}
}
int fromIndex = this.tempLastAnchorFoundIndex;
int index;
// check each next unknown anchor locations
while ((index = CharOperation.indexOf(JavadocConstants.ANCHOR_PREFIX_START, this.content, false, fromIndex)) != -1 && (index < indexOfSectionBottom || indexOfSectionBottom == -1)) {
fromIndex = index + 1;
int anchorEndStart = index + JavadocConstants.ANCHOR_PREFIX_START_LENGHT;
this.tempLastAnchorFoundIndex = anchorEndStart;
if (CharOperation.prefixEquals(anchor, this.content, false, anchorEndStart)) {
return computeChildRange(anchorEndStart, anchor, indexOfSectionBottom);
} else {
if (this.tempAnchorIndexes.length == this.tempAnchorIndexesCount) {
System.arraycopy(this.tempAnchorIndexes, 0, this.tempAnchorIndexes = new int[this.tempAnchorIndexesCount + 20], 0, this.tempAnchorIndexesCount);
}
this.tempAnchorIndexes[this.tempAnchorIndexesCount++] = anchorEndStart;
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
private int[] computeFieldRange(IField field) throws JavaModelException {
if (!this.hasComputedChildrenSections) {
computeChildrenSections();
}
StringBuffer buffer = new StringBuffer(field.getElementName());
buffer.append(JavadocConstants.ANCHOR_PREFIX_END);
char[] anchor = String.valueOf(buffer).toCharArray();
int[] range = null;
if (this.indexOfFieldDetails == -1 || this.indexOfFieldsBottom == -1) {
// the detail section has no top or bottom, so the doc has an unknown format
if (this.unknownFormatAnchorIndexes == null) {
this.unknownFormatAnchorIndexes = new int[this.type.getChildren().length];
this.unknownFormatAnchorIndexesCount = 0;
this.unknownFormatLastAnchorFoundIndex = this.childrenStart;
}
this.tempAnchorIndexes = this.unknownFormatAnchorIndexes;
this.tempAnchorIndexesCount = this.unknownFormatAnchorIndexesCount;
this.tempLastAnchorFoundIndex = this.unknownFormatLastAnchorFoundIndex;
range = computeChildRange(anchor, this.indexOfFieldsBottom);
this.unknownFormatLastAnchorFoundIndex = this.tempLastAnchorFoundIndex;
this.unknownFormatAnchorIndexesCount = this.tempAnchorIndexesCount;
this.unknownFormatAnchorIndexes = this.tempAnchorIndexes;
} else {
if (this.fieldAnchorIndexes == null) {
this.fieldAnchorIndexes = new int[this.type.getFields().length];
this.fieldAnchorIndexesCount = 0;
this.fieldLastAnchorFoundIndex = this.indexOfFieldDetails;
}
this.tempAnchorIndexes = this.fieldAnchorIndexes;
this.tempAnchorIndexesCount = this.fieldAnchorIndexesCount;
this.tempLastAnchorFoundIndex = this.fieldLastAnchorFoundIndex;
range = computeChildRange(anchor, this.indexOfFieldsBottom);
this.fieldLastAnchorFoundIndex = this.tempLastAnchorFoundIndex;
this.fieldAnchorIndexesCount = this.tempAnchorIndexesCount;
this.fieldAnchorIndexes = this.tempAnchorIndexes;
}
return range;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
private int[] computeMethodRange(IMethod method) throws JavaModelException {
if (!this.hasComputedChildrenSections) {
computeChildrenSections();
}
char[] anchor = computeMethodAnchorPrefixEnd((BinaryMethod)method).toCharArray();
int[] range = null;
if (this.indexOfAllMethodsTop == -1 || this.indexOfAllMethodsBottom == -1) {
// the detail section has no top or bottom, so the doc has an unknown format
if (this.unknownFormatAnchorIndexes == null) {
this.unknownFormatAnchorIndexes = new int[this.type.getChildren().length];
this.unknownFormatAnchorIndexesCount = 0;
this.unknownFormatLastAnchorFoundIndex = this.childrenStart;
}
this.tempAnchorIndexes = this.unknownFormatAnchorIndexes;
this.tempAnchorIndexesCount = this.unknownFormatAnchorIndexesCount;
this.tempLastAnchorFoundIndex = this.unknownFormatLastAnchorFoundIndex;
range = computeChildRange(anchor, this.indexOfFieldsBottom);
this.unknownFormatLastAnchorFoundIndex = this.tempLastAnchorFoundIndex;
this.unknownFormatAnchorIndexesCount = this.tempAnchorIndexesCount;
this.unknownFormatAnchorIndexes = this.tempAnchorIndexes;
} else {
if (this.methodAnchorIndexes == null) {
this.methodAnchorIndexes = new int[this.type.getFields().length];
this.methodAnchorIndexesCount = 0;
this.methodLastAnchorFoundIndex = this.indexOfAllMethodsTop;
}
this.tempAnchorIndexes = this.methodAnchorIndexes;
this.tempAnchorIndexesCount = this.methodAnchorIndexesCount;
this.tempLastAnchorFoundIndex = this.methodLastAnchorFoundIndex;
range = computeChildRange(anchor, this.indexOfAllMethodsBottom);
this.methodLastAnchorFoundIndex = this.tempLastAnchorFoundIndex;
this.methodAnchorIndexesCount = this.tempAnchorIndexesCount;
this.methodAnchorIndexes = this.tempAnchorIndexes;
}
return range;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
private String computeMethodAnchorPrefixEnd(BinaryMethod method) throws JavaModelException {
String typeQualifiedName = null;
if (this.type.isMember()) {
IType currentType = this.type;
StringBuffer buffer = new StringBuffer();
while (currentType != null) {
buffer.insert(0, currentType.getElementName());
currentType = currentType.getDeclaringType();
if (currentType != null) {
buffer.insert(0, '.');
}
}
typeQualifiedName = new String(buffer.toString());
} else {
typeQualifiedName = this.type.getElementName();
}
String methodName = method.getElementName();
if (method.isConstructor()) {
methodName = typeQualifiedName;
}
IBinaryMethod info = (IBinaryMethod) method.getElementInfo();
char[] genericSignature = info.getGenericSignature();
String anchor = null;
if (genericSignature != null) {
genericSignature = CharOperation.replaceOnCopy(genericSignature, '/', '.');
anchor = Util.toAnchor(0, genericSignature, methodName, Flags.isVarargs(method.getFlags()));
if (anchor == null) throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.UNKNOWN_JAVADOC_FORMAT, method));
} else {
anchor = Signature.toString(method.getSignature().replace('/', '.'), methodName, null, true, false, Flags.isVarargs(method.getFlags()));
}
IType declaringType = this.type;
if (declaringType.isMember()) {
int depth = 0;
// might need to remove a part of the signature corresponding to the synthetic argument (only for constructor)
if (method.isConstructor() && !Flags.isStatic(declaringType.getFlags())) {
depth++;
}
if (depth != 0) {
// depth is 1
int indexOfOpeningParen = anchor.indexOf('(');
if (indexOfOpeningParen == -1) {
// should not happen as this is a method signature
return null;
}
int index = indexOfOpeningParen;
indexOfOpeningParen++;
int indexOfComma = anchor.indexOf(',', index);
if (indexOfComma != -1) {
index = indexOfComma + 2;
anchor = anchor.substring(0, indexOfOpeningParen) + anchor.substring(index);
}
}
}
return anchor + JavadocConstants.ANCHOR_PREFIX_END;
}
// in model/org/eclipse/jdt/internal/core/JavadocContents.java
private void computeTypeRange() throws JavaModelException {
final int indexOfStartOfClassData = CharOperation.indexOf(JavadocConstants.START_OF_CLASS_DATA, this.content, false);
if (indexOfStartOfClassData == -1) {
this.typeDocRange = UNKNOWN_FORMAT;
return;
}
int indexOfNextSeparator = CharOperation.indexOf(JavadocConstants.SEPARATOR_START, this.content, false, indexOfStartOfClassData);
if (indexOfNextSeparator == -1) {
this.typeDocRange = UNKNOWN_FORMAT;
return;
}
int indexOfNextSummary = CharOperation.indexOf(JavadocConstants.NESTED_CLASS_SUMMARY, this.content, false, indexOfNextSeparator);
if (indexOfNextSummary == -1 && this.type.isEnum()) {
// try to find enum constant summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.ENUM_CONSTANT_SUMMARY, this.content, false, indexOfNextSeparator);
}
if (indexOfNextSummary == -1 && this.type.isAnnotation()) {
// try to find required enum constant summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.ANNOTATION_TYPE_REQUIRED_MEMBER_SUMMARY, this.content, false, indexOfNextSeparator);
if (indexOfNextSummary == -1) {
// try to find optional enum constant summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.ANNOTATION_TYPE_OPTIONAL_MEMBER_SUMMARY, this.content, false, indexOfNextSeparator);
}
}
if (indexOfNextSummary == -1) {
// try to find field summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.FIELD_SUMMARY, this.content, false, indexOfNextSeparator);
}
if (indexOfNextSummary == -1) {
// try to find constructor summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.CONSTRUCTOR_SUMMARY, this.content, false, indexOfNextSeparator);
}
if (indexOfNextSummary == -1) {
// try to find method summary start
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.METHOD_SUMMARY, this.content, false, indexOfNextSeparator);
}
if (indexOfNextSummary == -1) {
// we take the end of class data
indexOfNextSummary = CharOperation.indexOf(JavadocConstants.END_OF_CLASS_DATA, this.content, false, indexOfNextSeparator);
} else {
// improve performance of computation of children ranges
this.childrenStart = indexOfNextSummary + 1;
}
if (indexOfNextSummary == -1) {
this.typeDocRange = UNKNOWN_FORMAT;
return;
}
/*
* Check out to cut off the hierarchy see 119844
* We remove what the contents between the start of class data and the first <P>
*/
int start = indexOfStartOfClassData + JavadocConstants.START_OF_CLASS_DATA_LENGTH;
int indexOfFirstParagraph = CharOperation.indexOf("<P>".toCharArray(), this.content, false, start); //$NON-NLS-1$
if (indexOfFirstParagraph != -1 && indexOfFirstParagraph < indexOfNextSummary) {
start = indexOfFirstParagraph;
}
this.typeDocRange = new int[]{start, indexOfNextSummary};
}
// in model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java
protected void executeOperation() throws JavaModelException {
this.typeHierarchy.refresh(this);
}
// in model/org/eclipse/jdt/internal/core/Member.java
public String[] getCategories() throws JavaModelException {
IType type = (IType) getAncestor(IJavaElement.TYPE);
if (type == null) return CharOperation.NO_STRINGS;
if (type.isBinary()) {
return CharOperation.NO_STRINGS;
} else {
SourceTypeElementInfo info = (SourceTypeElementInfo) ((SourceType) type).getElementInfo();
HashMap map = info.getCategories();
if (map == null) return CharOperation.NO_STRINGS;
String[] categories = (String[]) map.get(this);
if (categories == null) return CharOperation.NO_STRINGS;
return categories;
}
}
// in model/org/eclipse/jdt/internal/core/Member.java
public int getFlags() throws JavaModelException {
MemberElementInfo info = (MemberElementInfo) getElementInfo();
return info.getModifiers();
}
// in model/org/eclipse/jdt/internal/core/Member.java
public ISourceRange getJavadocRange() throws JavaModelException {
ISourceRange range= getSourceRange();
if (range == null) return null;
IBuffer buf= null;
if (isBinary()) {
buf = getClassFile().getBuffer();
} else {
ICompilationUnit compilationUnit = getCompilationUnit();
if (!compilationUnit.isConsistent()) {
return null;
}
buf = compilationUnit.getBuffer();
}
final int start= range.getOffset();
final int length= range.getLength();
if (length > 0 && buf.getChar(start) == '/') {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
try {
scanner.setSource(buf.getText(start, length).toCharArray());
int docOffset= -1;
int docEnd= -1;
int terminal= scanner.getNextToken();
loop: while (true) {
switch(terminal) {
case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
docOffset= scanner.getCurrentTokenStartPosition();
docEnd= scanner.getCurrentTokenEndPosition() + 1;
terminal= scanner.getNextToken();
break;
case ITerminalSymbols.TokenNameCOMMENT_LINE :
case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
terminal= scanner.getNextToken();
continue loop;
default :
break loop;
}
}
if (docOffset != -1) {
return new SourceRange(docOffset + start, docEnd - docOffset);
}
} catch (InvalidInputException ex) {
// try if there is inherited Javadoc
} catch (IndexOutOfBoundsException e) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/Member.java
public ISourceRange getNameRange() throws JavaModelException {
MemberElementInfo info= (MemberElementInfo)getElementInfo();
return new SourceRange(info.getNameSourceStart(), info.getNameSourceEnd() - info.getNameSourceStart() + 1);
}
// in model/org/eclipse/jdt/internal/core/Member.java
protected boolean isMainMethod(IMethod method) throws JavaModelException {
if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$
int flags= method.getFlags();
if (Flags.isStatic(flags) && Flags.isPublic(flags)) {
String[] paramTypes= method.getParameterTypes();
if (paramTypes.length == 1) {
String typeSignature= Signature.toString(paramTypes[0]);
return "String[]".equals(Signature.getSimpleName(typeSignature)); //$NON-NLS-1$
}
}
}
return false;
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
protected void compute() throws JavaModelException, CoreException {
if (this.focusType != null) {
HierarchyBuilder builder =
new IndexBasedHierarchyBuilder(
this,
this.scope);
builder.build(this.computeSubtypes);
} // else a RegionBasedTypeHierarchy should be used
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
protected static byte[] readUntil(InputStream input, byte separator) throws JavaModelException, IOException{
return readUntil(input, separator, 0);
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
protected static byte[] readUntil(InputStream input, byte separator, int offset) throws IOException, JavaModelException{
int length = 0;
byte[] bytes = new byte[SIZE];
byte b;
while((b = (byte)input.read()) != separator && b != -1) {
if(bytes.length == length) {
System.arraycopy(bytes, 0, bytes = new byte[length*2], 0, length);
}
bytes[length++] = b;
}
if(b == -1) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
System.arraycopy(bytes, 0, bytes = new byte[length + offset], offset, length);
return bytes;
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
public static ITypeHierarchy load(IType type, InputStream input, WorkingCopyOwner owner) throws JavaModelException {
try {
TypeHierarchy typeHierarchy = new TypeHierarchy();
typeHierarchy.initialize(1);
IType[] types = new IType[SIZE];
int typeCount = 0;
byte version = (byte)input.read();
if(version != VERSION) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
byte generalInfo = (byte)input.read();
if((generalInfo & COMPUTE_SUBTYPES) != 0) {
typeHierarchy.computeSubtypes = true;
}
byte b;
byte[] bytes;
// read project
bytes = readUntil(input, SEPARATOR1);
if(bytes.length > 0) {
typeHierarchy.project = (IJavaProject)JavaCore.create(new String(bytes));
typeHierarchy.scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {typeHierarchy.project});
} else {
typeHierarchy.project = null;
typeHierarchy.scope = SearchEngine.createWorkspaceScope();
}
// read missing type
{
bytes = readUntil(input, SEPARATOR1);
byte[] missing;
int j = 0;
int length = bytes.length;
for (int i = 0; i < length; i++) {
b = bytes[i];
if(b == SEPARATOR2) {
missing = new byte[i - j];
System.arraycopy(bytes, j, missing, 0, i - j);
typeHierarchy.missingTypes.add(new String(missing));
j = i + 1;
}
}
System.arraycopy(bytes, j, missing = new byte[length - j], 0, length - j);
typeHierarchy.missingTypes.add(new String(missing));
}
// read types
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR4, 1);
bytes[0] = b;
IType element = (IType)JavaCore.create(new String(bytes), owner);
if(types.length == typeCount) {
System.arraycopy(types, 0, types = new IType[typeCount * 2], 0, typeCount);
}
types[typeCount++] = element;
// read flags
bytes = readUntil(input, SEPARATOR4);
Integer flags = bytesToFlags(bytes);
if(flags != null) {
typeHierarchy.cacheFlags(element, flags.intValue());
}
// read info
byte info = (byte)input.read();
if((info & INTERFACE) != 0) {
typeHierarchy.addInterface(element);
}
if((info & COMPUTED_FOR) != 0) {
if(!element.equals(type)) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
typeHierarchy.focusType = element;
}
if((info & ROOT) != 0) {
typeHierarchy.addRootClass(element);
}
}
// read super class
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR3, 1);
bytes[0] = b;
int subClass = new Integer(new String(bytes)).intValue();
// read super type
bytes = readUntil(input, SEPARATOR1);
int superClass = new Integer(new String(bytes)).intValue();
typeHierarchy.cacheSuperclass(
types[subClass],
types[superClass]);
}
// read super interface
while((b = (byte)input.read()) != SEPARATOR1 && b != -1) {
bytes = readUntil(input, SEPARATOR3, 1);
bytes[0] = b;
int subClass = new Integer(new String(bytes)).intValue();
// read super interface
bytes = readUntil(input, SEPARATOR1);
IType[] superInterfaces = new IType[(bytes.length / 2) + 1];
int interfaceCount = 0;
int j = 0;
byte[] b2;
for (int i = 0; i < bytes.length; i++) {
if(bytes[i] == SEPARATOR2){
b2 = new byte[i - j];
System.arraycopy(bytes, j, b2, 0, i - j);
j = i + 1;
superInterfaces[interfaceCount++] = types[new Integer(new String(b2)).intValue()];
}
}
b2 = new byte[bytes.length - j];
System.arraycopy(bytes, j, b2, 0, bytes.length - j);
superInterfaces[interfaceCount++] = types[new Integer(new String(b2)).intValue()];
System.arraycopy(superInterfaces, 0, superInterfaces = new IType[interfaceCount], 0, interfaceCount);
typeHierarchy.cacheSuperInterfaces(
types[subClass],
superInterfaces);
}
if(b == -1) {
throw new JavaModelException(new JavaModelStatus(IStatus.ERROR));
}
return typeHierarchy;
} catch(IOException e){
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
public synchronized void refresh(IProgressMonitor monitor) throws JavaModelException {
try {
this.progressMonitor = monitor;
if (monitor != null) {
monitor.beginTask(
this.focusType != null ?
Messages.bind(Messages.hierarchy_creatingOnType, this.focusType.getFullyQualifiedName()) :
Messages.hierarchy_creating,
100);
}
long start = -1;
if (DEBUG) {
start = System.currentTimeMillis();
if (this.computeSubtypes) {
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 (this.focusType != null) {
System.out.println(" on type " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$
}
}
compute();
initializeRegions();
this.needsRefresh = false;
this.changeCollector = null;
if (DEBUG) {
if (this.computeSubtypes) {
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());
}
} catch (JavaModelException e) {
throw e;
} catch (CoreException e) {
throw new JavaModelException(e);
} finally {
if (monitor != null) {
monitor.done();
}
this.progressMonitor = null;
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
public void store(OutputStream output, IProgressMonitor monitor) throws JavaModelException {
try {
// compute types in hierarchy
Hashtable hashtable = new Hashtable();
Hashtable hashtable2 = new Hashtable();
int count = 0;
if(this.focusType != null) {
Integer index = new Integer(count++);
hashtable.put(this.focusType, index);
hashtable2.put(index, this.focusType);
}
Object[] types = this.classToSuperclass.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry entry = (Map.Entry) types[i];
Object t = entry.getKey();
if(hashtable.get(t) == null) {
Integer index = new Integer(count++);
hashtable.put(t, index);
hashtable2.put(index, t);
}
Object superClass = entry.getValue();
if(superClass != null && hashtable.get(superClass) == null) {
Integer index = new Integer(count++);
hashtable.put(superClass, index);
hashtable2.put(index, superClass);
}
}
types = this.typeToSuperInterfaces.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry entry = (Map.Entry) types[i];
Object t = entry.getKey();
if(hashtable.get(t) == null) {
Integer index = new Integer(count++);
hashtable.put(t, index);
hashtable2.put(index, t);
}
Object[] sp = (Object[]) entry.getValue();
if(sp != null) {
for (int j = 0; j < sp.length; j++) {
Object superInterface = sp[j];
if(sp[j] != null && hashtable.get(superInterface) == null) {
Integer index = new Integer(count++);
hashtable.put(superInterface, index);
hashtable2.put(index, superInterface);
}
}
}
}
// save version of the hierarchy format
output.write(VERSION);
// save general info
byte generalInfo = 0;
if(this.computeSubtypes) {
generalInfo |= COMPUTE_SUBTYPES;
}
output.write(generalInfo);
// save project
if(this.project != null) {
output.write(this.project.getHandleIdentifier().getBytes());
}
output.write(SEPARATOR1);
// save missing types
for (int i = 0; i < this.missingTypes.size(); i++) {
if(i != 0) {
output.write(SEPARATOR2);
}
output.write(((String)this.missingTypes.get(i)).getBytes());
}
output.write(SEPARATOR1);
// save types
for (int i = 0; i < count ; i++) {
IType t = (IType)hashtable2.get(new Integer(i));
// n bytes
output.write(t.getHandleIdentifier().getBytes());
output.write(SEPARATOR4);
output.write(flagsToBytes((Integer)this.typeFlags.get(t)));
output.write(SEPARATOR4);
byte info = CLASS;
if(this.focusType != null && this.focusType.equals(t)) {
info |= COMPUTED_FOR;
}
if(this.interfaces.contains(t)) {
info |= INTERFACE;
}
if(this.rootClasses.contains(t)) {
info |= ROOT;
}
output.write(info);
}
output.write(SEPARATOR1);
// save superclasses
types = this.classToSuperclass.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry entry = (Map.Entry) types[i];
IJavaElement key = (IJavaElement) entry.getKey();
IJavaElement value = (IJavaElement) entry.getValue();
output.write(((Integer)hashtable.get(key)).toString().getBytes());
output.write('>');
output.write(((Integer)hashtable.get(value)).toString().getBytes());
output.write(SEPARATOR1);
}
output.write(SEPARATOR1);
// save superinterfaces
types = this.typeToSuperInterfaces.entrySet().toArray();
for (int i = 0; i < types.length; i++) {
Map.Entry entry = (Map.Entry) types[i];
IJavaElement key = (IJavaElement) entry.getKey();
IJavaElement[] values = (IJavaElement[]) entry.getValue();
if(values.length > 0) {
output.write(((Integer)hashtable.get(key)).toString().getBytes());
output.write(SEPARATOR3);
for (int j = 0; j < values.length; j++) {
IJavaElement value = values[j];
if(j != 0) output.write(SEPARATOR2);
output.write(((Integer)hashtable.get(value)).toString().getBytes());
}
output.write(SEPARATOR1);
}
}
output.write(SEPARATOR1);
} catch(IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
protected void compute() throws JavaModelException, CoreException {
HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this);
builder.build(this.computeSubtypes);
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addAffectedChildren(IJavaElementDelta delta) throws JavaModelException {
IJavaElementDelta[] children = delta.getAffectedChildren();
for (int i = 0, length = children.length; i < length; i++) {
IJavaElementDelta child = children[i];
IJavaElement childElement = child.getElement();
switch (childElement.getElementType()) {
case IJavaElement.IMPORT_CONTAINER:
addChange((IImportContainer)childElement, child);
break;
case IJavaElement.IMPORT_DECLARATION:
addChange((IImportDeclaration)childElement, child);
break;
case IJavaElement.TYPE:
addChange((IType)childElement, child);
break;
case IJavaElement.INITIALIZER:
case IJavaElement.FIELD:
case IJavaElement.METHOD:
addChange((IMember)childElement, child);
break;
}
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
public void addChange(ICompilationUnit cu, IJavaElementDelta newDelta) throws JavaModelException {
int newKind = newDelta.getKind();
switch (newKind) {
case IJavaElementDelta.ADDED:
ArrayList allTypes = new ArrayList();
getAllTypesFromElement(cu, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType type = (IType)allTypes.get(i);
addTypeAddition(type, (SimpleDelta)this.changes.get(type));
}
break;
case IJavaElementDelta.REMOVED:
allTypes = new ArrayList();
getAllTypesFromHierarchy((JavaElement)cu, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType type = (IType)allTypes.get(i);
addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
}
break;
case IJavaElementDelta.CHANGED:
addAffectedChildren(newDelta);
break;
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addChange(IImportContainer importContainer, IJavaElementDelta newDelta) throws JavaModelException {
int newKind = newDelta.getKind();
if (newKind == IJavaElementDelta.CHANGED) {
addAffectedChildren(newDelta);
return;
}
SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importContainer);
if (existingDelta != null) {
switch (newKind) {
case IJavaElementDelta.ADDED:
if (existingDelta.getKind() == IJavaElementDelta.REMOVED) {
// REMOVED then ADDED
this.changes.remove(importContainer);
}
break;
case IJavaElementDelta.REMOVED:
if (existingDelta.getKind() == IJavaElementDelta.ADDED) {
// ADDED then REMOVED
this.changes.remove(importContainer);
}
break;
// CHANGED handled above
}
} else {
SimpleDelta delta = new SimpleDelta();
switch (newKind) {
case IJavaElementDelta.ADDED:
delta.added();
break;
case IJavaElementDelta.REMOVED:
delta.removed();
break;
}
this.changes.put(importContainer, delta);
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addChange(IMember member, IJavaElementDelta newDelta) throws JavaModelException {
int newKind = newDelta.getKind();
switch (newKind) {
case IJavaElementDelta.ADDED:
ArrayList allTypes = new ArrayList();
getAllTypesFromElement(member, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType innerType = (IType)allTypes.get(i);
addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
}
break;
case IJavaElementDelta.REMOVED:
allTypes = new ArrayList();
getAllTypesFromHierarchy((JavaElement)member, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType type = (IType)allTypes.get(i);
addTypeRemoval(type, (SimpleDelta)this.changes.get(type));
}
break;
case IJavaElementDelta.CHANGED:
addAffectedChildren(newDelta);
break;
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addChange(IType type, IJavaElementDelta newDelta) throws JavaModelException {
int newKind = newDelta.getKind();
SimpleDelta existingDelta = (SimpleDelta)this.changes.get(type);
switch (newKind) {
case IJavaElementDelta.ADDED:
addTypeAddition(type, existingDelta);
ArrayList allTypes = new ArrayList();
getAllTypesFromElement(type, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType innerType = (IType)allTypes.get(i);
addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType));
}
break;
case IJavaElementDelta.REMOVED:
addTypeRemoval(type, existingDelta);
allTypes = new ArrayList();
getAllTypesFromHierarchy((JavaElement)type, allTypes);
for (int i = 0, length = allTypes.size(); i < length; i++) {
IType innerType = (IType)allTypes.get(i);
addTypeRemoval(innerType, (SimpleDelta)this.changes.get(innerType));
}
break;
case IJavaElementDelta.CHANGED:
addTypeChange(type, newDelta.getFlags(), existingDelta);
addAffectedChildren(newDelta);
break;
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addTypeAddition(IType type, SimpleDelta existingDelta) throws JavaModelException {
if (existingDelta != null) {
switch (existingDelta.getKind()) {
case IJavaElementDelta.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);
}
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void addTypeChange(IType type, int newFlags, SimpleDelta existingDelta) throws JavaModelException {
if (existingDelta != null) {
switch (existingDelta.getKind()) {
case IJavaElementDelta.CHANGED:
// CHANGED then CHANGED
int existingFlags = existingDelta.getFlags();
boolean hasChange = false;
if ((existingFlags & IJavaElementDelta.F_SUPER_TYPES) != 0
&& hasSuperTypeChange(type)) {
existingDelta.superTypes();
hasChange = true;
}
if ((existingFlags & IJavaElementDelta.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 & IJavaElementDelta.F_SUPER_TYPES) != 0
&& this.hierarchy.includesTypeOrSupertype(type)) {
typeDelta = new SimpleDelta();
typeDelta.superTypes();
}
if ((newFlags & IJavaElementDelta.F_MODIFIERS) != 0
&& (this.hierarchy.hasSupertype(type.getElementName())
|| type.equals(this.hierarchy.focusType))) {
if (typeDelta == null) {
typeDelta = new SimpleDelta();
}
typeDelta.modifiers();
}
if (typeDelta != null) {
this.changes.put(type, typeDelta);
}
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private void getAllTypesFromElement(IJavaElement element, ArrayList allTypes) throws JavaModelException {
switch (element.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
IType[] types = ((ICompilationUnit)element).getTypes();
for (int i = 0, length = types.length; i < length; i++) {
IType type = types[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
break;
case IJavaElement.TYPE:
types = ((IType)element).getTypes();
for (int i = 0, length = types.length; i < length; i++) {
IType type = types[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
break;
case IJavaElement.INITIALIZER:
case IJavaElement.FIELD:
case IJavaElement.METHOD:
IJavaElement[] children = ((IMember)element).getChildren();
for (int i = 0, length = children.length; i < length; i++) {
IType type = (IType)children[i];
allTypes.add(type);
getAllTypesFromElement(type, allTypes);
}
break;
}
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private boolean hasSuperTypeChange(IType type) throws JavaModelException {
// check super class
IType 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
IType[] 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;
}
// in model/org/eclipse/jdt/internal/core/hierarchy/ChangeCollector.java
private boolean hasVisibilityChange(IType type) throws JavaModelException {
int existingFlags = this.hierarchy.getCachedFlags(type);
int newFlags = type.getFlags();
return existingFlags != newFlags;
}
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
private void buildForProject(JavaProject project, ArrayList potentialSubtypes, org.eclipse.jdt.core.ICompilationUnit[] workingCopies, HashSet localTypes, IProgressMonitor monitor) throws JavaModelException {
// resolve
int openablesLength = potentialSubtypes.size();
if (openablesLength > 0) {
// copy vectors into arrays
Openable[] openables = new Openable[openablesLength];
potentialSubtypes.toArray(openables);
// sort in the order of roots and in reverse alphabetical order for .class file
// since requesting top level types in the process of caching an enclosing type is
// not supported by the lookup environment
IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
int rootsLength = roots.length;
final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength);
for (int i = 0; i < openablesLength; i++) {
IJavaElement root = openables[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
int index;
for (index = 0; index < rootsLength; index++) {
if (roots[index].equals(root))
break;
}
indexes.put(openables[i], index);
}
Arrays.sort(openables, new Comparator() {
public int compare(Object a, Object b) {
int aIndex = indexes.get(a);
int bIndex = indexes.get(b);
if (aIndex != bIndex)
return aIndex - bIndex;
return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName());
}
});
IType focusType = getType();
boolean inProjectOfFocusType = focusType != null && focusType.getJavaProject().equals(project);
org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside = null;
if (inProjectOfFocusType) {
org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType.getCompilationUnit();
if (unitToLookInside != null) {
int wcLength = workingCopies == null ? 0 : workingCopies.length;
if (wcLength == 0) {
unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
} else {
unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength+1];
unitsToLookInside[0] = unitToLookInside;
System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
}
} else {
unitsToLookInside = workingCopies;
}
}
SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
this.nameLookup = searchableEnvironment.nameLookup;
Map options = project.getOptions(true);
// disable task tags to speed up parsing
options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
this.hierarchyResolver =
new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory());
if (focusType != null) {
Member declaringMember = ((Member)focusType).getOuterMostLocalContext();
if (declaringMember == null) {
// top level or member type
if (!inProjectOfFocusType) {
char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray();
String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names;
if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName)) == null) {
// focus type is not visible in this project: no need to go further
return;
}
}
} else {
// local or anonymous type
Openable openable;
if (declaringMember.isBinary()) {
openable = (Openable)declaringMember.getClassFile();
} else {
openable = (Openable)declaringMember.getCompilationUnit();
}
localTypes = new HashSet();
localTypes.add(openable.getPath().toString());
this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor);
return;
}
}
this.hierarchyResolver.resolve(openables, localTypes, monitor);
}
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
protected void executeOperation() throws JavaModelException {
checkCanceled();
try {
beginTask("", 1); //$NON-NLS-1$
if (JavaModelManager.CP_RESOLVE_VERBOSE)
verbose_set_container();
if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
verbose_set_container_invocation_trace();
JavaModelManager manager = JavaModelManager.getJavaModelManager();
if (manager.containerPutIfInitializingWithSameEntries(this.containerPath, this.affectedProjects, this.respectiveContainers))
return;
final int projectLength = this.affectedProjects.length;
final IJavaProject[] modifiedProjects;
System.arraycopy(this.affectedProjects, 0, modifiedProjects = new IJavaProject[projectLength], 0, projectLength);
// filter out unmodified project containers
int remaining = 0;
for (int i = 0; i < projectLength; i++){
if (isCanceled())
return;
JavaProject affectedProject = (JavaProject) this.affectedProjects[i];
IClasspathContainer newContainer = this.respectiveContainers[i];
if (newContainer == null) newContainer = JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS; // 30920 - prevent infinite loop
boolean found = false;
if (JavaProject.hasJavaNature(affectedProject.getProject())){
IClasspathEntry[] rawClasspath = affectedProject.getRawClasspath();
for (int j = 0, cpLength = rawClasspath.length; j <cpLength; j++) {
IClasspathEntry entry = rawClasspath[j];
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER && entry.getPath().equals(this.containerPath)){
found = true;
break;
}
}
}
if (!found) {
modifiedProjects[i] = null; // filter out this project - does not reference the container path, or isnt't yet Java project
manager.containerPut(affectedProject, this.containerPath, newContainer);
continue;
}
IClasspathContainer oldContainer = manager.containerGet(affectedProject, this.containerPath);
if (oldContainer == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
oldContainer = null;
}
if ((oldContainer != null && oldContainer.equals(this.respectiveContainers[i]))
|| (oldContainer == this.respectiveContainers[i])/*handle case where old and new containers are null (see bug 149043*/) {
modifiedProjects[i] = null; // filter out this project - container did not change
continue;
}
remaining++;
manager.containerPut(affectedProject, this.containerPath, newContainer);
}
if (remaining == 0) return;
// trigger model refresh
try {
for(int i = 0; i < projectLength; i++){
if (isCanceled())
return;
JavaProject affectedProject = (JavaProject)modifiedProjects[i];
if (affectedProject == null) continue; // was filtered out
if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
verbose_update_project(affectedProject);
// force resolved classpath to be recomputed
ClasspathChange classpathChange = affectedProject.getPerProjectInfo().resetResolvedClasspath();
// if needed, generate delta, update project ref, create markers, ...
classpathChanged(classpathChange, i==0/*refresh external linked folder only once*/);
if (this.canChangeResources) {
// touch project to force a build if needed
try {
affectedProject.getProject().touch(this.progressMonitor);
} catch (CoreException e) {
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970
if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName()))
throw e;
}
}
}
} catch(CoreException e) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE)
verbose_failure(e);
if (e instanceof JavaModelException) {
throw (JavaModelException)e;
} else {
throw new JavaModelException(e);
}
} finally {
for (int i = 0; i < projectLength; i++) {
if (this.respectiveContainers[i] == null) {
manager.containerPut(this.affectedProjects[i], this.containerPath, null); // reset init in progress marker
}
}
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
private void deletePackageFragment(IPackageFragment frag)
throws JavaModelException {
IResource res = ((JavaElement) frag).resource();
if (res != null) {
// collect the children to remove
IJavaElement[] childrenOfInterest = frag.getChildren();
if (childrenOfInterest.length > 0) {
IResource[] resources = new IResource[childrenOfInterest.length];
// remove the children
for (int i = 0; i < childrenOfInterest.length; i++) {
resources[i] = ((JavaElement) childrenOfInterest[i]).resource();
}
deleteResources(resources, this.force);
}
// Discard non-java resources
Object[] nonJavaResources = frag.getNonJavaResources();
int actualResourceCount = 0;
for (int i = 0, max = nonJavaResources.length; i < max; i++){
if (nonJavaResources[i] instanceof IResource) actualResourceCount++;
}
IResource[] actualNonJavaResources = new IResource[actualResourceCount];
for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
}
deleteResources(actualNonJavaResources, this.force);
// delete remaining files in this package (.class file in the case where Proj=src=bin)
IResource[] remainingFiles;
try {
remainingFiles = ((IContainer) res).members();
} catch (CoreException ce) {
throw new JavaModelException(ce);
}
boolean isEmpty = true;
for (int i = 0, length = remainingFiles.length; i < length; i++) {
IResource file = remainingFiles[i];
if (file instanceof IFile && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(file.getName())) {
deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
} else {
isEmpty = false;
}
}
if (isEmpty && !frag.isDefaultPackage()/*don't delete default package's folder: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38450*/) {
// delete recursively empty folders
IResource fragResource = ((JavaElement) frag).resource();
if (fragResource != null) {
deleteEmptyPackageFragment(frag, false, fragResource.getParent());
}
}
}
}
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
protected void processElement(IJavaElement element) throws JavaModelException {
switch (element.getElementType()) {
case IJavaElement.CLASS_FILE :
case IJavaElement.COMPILATION_UNIT :
deleteResource(element.getResource(), this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
break;
case IJavaElement.PACKAGE_FRAGMENT :
deletePackageFragment((IPackageFragment) element);
break;
default :
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
}
// ensure the element is closed
if (element instanceof IOpenable) {
((IOpenable)element).close();
}
}
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
if (element == null || !element.exists())
error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
int type = element.getElementType();
if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT || type > IJavaElement.COMPILATION_UNIT)
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment)
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
IResource resource = ((JavaElement) element).resource();
if (resource instanceof IFolder) {
if (resource.isLinked()) {
error(IJavaModelStatusConstants.INVALID_RESOURCE, element);
}
}
}
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
public static CompilationUnitDeclaration process(
CompilationUnit unitElement,
SourceElementParser parser,
WorkingCopyOwner workingCopyOwner,
HashMap problems,
boolean creatingAST,
int reconcileFlags,
IProgressMonitor monitor)
throws JavaModelException {
JavaProject project = (JavaProject) unitElement.getJavaProject();
CancelableNameEnvironment environment = null;
CancelableProblemFactory problemFactory = null;
CompilationUnitProblemFinder problemFinder = null;
CompilationUnitDeclaration unit = null;
try {
environment = new CancelableNameEnvironment(project, workingCopyOwner, monitor);
problemFactory = new CancelableProblemFactory(monitor);
CompilerOptions compilerOptions = getCompilerOptions(project.getOptions(true), creatingAST, ((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0));
boolean ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
compilerOptions.ignoreMethodBodies = ignoreMethodBodies;
problemFinder = new CompilationUnitProblemFinder(
environment,
getHandlingPolicy(),
compilerOptions,
getRequestor(),
problemFactory);
boolean analyzeAndGenerateCode = true;
if (ignoreMethodBodies) {
analyzeAndGenerateCode = false;
}
try {
if (parser != null) {
problemFinder.parser = parser;
unit = parser.parseCompilationUnit(unitElement, true/*full parse*/, monitor);
problemFinder.resolve(
unit,
unitElement,
true, // verify methods
analyzeAndGenerateCode, // analyze code
analyzeAndGenerateCode); // generate code
} else {
unit =
problemFinder.resolve(
unitElement,
true, // verify methods
analyzeAndGenerateCode, // analyze code
analyzeAndGenerateCode); // generate code
}
} catch (AbortCompilation e) {
problemFinder.handleInternalException(e, unit);
}
if (unit != null) {
CompilationResult unitResult = unit.compilationResult;
CategorizedProblem[] unitProblems = unitResult.getProblems();
int length = unitProblems == null ? 0 : unitProblems.length;
if (length > 0) {
CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
problems.put(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, categorizedProblems);
}
unitProblems = unitResult.getTasks();
length = unitProblems == null ? 0 : unitProblems.length;
if (length > 0) {
CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
problems.put(IJavaModelMarker.TASK_MARKER, categorizedProblems);
}
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} catch (OperationCanceledException e) {
// catch this exception so as to not enter the catch(RuntimeException e) below
throw e;
} catch(RuntimeException e) {
// avoid breaking other tools due to internal compiler failure (40334)
String lineDelimiter = unitElement.findRecommendedLineSeparator();
StringBuffer message = new StringBuffer("Exception occurred during problem detection:"); //$NON-NLS-1$
message.append(lineDelimiter);
message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$
message.append(lineDelimiter);
message.append(unitElement.getSource());
message.append(lineDelimiter);
message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$
Util.log(e, message.toString());
throw new JavaModelException(e, IJavaModelStatusConstants.COMPILER_FAILURE);
} finally {
if (environment != null)
environment.setMonitor(null); // don't hold a reference to this external object
if (problemFactory != null)
problemFactory.monitor = null; // don't hold a reference to this external object
// NB: unit.cleanUp() is done by caller
if (problemFinder != null && !creatingAST)
problemFinder.lookupEnvironment.reset();
}
return unit;
}
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
public static CompilationUnitDeclaration process(
CompilationUnit unitElement,
WorkingCopyOwner workingCopyOwner,
HashMap problems,
boolean creatingAST,
int reconcileFlags,
IProgressMonitor monitor)
throws JavaModelException {
return process(unitElement, null/*use default Parser*/, workingCopyOwner, problems, creatingAST, reconcileFlags, monitor);
}
// in model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
ASTNode node = super.generateElementAST(rewriter, cu);
if (node.getNodeType() != ASTNode.INITIALIZER)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
return node;
}
// in model/org/eclipse/jdt/internal/core/CreateMethodOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
ASTNode node = super.generateElementAST(rewriter, cu);
if (node.getNodeType() != ASTNode.METHOD_DECLARATION)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
return node;
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void error(int code, IJavaElement element) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(code, element));
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void executeOperation() throws JavaModelException {
processElements();
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected String getNewNameFor(IJavaElement element) throws JavaModelException {
String newName = null;
if (this.renamings != null)
newName = (String) this.renamings.get(element);
if (newName == null && element instanceof IMethod && ((IMethod) element).isConstructor())
newName = getDestinationParent(element).getElementName();
return newName;
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void processElements() throws JavaModelException {
try {
beginTask(getMainTaskName(), this.elementsToProcess.length);
IJavaModelStatus[] errors = new IJavaModelStatus[3];
int errorsCounter = 0;
for (int i = 0; i < this.elementsToProcess.length; i++) {
try {
verify(this.elementsToProcess[i]);
processElement(this.elementsToProcess[i]);
} catch (JavaModelException jme) {
if (errorsCounter == errors.length) {
// resize
System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter);
}
errors[errorsCounter++] = jme.getJavaModelStatus();
} finally {
worked(1);
}
}
if (errorsCounter == 1) {
throw new JavaModelException(errors[0]);
} else if (errorsCounter > 1) {
if (errorsCounter != errors.length) {
// resize
System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter]), 0, errorsCounter);
}
throw new JavaModelException(JavaModelStatus.newMultiStatus(errors));
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void verifyDestination(IJavaElement element, IJavaElement destination) throws JavaModelException {
if (destination == null || !destination.exists())
error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination);
int destType = destination.getElementType();
switch (element.getElementType()) {
case IJavaElement.PACKAGE_DECLARATION :
case IJavaElement.IMPORT_DECLARATION :
if (destType != IJavaElement.COMPILATION_UNIT)
error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
break;
case IJavaElement.TYPE :
if (destType != IJavaElement.COMPILATION_UNIT && destType != IJavaElement.TYPE)
error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
break;
case IJavaElement.METHOD :
case IJavaElement.FIELD :
case IJavaElement.INITIALIZER :
if (destType != IJavaElement.TYPE || destination instanceof BinaryType)
error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
break;
case IJavaElement.COMPILATION_UNIT :
if (destType != IJavaElement.PACKAGE_FRAGMENT)
error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
else {
CompilationUnit cu = (CompilationUnit)element;
if (isMove() && cu.isWorkingCopy() && !cu.isPrimary())
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
break;
case IJavaElement.PACKAGE_FRAGMENT :
IPackageFragment fragment = (IPackageFragment) element;
IJavaElement parent = fragment.getParent();
if (parent.isReadOnly())
error(IJavaModelStatusConstants.READ_ONLY, element);
else if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT)
error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
break;
default :
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void verifyRenaming(IJavaElement element) throws JavaModelException {
String newName = getNewNameFor(element);
boolean isValid = true;
IJavaProject project = element.getJavaProject();
String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT :
if (((IPackageFragment) element).isDefaultPackage()) {
// don't allow renaming of default package (see PR #1G47GUM)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, element));
}
isValid = JavaConventions.validatePackageName(newName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
break;
case IJavaElement.COMPILATION_UNIT :
isValid = JavaConventions.validateCompilationUnitName(newName,sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
break;
case IJavaElement.INITIALIZER :
isValid = false; //cannot rename initializers
break;
default :
isValid = JavaConventions.validateIdentifier(newName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
break;
}
if (!isValid) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, element, newName));
}
}
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
protected void verifySibling(IJavaElement element, IJavaElement destination) throws JavaModelException {
IJavaElement insertBeforeElement = (IJavaElement) this.insertBeforeElements.get(element);
if (insertBeforeElement != null) {
if (!insertBeforeElement.exists() || !insertBeforeElement.getParent().equals(destination)) {
error(IJavaModelStatusConstants.INVALID_SIBLING, insertBeforeElement);
}
}
}
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
protected void executeOperation() throws JavaModelException {
try {
beginTask(Messages.workingCopy_commit, 2);
CompilationUnit workingCopy = getCompilationUnit();
if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(workingCopy.getJavaProject().getElementName())) {
// case of a working copy without a resource
workingCopy.getBuffer().save(this.progressMonitor, this.force);
return;
}
ICompilationUnit primary = workingCopy.getPrimary();
boolean isPrimary = workingCopy.isPrimary();
JavaElementDeltaBuilder deltaBuilder = null;
PackageFragmentRoot root = (PackageFragmentRoot)workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
boolean isIncluded = !Util.isExcluded(workingCopy);
IFile resource = (IFile)workingCopy.getResource();
IJavaProject project = root.getJavaProject();
if (isPrimary || (root.validateOnClasspath().isOK() && isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName(workingCopy.getElementName(), project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true)))) {
// force opening so that the delta builder can get the old info
if (!isPrimary && !primary.isOpen()) {
primary.open(null);
}
// creates the delta builder (this remembers the content of the cu) if:
// - it is not excluded
// - and it is not a primary or it is a non-consistent primary
if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) {
deltaBuilder = new JavaElementDeltaBuilder(primary);
}
// save the cu
IBuffer primaryBuffer = primary.getBuffer();
if (!isPrimary) {
if (primaryBuffer == null) return;
char[] primaryContents = primaryBuffer.getCharacters();
boolean hasSaved = false;
try {
IBuffer workingCopyBuffer = workingCopy.getBuffer();
if (workingCopyBuffer == null) return;
primaryBuffer.setContents(workingCopyBuffer.getCharacters());
primaryBuffer.save(this.progressMonitor, this.force);
primary.makeConsistent(this);
hasSaved = true;
} finally {
if (!hasSaved){
// restore original buffer contents since something went wrong
primaryBuffer.setContents(primaryContents);
}
}
} else {
// for a primary working copy no need to set the content of the buffer again
primaryBuffer.save(this.progressMonitor, this.force);
primary.makeConsistent(this);
}
} else {
// working copy on cu outside classpath OR resource doesn't exist yet
String encoding = null;
try {
encoding = resource.getCharset();
}
catch (CoreException ce) {
// use no encoding
}
String contents = workingCopy.getSource();
if (contents == null) return;
try {
byte[] bytes = encoding == null
? contents.getBytes()
: contents.getBytes(encoding);
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
if (resource.exists()) {
resource.setContents(
stream,
this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
null);
} else {
resource.create(
stream,
this.force,
this.progressMonitor);
}
} catch (CoreException e) {
throw new JavaModelException(e);
} catch (UnsupportedEncodingException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
// make sure working copy is in sync
workingCopy.updateTimeStamp((CompilationUnit)primary);
workingCopy.makeConsistent(this);
worked(1);
// build the deltas
if (deltaBuilder != null) {
deltaBuilder.buildDeltas();
// add the deltas to the list of deltas created during this operation
if (deltaBuilder.delta != null) {
addDelta(deltaBuilder.delta);
}
}
worked(1);
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static byte[] getResourceContentsAsByteArray(IFile file) throws JavaModelException {
InputStream stream= null;
try {
stream = file.getContents(true);
} catch (CoreException e) {
throw new JavaModelException(e);
}
try {
return org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsByteArray(stream, -1);
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} finally {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static char[] getResourceContentsAsCharArray(IFile file) throws JavaModelException {
// Get encoding from file
String encoding;
try {
encoding = file.getCharset();
} catch(CoreException ce) {
// do not use any encoding
encoding = null;
}
return getResourceContentsAsCharArray(file, encoding);
}
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static char[] getResourceContentsAsCharArray(IFile file, String encoding) throws JavaModelException {
// Get file length
// workaround https://bugs.eclipse.org/bugs/show_bug.cgi?id=130736 by using java.io.File if possible
IPath location = file.getLocation();
long length;
if (location == null) {
// non local file
try {
URI locationURI = file.getLocationURI();
if (locationURI == null)
throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Messages.bind(Messages.file_notFound, file.getFullPath().toString())));
length = EFS.getStore(locationURI).fetchInfo().getLength();
} catch (CoreException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
}
} else {
// local file
length = location.toFile().length();
}
// Get resource contents
InputStream stream= null;
try {
stream = file.getContents(true);
} catch (CoreException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
}
try {
return org.eclipse.jdt.internal.compiler.util.Util.getInputStreamAsCharArray(stream, (int) length, encoding);
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
} finally {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
}
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static String getSourceAttachmentProperty(IPath path) throws JavaModelException {
Map rootPathToAttachments = JavaModelManager.getJavaModelManager().rootPathToAttachments;
String property = (String) rootPathToAttachments.get(path);
if (property == null) {
try {
property = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(getSourceAttachmentPropertyName(path));
if (property == null) {
rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
return null;
}
rootPathToAttachments.put(path, property);
return property;
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else if (property.equals(PackageFragmentRoot.NO_SOURCE_ATTACHMENT)) {
return null;
} else
return property;
}
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static IMethod findMethod(IType type, char[] selector, String[] paramTypeSignatures, boolean isConstructor) throws JavaModelException {
IMethod method = null;
int startingIndex = 0;
String[] args;
IType enclosingType = type.getDeclaringType();
// If the method is a constructor of a non-static inner type, add the enclosing type as an
// additional parameter to the constructor
if (enclosingType != null
&& isConstructor
&& !Flags.isStatic(type.getFlags())) {
args = new String[paramTypeSignatures.length+1];
startingIndex = 1;
args[0] = Signature.createTypeSignature(enclosingType.getFullyQualifiedName(), true);
} else {
args = new String[paramTypeSignatures.length];
}
int length = args.length;
for(int i = startingIndex; i< length ; i++){
args[i] = new String(paramTypeSignatures[i-startingIndex]);
}
method = type.getMethod(new String(selector), args);
IMethod[] methods = type.findMethods(method);
if (methods != null && methods.length > 0) {
method = methods[0];
}
return method;
}
// in model/org/eclipse/jdt/internal/core/util/DOMFinder.java
public ASTNode search() throws JavaModelException {
ISourceRange range = null;
if (this.element instanceof IMember && !(this.element instanceof IInitializer))
range = ((IMember) this.element).getNameRange();
else
range = this.element.getSourceRange();
this.rangeStart = range.getOffset();
this.rangeLength = range.getLength();
this.ast.accept(this);
return this.foundNode;
}
// in model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
//look for an existing package declaration
IJavaElement[] children = getCompilationUnit().getChildren();
for (int i = 0; i < children.length; i++) {
if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION && this.name.equals(children[i].getElementName())) {
//equivalent package declaration already exists
this.creationOccurred = false;
return null;
}
}
AST ast = this.cuAST.getAST();
PackageDeclaration pkgDeclaration = ast.newPackageDeclaration();
Name astName = ast.newName(this.name);
pkgDeclaration.setName(astName);
return pkgDeclaration;
}
// in model/org/eclipse/jdt/internal/core/PackageDeclaration.java
public ISourceRange getNameRange() throws JavaModelException {
AnnotatableInfo info = (AnnotatableInfo) getElementInfo();
return info.getNameRange();
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
protected void closing(Object info) throws JavaModelException {
super.closing(info);
SourceMethodElementInfo elementInfo = (SourceMethodElementInfo) info;
ITypeParameter[] typeParameters = elementInfo.typeParameters;
for (int i = 0, length = typeParameters.length; i < length; i++) {
((TypeParameter) typeParameters[i]).close();
}
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public IMemberValuePair getDefaultValue() throws JavaModelException {
SourceMethodElementInfo sourceMethodInfo = (SourceMethodElementInfo) getElementInfo();
if (sourceMethodInfo.isAnnotationMethod()) {
return ((SourceAnnotationMethodInfo) sourceMethodInfo).defaultValue;
}
return null;
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String[] getExceptionTypes() throws JavaModelException {
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
char[][] exs= info.getExceptionTypeNames();
return CompilationUnitStructureRequestor.convertTypeNamesToSigs(exs);
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String[] getParameterNames() throws JavaModelException {
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
char[][] names= info.getArgumentNames();
return CharOperation.toStrings(names);
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public ITypeParameter[] getTypeParameters() throws JavaModelException {
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
return info.typeParameters;
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public ILocalVariable[] getParameters() throws JavaModelException {
ILocalVariable[] arguments = ((SourceMethodElementInfo) getElementInfo()).arguments;
if (arguments == null)
return LocalVariable.NO_LOCAL_VARIABLES;
return arguments;
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String[] getTypeParameterSignatures() throws JavaModelException {
ITypeParameter[] typeParameters = getTypeParameters();
int length = typeParameters.length;
String[] typeParameterSignatures = new String[length];
for (int i = 0; i < length; i++) {
TypeParameter typeParameter = (TypeParameter) typeParameters[i];
TypeParameterElementInfo info = (TypeParameterElementInfo) typeParameter.getElementInfo();
char[][] bounds = info.bounds;
if (bounds == null) {
typeParameterSignatures[i] = Signature.createTypeParameterSignature(typeParameter.getElementName(), CharOperation.NO_STRINGS);
} else {
int boundsLength = bounds.length;
char[][] boundSignatures = new char[boundsLength][];
for (int j = 0; j < boundsLength; j++) {
boundSignatures[j] = Signature.createCharArrayTypeSignature(bounds[j], false);
}
typeParameterSignatures[i] = new String(Signature.createTypeParameterSignature(typeParameter.getElementName().toCharArray(), boundSignatures));
}
}
return typeParameterSignatures;
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String[] getRawParameterNames() throws JavaModelException {
return getParameterNames();
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String getReturnType() throws JavaModelException {
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
return Signature.createTypeSignature(info.getReturnTypeName(), false);
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public String getSignature() throws JavaModelException {
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
return Signature.createMethodSignature(this.parameterTypes, Signature.createTypeSignature(info.getReturnTypeName(), false));
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public boolean isConstructor() throws JavaModelException {
if (!getElementName().equals(this.parent.getElementName())) {
// faster than reaching the info
return false;
}
SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
return info.isConstructor();
}
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
public boolean isMainMethod() throws JavaModelException {
return this.isMainMethod(this);
}
// in model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
ASTNode node = super.generateElementAST(rewriter, cu);
if (node.getNodeType() != ASTNode.FIELD_DECLARATION)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
return node;
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
protected void closing(Object info) throws JavaModelException {
// Do any necessary cleanup
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] containers= new IJavaElement[] {container};
IJavaElement[] siblings= null;
if (sibling != null) {
siblings= new IJavaElement[] {sibling};
}
String[] renamings= null;
if (rename != null) {
renamings= new String[] {rename};
}
getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
IJavaElement[] elements = new IJavaElement[] {this};
getJavaModel().delete(elements, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
Openable openableParent = (Openable)getOpenableParent();
if (openableParent == null) return;
JavaElementInfo openableParentInfo = (JavaElementInfo) JavaModelManager.getJavaModelManager().getInfo(openableParent);
if (openableParentInfo == null) {
openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
}
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public IAnnotation[] getAnnotations() throws JavaModelException {
AnnotatableInfo info = (AnnotatableInfo) getElementInfo();
return info.annotations;
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public IResource getCorrespondingResource() throws JavaModelException {
if (!exists()) throw newNotPresentException();
return null;
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public String getSource() throws JavaModelException {
IOpenable openable = getOpenableParent();
IBuffer buffer = openable.getBuffer();
if (buffer == null) {
return null;
}
ISourceRange range = getSourceRange();
int offset = range.getOffset();
int length = range.getLength();
if (offset == -1 || length == 0 ) {
return null;
}
try {
return buffer.getText(offset, length);
} catch(RuntimeException e) {
return null;
}
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public ISourceRange getSourceRange() throws JavaModelException {
SourceRefElementInfo info = (SourceRefElementInfo) getElementInfo();
return info.getSourceRange();
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public IResource getUnderlyingResource() throws JavaModelException {
if (!exists()) throw newNotPresentException();
return getParent().getUnderlyingResource();
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public boolean hasChildren() throws JavaModelException {
return getChildren().length > 0;
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public boolean isStructureKnown() throws JavaModelException {
// structure is always known inside an openable
return true;
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (container == null) {
throw new IllegalArgumentException(Messages.operation_nullContainer);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] containers= new IJavaElement[] {container};
IJavaElement[] siblings= null;
if (sibling != null) {
siblings= new IJavaElement[] {sibling};
}
String[] renamings= null;
if (rename != null) {
renamings= new String[] {rename};
}
getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
if (newName == null) {
throw new IllegalArgumentException(Messages.element_nullName);
}
IJavaElement[] elements= new IJavaElement[] {this};
IJavaElement[] dests= new IJavaElement[] {getParent()};
String[] renamings= new String[] {newName};
getJavaModel().rename(elements, dests, renamings, force, monitor);
}
// in model/org/eclipse/jdt/internal/core/BecomeWorkingCopyOperation.java
protected void executeOperation() throws JavaModelException {
// open the working copy now to ensure contents are that of the current state of this element
CompilationUnit workingCopy = getWorkingCopy();
JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(workingCopy, true/*create if needed*/, true/*record usage*/, this.problemRequestor);
workingCopy.openWhenClosed(workingCopy.createElementInfo(), this.progressMonitor);
if (!workingCopy.isPrimary()) {
// report added java delta for a non-primary working copy
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.added(workingCopy);
addDelta(delta);
} else {
if (workingCopy.getResource().isAccessible()) {
// report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
addDelta(delta);
} else {
// report an ADDED delta
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
delta.added(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
addDelta(delta);
}
}
this.resultElements = new IJavaElement[] {workingCopy};
}
// in model/org/eclipse/jdt/internal/core/ImportContainer.java
public ISourceRange getSourceRange() throws JavaModelException {
IJavaElement[] imports= getChildren();
ISourceRange firstRange= ((ISourceReference)imports[0]).getSourceRange();
ISourceRange lastRange= ((ISourceReference)imports[imports.length - 1]).getSourceRange();
SourceRange range= new SourceRange(firstRange.getOffset(), lastRange.getOffset() + lastRange.getLength() - firstRange.getOffset());
return range;
}
// in model/org/eclipse/jdt/internal/core/ResolvedSourceType.java
public String getFullyQualifiedParameterizedName() throws JavaModelException {
return getFullyQualifiedParameterizedName(getFullyQualifiedName('.'), this.uniqueKey);
}
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
public void updateProjectReferencesIfNecessary() throws JavaModelException {
String[] oldRequired = this.oldResolvedClasspath == null ? CharOperation.NO_STRINGS : this.project.projectPrerequisites(this.oldResolvedClasspath);
IClasspathEntry[] newResolvedClasspath = this.project.getResolvedClasspath();
String[] newRequired = this.project.projectPrerequisites(newResolvedClasspath);
final IProject projectResource = this.project.getProject();
try {
IProject[] projectReferences = projectResource.getDescription().getDynamicReferences();
HashSet oldReferences = new HashSet(projectReferences.length);
for (int i = 0; i < projectReferences.length; i++){
String projectName = projectReferences[i].getName();
oldReferences.add(projectName);
}
HashSet newReferences = (HashSet)oldReferences.clone();
for (int i = 0; i < oldRequired.length; i++){
String projectName = oldRequired[i];
newReferences.remove(projectName);
}
for (int i = 0; i < newRequired.length; i++){
String projectName = newRequired[i];
newReferences.add(projectName);
}
Iterator iter;
int newSize = newReferences.size();
checkIdentity: {
if (oldReferences.size() == newSize){
iter = newReferences.iterator();
while (iter.hasNext()){
if (!oldReferences.contains(iter.next())){
break checkIdentity;
}
}
return;
}
}
String[] requiredProjectNames = new String[newSize];
int index = 0;
iter = newReferences.iterator();
while (iter.hasNext()){
requiredProjectNames[index++] = (String)iter.next();
}
Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent
final IProject[] requiredProjectArray = new IProject[newSize];
IWorkspaceRoot wksRoot = projectResource.getWorkspace().getRoot();
for (int i = 0; i < newSize; i++){
requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
}
// ensure that a scheduling rule is used so that the project description is not modified by another thread while we update it
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=214981
// also ensure that if no change (checkIdentify block returned above) we don't reach here
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241751
IWorkspace workspace = projectResource.getWorkspace();
ISchedulingRule rule = workspace.getRuleFactory().modifyRule(projectResource); // scheduling rule for modifying the project
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IProjectDescription description = projectResource.getDescription();
description.setDynamicReferences(requiredProjectArray);
projectResource.setDescription(description, IResource.AVOID_NATURE_CONFIG, null);
}
};
workspace.run(runnable, rule, IWorkspace.AVOID_UPDATE, null);
} catch(CoreException e){
if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName()))
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/ResolvedBinaryType.java
public String getFullyQualifiedParameterizedName() throws JavaModelException {
return getFullyQualifiedParameterizedName(getFullyQualifiedName('.'), this.uniqueKey);
}
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
private String getSourceFor(IJavaElement element) throws JavaModelException {
String source = (String) this.sources.get(element);
if (source == null && element instanceof IMember) {
source = ((IMember)element).getSource();
this.sources.put(element, source);
}
return source;
}
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) throws JavaModelException {
if ((isRename() || getNewNameFor(element) != null)
&& dest.getElementType() == IJavaElement.COMPILATION_UNIT) {
String typeName = dest.getElementName();
typeName = org.eclipse.jdt.internal.core.util.Util.getNameWithoutJavaLikeExtension(typeName);
return element.getElementName().equals(typeName) && element.getParent().equals(dest);
}
return false;
}
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
protected void processElement(IJavaElement element) throws JavaModelException {
JavaModelOperation op = getNestedOperation(element);
boolean createElementInCUOperation =op instanceof CreateElementInCUOperation;
if (op == null) {
return;
}
if (createElementInCUOperation) {
IJavaElement sibling = (IJavaElement) this.insertBeforeElements.get(element);
if (sibling != null) {
((CreateElementInCUOperation) op).setRelativePosition(sibling, CreateElementInCUOperation.INSERT_BEFORE);
} else
if (isRename()) {
IJavaElement anchor = resolveRenameAnchor(element);
if (anchor != null) {
((CreateElementInCUOperation) op).setRelativePosition(anchor, CreateElementInCUOperation.INSERT_AFTER); // insert after so that the anchor is found before when deleted below
}
}
String newName = getNewNameFor(element);
if (newName != null) {
((CreateElementInCUOperation) op).setAlteredName(newName);
}
}
executeNestedOperation(op, 1);
JavaElement destination = (JavaElement) getDestinationParent(element);
ICompilationUnit unit= destination.getCompilationUnit();
if (!unit.isWorkingCopy()) {
unit.close();
}
if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) {
JavaModelOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, this.force);
executeNestedOperation(deleteOp, 1);
}
}
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
private IJavaElement resolveRenameAnchor(IJavaElement element) throws JavaModelException {
IParent parent = (IParent) element.getParent();
IJavaElement[] children = parent.getChildren();
for (int i = 0; i < children.length; i++) {
IJavaElement child = children[i];
if (child.equals(element)) {
return child;
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
if (element == null || !element.exists())
error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
if (element.getElementType() < IJavaElement.TYPE)
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
if (element.isReadOnly())
error(IJavaModelStatusConstants.READ_ONLY, element);
IJavaElement dest = getDestinationParent(element);
verifyDestination(element, dest);
verifySibling(element, dest);
if (this.renamingsList != null) {
verifyRenaming(element);
}
}
// in model/org/eclipse/jdt/internal/core/RenameElementsOperation.java
protected void verify(IJavaElement element) throws JavaModelException {
if (element == null || !element.exists())
error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
if (element.isReadOnly())
error(IJavaModelStatusConstants.READ_ONLY, element);
if (!(element instanceof ISourceReference))
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
int elementType = element.getElementType();
if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER)
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
verifyRenaming(element);
}
// in model/org/eclipse/jdt/internal/core/CreateImportOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
// ensure no duplicate
Iterator imports = this.cuAST.imports().iterator();
boolean onDemand = this.importName.endsWith(".*"); //$NON-NLS-1$
String importActualName = this.importName;
if (onDemand) {
importActualName = this.importName.substring(0, this.importName.length() - 2);
}
while (imports.hasNext()) {
ImportDeclaration importDeclaration = (ImportDeclaration) imports.next();
if (importActualName.equals(importDeclaration.getName().getFullyQualifiedName())
&& (onDemand == importDeclaration.isOnDemand())
&& (Flags.isStatic(this.flags) == importDeclaration.isStatic())) {
this.creationOccurred = false;
return null;
}
}
AST ast = this.cuAST.getAST();
ImportDeclaration importDeclaration = ast.newImportDeclaration();
importDeclaration.setStatic(Flags.isStatic(this.flags));
// split import name into individual fragments, checking for on demand imports
char[][] charFragments = CharOperation.splitOn('.', importActualName.toCharArray(), 0, importActualName.length());
int length = charFragments.length;
String[] strFragments = new String[length];
for (int i = 0; i < length; i++) {
strFragments[i] = String.valueOf(charFragments[i]);
}
Name name = ast.newName(strFragments);
importDeclaration.setName(name);
if (onDemand) importDeclaration.setOnDemand(true);
return importDeclaration;
}
// in model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java
protected void executeOperation() throws JavaModelException {
try {
JavaElementDelta delta = null;
PackageFragmentRoot root = (PackageFragmentRoot) getParentElement();
beginTask(Messages.operation_createPackageFragmentProgress, this.pkgName.length);
IContainer parentFolder = (IContainer) root.resource();
String[] sideEffectPackageName = CharOperation.NO_STRINGS;
ArrayList results = new ArrayList(this.pkgName.length);
char[][] inclusionPatterns = root.fullInclusionPatternChars();
char[][] exclusionPatterns = root.fullExclusionPatternChars();
int i;
for (i = 0; i < this.pkgName.length; i++) {
String subFolderName = this.pkgName[i];
sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
IResource subFolder = parentFolder.findMember(subFolderName);
if (subFolder == null) {
createFolder(parentFolder, subFolderName, this.force);
parentFolder = parentFolder.getFolder(new Path(subFolderName));
IPackageFragment addedFrag = root.getPackageFragment(sideEffectPackageName);
if (!Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
if (delta == null) {
delta = newJavaElementDelta();
}
delta.added(addedFrag);
}
results.add(addedFrag);
} else {
parentFolder = (IContainer) subFolder;
}
worked(1);
}
if (results.size() > 0) {
this.resultElements = new IJavaElement[results.size()];
results.toArray(this.resultElements);
if (delta != null) {
addDelta(delta);
}
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/TypeParameter.java
public String[] getBounds() throws JavaModelException {
TypeParameterElementInfo info = (TypeParameterElementInfo) getElementInfo();
return CharOperation.toStrings(info.bounds);
}
// in model/org/eclipse/jdt/internal/core/TypeParameter.java
public String[] getBoundsSignatures() throws JavaModelException {
String[] boundSignatures = null;
TypeParameterElementInfo info = (TypeParameterElementInfo) this.getElementInfo();
// For a binary type or method, the signature is already available from the .class file.
// No need to construct again
if (this.parent instanceof BinaryMember) {
char[][] boundsSignatures = info.boundsSignatures;
if (boundsSignatures == null || boundsSignatures.length == 0) {
return CharOperation.NO_STRINGS;
}
return CharOperation.toStrings(info.boundsSignatures);
}
char[][] bounds = info.bounds;
if (bounds == null || bounds.length == 0) {
return CharOperation.NO_STRINGS;
}
int boundsLength = bounds.length;
boundSignatures = new String[boundsLength];
for (int i = 0; i < boundsLength; i++) {
boundSignatures[i] = new String(Signature.createCharArrayTypeSignature(bounds[i], false));
}
return boundSignatures;
}
// in model/org/eclipse/jdt/internal/core/TypeParameter.java
public ISourceRange getNameRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
ClassFile classFile = (ClassFile)getClassFile();
if (classFile != null) {
classFile.getBuffer();
return mapper.getNameRange(this);
}
}
TypeParameterElementInfo info = (TypeParameterElementInfo) getElementInfo();
return new SourceRange(info.nameStart, info.nameEnd - info.nameStart + 1);
}
// in model/org/eclipse/jdt/internal/core/TypeParameter.java
public ISourceRange getSourceRange() throws JavaModelException {
SourceMapper mapper= getSourceMapper();
if (mapper != null) {
// ensure the class file's buffer is open so that source ranges are computed
ClassFile classFile = (ClassFile)getClassFile();
if (classFile != null) {
classFile.getBuffer();
return mapper.getSourceRange(this);
}
}
return super.getSourceRange();
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public static void validateCycles(Map preferredClasspaths) throws JavaModelException {
//long start = System.currentTimeMillis();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject[] rscProjects = workspaceRoot.getProjects();
int length = rscProjects.length;
JavaProject[] projects = new JavaProject[length];
LinkedHashSet cycleParticipants = new LinkedHashSet();
HashSet traversed = new HashSet();
// compute cycle participants
ArrayList prereqChain = new ArrayList();
for (int i = 0; i < length; i++){
if (hasJavaNature(rscProjects[i])) {
JavaProject project = (projects[i] = (JavaProject)JavaCore.create(rscProjects[i]));
if (!traversed.contains(project.getPath())){
prereqChain.clear();
project.updateCycleParticipants(prereqChain, cycleParticipants, workspaceRoot, traversed, preferredClasspaths);
}
}
}
//System.out.println("updateAllCycleMarkers: " + (System.currentTimeMillis() - start) + " ms");
for (int i = 0; i < length; i++){
JavaProject project = projects[i];
if (project != null) {
if (cycleParticipants.contains(project.getPath())){
IMarker cycleMarker = project.getCycleMarker();
String circularCPOption = project.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true);
int circularCPSeverity = JavaCore.ERROR.equals(circularCPOption) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING;
if (cycleMarker != null) {
// update existing cycle marker if needed
try {
int existingSeverity = ((Integer)cycleMarker.getAttribute(IMarker.SEVERITY)).intValue();
if (existingSeverity != circularCPSeverity) {
cycleMarker.setAttribute(IMarker.SEVERITY, circularCPSeverity);
}
} catch (CoreException e) {
throw new JavaModelException(e);
}
} else {
IJavaProject[] projectsInCycle;
String cycleString = ""; //$NON-NLS-1$
if (cycleParticipants.isEmpty()) {
projectsInCycle = null;
} else {
projectsInCycle = new IJavaProject[cycleParticipants.size()];
Iterator it = cycleParticipants.iterator();
int k = 0;
while (it.hasNext()) {
//projectsInCycle[i++] = (IPath) it.next();
IResource member = workspaceRoot.findMember((IPath) it.next());
if (member != null && member.getType() == IResource.PROJECT){
projectsInCycle[k] = JavaCore.create((IProject)member);
if (projectsInCycle[k] != null) {
if (k != 0) cycleString += ", "; //$NON-NLS-1$
cycleString += projectsInCycle[k++].getElementName();
}
}
}
}
// create new marker
project.createClasspathProblemMarker(
new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project, cycleString));
}
} else {
project.flushClasspathProblemMarkers(true, false);
}
}
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
// cannot refresh cp markers on opening (emulate cp check on startup) since can create deadlocks (see bug 37274)
IClasspathEntry[] resolvedClasspath = getResolvedClasspath();
// compute the pkg fragment roots
info.setChildren(computePackageFragmentRoots(resolvedClasspath, false, null /*no reverse map*/));
return true;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void close() throws JavaModelException {
if (JavaProject.hasJavaNature(this.project)) {
// Get cached preferences if exist
JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(this.project, false);
if (perProjectInfo != null && perProjectInfo.preferences != null) {
IEclipsePreferences eclipseParentPreferences = (IEclipsePreferences) perProjectInfo.preferences.parent();
if (this.preferencesNodeListener != null) {
eclipseParentPreferences.removeNodeChangeListener(this.preferencesNodeListener);
this.preferencesNodeListener = null;
}
if (this.preferencesChangeListener != null) {
perProjectInfo.preferences.removePreferenceChangeListener(this.preferencesChangeListener);
this.preferencesChangeListener = null;
}
}
}
super.close();
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
private void computeExpandedClasspath(
ClasspathEntry referringEntry,
HashSet rootIDs,
ObjectVector accumulatedEntries) throws JavaModelException {
String projectRootId = rootID();
if (rootIDs.contains(projectRootId)){
return; // break cycles if any
}
rootIDs.add(projectRootId);
IClasspathEntry[] resolvedClasspath = getResolvedClasspath();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
boolean isInitialProject = referringEntry == null;
for (int i = 0, length = resolvedClasspath.length; i < length; i++){
ClasspathEntry entry = (ClasspathEntry) resolvedClasspath[i];
if (isInitialProject || entry.isExported()){
String rootID = entry.rootID();
if (rootIDs.contains(rootID)) {
continue;
}
// combine restrictions along the project chain
ClasspathEntry combinedEntry = entry.combineWith(referringEntry);
accumulatedEntries.add(combinedEntry);
// recurse in project to get all its indirect exports (only consider exported entries from there on)
if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
IResource member = workspaceRoot.findMember(entry.getPath());
if (member != null && member.getType() == IResource.PROJECT){ // double check if bound to project (23977)
IProject projRsc = (IProject) member;
if (JavaProject.hasJavaNature(projRsc)) {
JavaProject javaProject = (JavaProject) JavaCore.create(projRsc);
javaProject.computeExpandedClasspath(
combinedEntry,
rootIDs,
accumulatedEntries);
}
}
} else {
rootIDs.add(rootID);
}
}
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void computePackageFragmentRoots(
IClasspathEntry resolvedEntry,
ObjectVector accumulatedRoots,
HashSet rootIDs,
IClasspathEntry referringEntry,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
String rootID = ((ClasspathEntry)resolvedEntry).rootID();
if (rootIDs.contains(rootID)) return;
IPath projectPath = this.project.getFullPath();
IPath entryPath = resolvedEntry.getPath();
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IPackageFragmentRoot root = null;
switch(resolvedEntry.getEntryKind()){
// source folder
case IClasspathEntry.CPE_SOURCE :
if (projectPath.isPrefixOf(entryPath)){
Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
if (target == null) return;
if (target instanceof IFolder || target instanceof IProject){
root = getPackageFragmentRoot((IResource)target);
}
}
break;
// internal/external JAR or folder
case IClasspathEntry.CPE_LIBRARY :
if (referringEntry != null && !resolvedEntry.isExported())
return;
Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
if (target == null)
return;
if (target instanceof IResource){
// internal target
root = getPackageFragmentRoot((IResource) target, entryPath);
} else if (target instanceof File) {
// external target
if (JavaModel.isFile(target)) {
root = new JarPackageFragmentRoot(entryPath, this);
} else if (((File) target).isDirectory()) {
root = new ExternalPackageFragmentRoot(entryPath, this);
}
}
break;
// recurse into required project
case IClasspathEntry.CPE_PROJECT :
if (!retrieveExportedRoots) return;
if (referringEntry != null && !resolvedEntry.isExported()) return;
IResource member = workspaceRoot.findMember(entryPath);
if (member != null && member.getType() == IResource.PROJECT){// double check if bound to project (23977)
IProject requiredProjectRsc = (IProject) member;
if (JavaProject.hasJavaNature(requiredProjectRsc)){ // special builder binary output
rootIDs.add(rootID);
JavaProject requiredProject = (JavaProject)JavaCore.create(requiredProjectRsc);
requiredProject.computePackageFragmentRoots(
requiredProject.getResolvedClasspath(),
accumulatedRoots,
rootIDs,
rootToResolvedEntries == null ? resolvedEntry : ((ClasspathEntry)resolvedEntry).combineWith((ClasspathEntry) referringEntry), // only combine if need to build the reverse map
retrieveExportedRoots,
rootToResolvedEntries);
}
break;
}
}
if (root != null) {
accumulatedRoots.add(root);
rootIDs.add(rootID);
if (rootToResolvedEntries != null) rootToResolvedEntries.put(root, ((ClasspathEntry)resolvedEntry).combineWith((ClasspathEntry) referringEntry));
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot[] computePackageFragmentRoots(
IClasspathEntry[] resolvedClasspath,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
ObjectVector accumulatedRoots = new ObjectVector();
computePackageFragmentRoots(
resolvedClasspath,
accumulatedRoots,
new HashSet(5), // rootIDs
null, // inside original project
retrieveExportedRoots,
rootToResolvedEntries);
IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots.size()];
accumulatedRoots.copyInto(rootArray);
return rootArray;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void computePackageFragmentRoots(
IClasspathEntry[] resolvedClasspath,
ObjectVector accumulatedRoots,
HashSet rootIDs,
IClasspathEntry referringEntry,
boolean retrieveExportedRoots,
Map rootToResolvedEntries) throws JavaModelException {
if (referringEntry == null){
rootIDs.add(rootID());
}
for (int i = 0, length = resolvedClasspath.length; i < length; i++){
computePackageFragmentRoots(
resolvedClasspath[i],
accumulatedRoots,
rootIDs,
referringEntry,
retrieveExportedRoots,
rootToResolvedEntries);
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected String encodeClasspath(IClasspathEntry[] classpath, IClasspathEntry[] referencedEntries, IPath outputLocation, boolean indent, Map unknownElements) throws JavaModelException {
try {
ByteArrayOutputStream s = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
XMLWriter xmlWriter = new XMLWriter(writer, this, true/*print XML version*/);
xmlWriter.startTag(ClasspathEntry.TAG_CLASSPATH, indent);
for (int i = 0; i < classpath.length; ++i) {
((ClasspathEntry)classpath[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true, unknownElements, false);
}
if (outputLocation != null) {
outputLocation = outputLocation.removeFirstSegments(1);
outputLocation = outputLocation.makeRelative();
HashMap parameters = new HashMap();
parameters.put(ClasspathEntry.TAG_KIND, ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));
parameters.put(ClasspathEntry.TAG_PATH, String.valueOf(outputLocation));
xmlWriter.printTag(ClasspathEntry.TAG_CLASSPATHENTRY, parameters, indent, true, true);
}
if (referencedEntries != null) {
for (int i = 0; i < referencedEntries.length; ++i) {
((ClasspathEntry) referencedEntries[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true, unknownElements, true);
}
}
xmlWriter.endTag(ClasspathEntry.TAG_CLASSPATH, indent, true/*insert new line*/);
writer.flush();
writer.close();
return s.toString("UTF8");//$NON-NLS-1$
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IJavaElement findElement(IPath path) throws JavaModelException {
return findElement(path, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IJavaElement findElement(IPath path, WorkingCopyOwner owner) throws JavaModelException {
if (path == null || path.isAbsolute()) {
throw new JavaModelException(
new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, path));
}
try {
String extension = path.getFileExtension();
if (extension == null) {
String packageName = path.toString().replace(IPath.SEPARATOR, '.');
return findPackageFragment(packageName);
} else if (Util.isJavaLikeFileName(path.lastSegment())
|| extension.equalsIgnoreCase(EXTENSION_class)) {
IPath packagePath = path.removeLastSegments(1);
String packageName = packagePath.toString().replace(IPath.SEPARATOR, '.');
String typeName = path.lastSegment();
typeName = typeName.substring(0, typeName.length() - extension.length() - 1);
String qualifiedName = null;
if (packageName.length() > 0) {
qualifiedName = packageName + "." + typeName; //$NON-NLS-1$
} else {
qualifiedName = typeName;
}
// lookup type
NameLookup lookup = newNameLookup(owner);
NameLookup.Answer answer = lookup.findType(
qualifiedName,
false,
NameLookup.ACCEPT_ALL,
true/* consider secondary types */,
false/* do NOT wait for indexes */,
false/*don't check restrictions*/,
null);
if (answer != null) {
return answer.type.getParent();
} else {
return null;
}
} else {
// unsupported extension
return null;
}
} catch (JavaModelException e) {
if (e.getStatus().getCode()
== IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) {
return null;
} else {
throw e;
}
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IJavaElement findPackageFragment(String packageName)
throws JavaModelException {
NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
IPackageFragment[] pkgFragments = lookup.findPackageFragments(packageName, false);
if (pkgFragments == null) {
return null;
} else {
// try to return one that is a child of this project
for (int i = 0, length = pkgFragments.length; i < length; i++) {
IPackageFragment pkgFragment = pkgFragments[i];
if (equals(pkgFragment.getParent().getParent())) {
return pkgFragment;
}
}
// default to the first one
return pkgFragments[0];
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IJavaElement findElement(String bindingKey, WorkingCopyOwner owner) throws JavaModelException {
JavaElementFinder elementFinder = new JavaElementFinder(bindingKey, this, owner);
elementFinder.parse();
if (elementFinder.exception != null)
throw elementFinder.exception;
return elementFinder.element;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragment findPackageFragment(IPath path)
throws JavaModelException {
return findPackageFragment0(JavaProject.canonicalizedPath(path));
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
private IPackageFragment findPackageFragment0(IPath path)
throws JavaModelException {
NameLookup lookup = newNameLookup((WorkingCopyOwner)null/*no need to look at working copies for pkgs*/);
return lookup.findPackageFragment(path);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot findPackageFragmentRoot(IPath path)
throws JavaModelException {
return findPackageFragmentRoot0(JavaProject.canonicalizedPath(path));
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot findPackageFragmentRoot0(IPath path)
throws JavaModelException {
IPackageFragmentRoot[] allRoots = this.getAllPackageFragmentRoots();
if (!path.isAbsolute()) {
throw new IllegalArgumentException(Messages.path_mustBeAbsolute);
}
for (int i= 0; i < allRoots.length; i++) {
IPackageFragmentRoot classpathRoot= allRoots[i];
if (classpathRoot.getPath().equals(path)) {
return classpathRoot;
}
}
return null;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String fullyQualifiedName) throws JavaModelException {
return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String fullyQualifiedName, IProgressMonitor progressMonitor) throws JavaModelException {
return findType(fullyQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
IType findType(String fullyQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup.Answer answer = lookup.findType(
fullyQualifiedName,
false,
NameLookup.ACCEPT_ALL,
considerSecondaryTypes,
true, /* wait for indexes (only if consider secondary types)*/
false/*don't check restrictions*/,
progressMonitor);
if (answer == null) {
// try to find enclosing type
int lastDot = fullyQualifiedName.lastIndexOf('.');
if (lastDot == -1) return null;
IType type = findType(fullyQualifiedName.substring(0, lastDot), lookup, considerSecondaryTypes, progressMonitor);
if (type != null) {
type = type.getType(fullyQualifiedName.substring(lastDot+1));
if (!type.exists()) {
return null;
}
}
return type;
}
return answer.type;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String packageName, String typeQualifiedName) throws JavaModelException {
return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String packageName, String typeQualifiedName, IProgressMonitor progressMonitor) throws JavaModelException {
return findType(packageName, typeQualifiedName, DefaultWorkingCopyOwner.PRIMARY, progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
IType findType(String packageName, String typeQualifiedName, NameLookup lookup, boolean considerSecondaryTypes, IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup.Answer answer = lookup.findType(
typeQualifiedName,
packageName,
false,
NameLookup.ACCEPT_ALL,
considerSecondaryTypes,
true, // wait for indexes (in case we need to consider secondary types)
false/*don't check restrictions*/,
progressMonitor);
return answer == null ? null : answer.type;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(
packageName,
typeQualifiedName,
lookup,
false, // do not consider secondary types
null);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String packageName, String typeQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(
packageName,
typeQualifiedName,
lookup,
true, // consider secondary types
progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(fullyQualifiedName, lookup, false, null);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IType findType(String fullyQualifiedName, WorkingCopyOwner owner, IProgressMonitor progressMonitor) throws JavaModelException {
NameLookup lookup = newNameLookup(owner);
return findType(fullyQualifiedName, lookup, true, progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot[] getAllPackageFragmentRoots()
throws JavaModelException {
return getAllPackageFragmentRoots(null /*no reverse map*/);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot[] getAllPackageFragmentRoots(Map rootToResolvedEntries) throws JavaModelException {
return computePackageFragmentRoots(getResolvedClasspath(), true/*retrieveExportedRoots*/, rootToResolvedEntries);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry getClasspathEntryFor(IPath path) throws JavaModelException {
getResolvedClasspath(); // force resolution
PerProjectInfo perProjectInfo = getPerProjectInfo();
if (perProjectInfo == null)
return null;
Map rootPathToResolvedEntries = perProjectInfo.rootPathToResolvedEntries;
if (rootPathToResolvedEntries == null)
return null;
IClasspathEntry classpathEntry = (IClasspathEntry) rootPathToResolvedEntries.get(path);
if (classpathEntry == null) {
path = getProject().getWorkspace().getRoot().getLocation().append(path);
classpathEntry = (IClasspathEntry) rootPathToResolvedEntries.get(path);
}
return classpathEntry;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] getExpandedClasspath() throws JavaModelException {
ObjectVector accumulatedEntries = new ObjectVector();
computeExpandedClasspath(null, new HashSet(5), accumulatedEntries);
IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()];
accumulatedEntries.copyInto(expandedPath);
return expandedPath;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected JavaProjectElementInfo getJavaProjectElementInfo()
throws JavaModelException {
return (JavaProjectElementInfo) getElementInfo();
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public Object[] getNonJavaResources() throws JavaModelException {
return ((JavaProjectElementInfo) getElementInfo()).getNonJavaResources(this);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPath getOutputLocation() throws JavaModelException {
// Do not create marker while getting output location
JavaModelManager.PerProjectInfo perProjectInfo = getPerProjectInfo();
IPath outputLocation = perProjectInfo.outputLocation;
if (outputLocation != null) return outputLocation;
// force to read classpath - will position output location as well
getRawClasspath();
outputLocation = perProjectInfo.outputLocation;
if (outputLocation == null) {
return defaultOutputLocation();
}
return outputLocation;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragmentRoot[] getPackageFragmentRoots()
throws JavaModelException {
Object[] children;
int length;
IPackageFragmentRoot[] roots;
System.arraycopy(
children = getChildren(),
0,
roots = new IPackageFragmentRoot[length = children.length],
0,
length);
return roots;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IPackageFragment[] getPackageFragments() throws JavaModelException {
IPackageFragmentRoot[] roots = getPackageFragmentRoots();
return getPackageFragmentsInRoots(roots);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public JavaModelManager.PerProjectInfo getPerProjectInfo() throws JavaModelException {
return JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(this.project);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ProjectCache getProjectCache() throws JavaModelException {
return ((JavaProjectElementInfo) getElementInfo()).getProjectCache(this);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] getRawClasspath() throws JavaModelException {
JavaModelManager.PerProjectInfo perProjectInfo = getPerProjectInfo();
IClasspathEntry[] classpath = perProjectInfo.rawClasspath;
if (classpath != null) return classpath;
classpath = perProjectInfo.readAndCacheClasspath(this)[0];
if (classpath == JavaProject.INVALID_CLASSPATH)
return defaultClasspath();
return classpath;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] getReferencedClasspathEntries() throws JavaModelException {
return getPerProjectInfo().referencedEntries;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public String[] getRequiredProjectNames() throws JavaModelException {
return projectPrerequisites(getResolvedClasspath());
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] getResolvedClasspath() throws JavaModelException {
PerProjectInfo perProjectInfo = getPerProjectInfo();
IClasspathEntry[] resolvedClasspath = perProjectInfo.getResolvedClasspath();
if (resolvedClasspath == null) {
resolveClasspath(perProjectInfo, false/*don't use previous session values*/, true/*add classpath change*/);
resolvedClasspath = perProjectInfo.getResolvedClasspath();
if (resolvedClasspath == null) {
// another thread reset the resolved classpath, use a temporary PerProjectInfo
PerProjectInfo temporaryInfo = newTemporaryInfo();
resolveClasspath(temporaryInfo, false/*don't use previous session values*/, true/*add classpath change*/);
resolvedClasspath = temporaryInfo.getResolvedClasspath();
}
}
return resolvedClasspath;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) throws JavaModelException {
if (JavaModelManager.getJavaModelManager().isClasspathBeingResolved(this)) {
if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
verbose_reentering_classpath_resolution();
return RESOLUTION_IN_PROGRESS;
}
PerProjectInfo perProjectInfo = getPerProjectInfo();
// use synchronized block to ensure consistency
IClasspathEntry[] resolvedClasspath;
IJavaModelStatus unresolvedEntryStatus;
synchronized (perProjectInfo) {
resolvedClasspath = perProjectInfo.getResolvedClasspath();
unresolvedEntryStatus = perProjectInfo.unresolvedEntryStatus;
}
if (resolvedClasspath == null
|| (unresolvedEntryStatus != null && !unresolvedEntryStatus.isOK())) { // force resolution to ensure initializers are run again
resolveClasspath(perProjectInfo, false/*don't use previous session values*/, true/*add classpath change*/);
synchronized (perProjectInfo) {
resolvedClasspath = perProjectInfo.getResolvedClasspath();
unresolvedEntryStatus = perProjectInfo.unresolvedEntryStatus;
}
if (resolvedClasspath == null) {
// another thread reset the resolved classpath, use a temporary PerProjectInfo
PerProjectInfo temporaryInfo = newTemporaryInfo();
resolveClasspath(temporaryInfo, false/*don't use previous session values*/, true/*add classpath change*/);
resolvedClasspath = temporaryInfo.getResolvedClasspath();
unresolvedEntryStatus = temporaryInfo.unresolvedEntryStatus;
}
}
if (!ignoreUnresolvedEntry && unresolvedEntryStatus != null && !unresolvedEntryStatus.isOK())
throw new JavaModelException(unresolvedEntryStatus);
return resolvedClasspath;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IResource getUnderlyingResource() throws JavaModelException {
if (!exists()) throw newNotPresentException();
return this.project;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public NameLookup newNameLookup(ICompilationUnit[] workingCopies) throws JavaModelException {
return getJavaProjectElementInfo().newNameLookup(this, workingCopies);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
ICompilationUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/);
return newNameLookup(workingCopies);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public SearchableEnvironment newSearchableNameEnvironment(ICompilationUnit[] workingCopies) throws JavaModelException {
return new SearchableEnvironment(this, workingCopies);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaModelException {
return new SearchableEnvironment(this, owner);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ITypeHierarchy newTypeHierarchy(
IRegion region,
IProgressMonitor monitor)
throws JavaModelException {
return newTypeHierarchy(region, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ITypeHierarchy newTypeHierarchy(
IRegion region,
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
if (region == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
}
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op =
new CreateTypeHierarchyOperation(region, workingCopies, null, true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ITypeHierarchy newTypeHierarchy(
IType type,
IRegion region,
IProgressMonitor monitor)
throws JavaModelException {
return newTypeHierarchy(type, region, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ITypeHierarchy newTypeHierarchy(
IType type,
IRegion region,
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
if (type == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullFocusType);
}
if (region == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
}
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op =
new CreateTypeHierarchyOperation(region, workingCopies, type, true/*compute subtypes*/);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public String[] projectPrerequisites(IClasspathEntry[] resolvedClasspath)
throws JavaModelException {
ArrayList prerequisites = new ArrayList();
for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
IClasspathEntry entry = resolvedClasspath[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
prerequisites.add(entry.getPath().lastSegment());
}
}
int size = prerequisites.size();
if (size == 0) {
return NO_PREREQUISITES;
} else {
String[] result = new String[size];
prerequisites.toArray(result);
return result;
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[] resolveClasspath(IClasspathEntry[] rawClasspath) throws JavaModelException {
return resolveClasspath(rawClasspath, false/*don't use previous session*/, true/*resolve chained libraries*/).resolvedClasspath;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ResolvedClasspath resolveClasspath(IClasspathEntry[] rawClasspath, boolean usePreviousSession, boolean resolveChainedLibraries) throws JavaModelException {
return resolveClasspath(rawClasspath, null, usePreviousSession, resolveChainedLibraries);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public ResolvedClasspath resolveClasspath(IClasspathEntry[] rawClasspath, IClasspathEntry[] referencedEntries, boolean usePreviousSession, boolean resolveChainedLibraries) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager();
ResolvedClasspath result = new ResolvedClasspath();
Map knownDrives = new HashMap();
Map referencedEntriesMap = new HashMap();
List rawLibrariesPath = new ArrayList();
LinkedHashSet resolvedEntries = new LinkedHashSet();
if(resolveChainedLibraries) {
for (int index = 0; index < rawClasspath.length; index++) {
IClasspathEntry currentEntry = rawClasspath[index];
if (currentEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
rawLibrariesPath.add(ClasspathEntry.resolveDotDot(getProject().getLocation(), currentEntry.getPath()));
}
}
if (referencedEntries != null) {
// The Set is required to keep the order intact while the referencedEntriesMap (Map)
// is used to map the referenced entries with path
LinkedHashSet referencedEntriesSet = new LinkedHashSet();
for (int index = 0; index < referencedEntries.length; index++) {
IPath path = referencedEntries[index].getPath();
if (!rawLibrariesPath.contains(path) && referencedEntriesMap.get(path) == null) {
referencedEntriesMap.put(path, referencedEntries[index]);
referencedEntriesSet.add(referencedEntries[index]);
}
}
if (referencedEntriesSet.size() > 0) {
result.referencedEntries = new IClasspathEntry[referencedEntriesSet.size()];
referencedEntriesSet.toArray(result.referencedEntries);
}
}
}
int length = rawClasspath.length;
for (int i = 0; i < length; i++) {
IClasspathEntry rawEntry = rawClasspath[i];
IClasspathEntry resolvedEntry = rawEntry;
switch (rawEntry.getEntryKind()){
case IClasspathEntry.CPE_VARIABLE :
try {
resolvedEntry = manager.resolveVariableEntry(rawEntry, usePreviousSession);
} catch (ClasspathEntry.AssertionFailedException e) {
// Catch the assertion failure and set status instead
// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage());
break;
}
if (resolvedEntry == null) {
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, this, rawEntry.getPath());
} else {
// If the entry is already present in the rawReversetMap, it means the entry and the chained libraries
// have already been processed. So, skip it.
if (resolveChainedLibraries && resolvedEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY
&& result.rawReverseMap.get(resolvedEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = ((ClasspathEntry) resolvedEntry).resolvedChainedLibraries();
for (int j = 0, length2 = extraEntries.length; j < length2; j++) {
if (!rawLibrariesPath.contains(extraEntries[j].getPath())) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037
// referenced entries for variable entries could also be persisted with extra attributes, so addAsChainedEntry = true
addToResult(rawEntry, extraEntries[j], result, resolvedEntries, externalFoldersManager, referencedEntriesMap, true, knownDrives);
}
}
}
addToResult(rawEntry, resolvedEntry, result, resolvedEntries, externalFoldersManager, referencedEntriesMap, false, knownDrives);
}
break;
case IClasspathEntry.CPE_CONTAINER :
IClasspathContainer container = usePreviousSession ? manager.getPreviousSessionContainer(rawEntry.getPath(), this) : JavaCore.getClasspathContainer(rawEntry.getPath(), this);
if (container == null){
result.unresolvedEntryStatus = new JavaModelStatus(IJavaModelStatusConstants.CP_CONTAINER_PATH_UNBOUND, this, rawEntry.getPath());
break;
}
IClasspathEntry[] containerEntries = container.getClasspathEntries();
if (containerEntries == null) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
JavaModelManager.getJavaModelManager().verbose_missbehaving_container_null_entries(this, rawEntry.getPath());
}
break;
}
// container was bound
for (int j = 0, containerLength = containerEntries.length; j < containerLength; j++){
ClasspathEntry cEntry = (ClasspathEntry) containerEntries[j];
if (cEntry == null) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
JavaModelManager.getJavaModelManager().verbose_missbehaving_container(this, rawEntry.getPath(), containerEntries);
}
break;
}
// if container is exported or restricted, then its nested entries must in turn be exported (21749) and/or propagate restrictions
cEntry = cEntry.combineWith((ClasspathEntry) rawEntry);
if (cEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
// resolve ".." in library path
cEntry = cEntry.resolvedDotDot(getProject().getLocation());
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=313965
// Do not resolve if the system attribute is set to false
if (resolveChainedLibraries
&& JavaModelManager.getJavaModelManager().resolveReferencedLibrariesForContainers
&& result.rawReverseMap.get(cEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = cEntry.resolvedChainedLibraries();
for (int k = 0, length2 = extraEntries.length; k < length2; k++) {
if (!rawLibrariesPath.contains(extraEntries[k].getPath())) {
addToResult(rawEntry, extraEntries[k], result, resolvedEntries, externalFoldersManager, referencedEntriesMap, false, knownDrives);
}
}
}
}
addToResult(rawEntry, cEntry, result, resolvedEntries, externalFoldersManager, referencedEntriesMap, false, knownDrives);
}
break;
case IClasspathEntry.CPE_LIBRARY:
// resolve ".." in library path
resolvedEntry = ((ClasspathEntry) rawEntry).resolvedDotDot(getProject().getLocation());
if (resolveChainedLibraries && result.rawReverseMap.get(resolvedEntry.getPath()) == null) {
// resolve Class-Path: in manifest
ClasspathEntry[] extraEntries = ((ClasspathEntry) resolvedEntry).resolvedChainedLibraries();
for (int k = 0, length2 = extraEntries.length; k < length2; k++) {
if (!rawLibrariesPath.contains(extraEntries[k].getPath())) {
addToResult(rawEntry, extraEntries[k], result, resolvedEntries, externalFoldersManager, referencedEntriesMap, true, knownDrives);
}
}
}
addToResult(rawEntry, resolvedEntry, result, resolvedEntries, externalFoldersManager, referencedEntriesMap, false, knownDrives);
break;
default :
addToResult(rawEntry, resolvedEntry, result, resolvedEntries, externalFoldersManager, referencedEntriesMap, false, knownDrives);
break;
}
}
result.resolvedClasspath = new IClasspathEntry[resolvedEntries.size()];
resolvedEntries.toArray(result.resolvedClasspath);
return result;
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void resolveClasspath(PerProjectInfo perProjectInfo, boolean usePreviousSession, boolean addClasspathChange) throws JavaModelException {
if (CP_RESOLUTION_BP_LISTENERS != null)
breakpoint(1, this);
JavaModelManager manager = JavaModelManager.getJavaModelManager();
boolean isClasspathBeingResolved = manager.isClasspathBeingResolved(this);
try {
if (!isClasspathBeingResolved) {
manager.setClasspathBeingResolved(this, true);
}
// get raw info inside a synchronized block to ensure that it is consistent
IClasspathEntry[][] classpath = new IClasspathEntry[2][];
int timeStamp;
synchronized (perProjectInfo) {
classpath[0] = perProjectInfo.rawClasspath;
classpath[1] = perProjectInfo.referencedEntries;
// Checking null only for rawClasspath enough
if (classpath[0] == null)
classpath = perProjectInfo.readAndCacheClasspath(this);
timeStamp = perProjectInfo.rawTimeStamp;
}
ResolvedClasspath result = resolveClasspath(classpath[0], classpath[1], usePreviousSession, true/*resolve chained libraries*/);
if (CP_RESOLUTION_BP_LISTENERS != null)
breakpoint(2, this);
// store resolved info along with the raw info to ensure consistency
perProjectInfo.setResolvedClasspath(result.resolvedClasspath, result.referencedEntries, result.rawReverseMap, result.rootPathToResolvedEntries, usePreviousSession ? PerProjectInfo.NEED_RESOLUTION : result.unresolvedEntryStatus, timeStamp, addClasspathChange);
} finally {
if (!isClasspathBeingResolved) {
manager.setClasspathBeingResolved(this, false);
}
if (CP_RESOLUTION_BP_LISTENERS != null)
breakpoint(3, this);
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public boolean writeFileEntries(IClasspathEntry[] newClasspath, IClasspathEntry[] referencedEntries, IPath newOutputLocation) throws JavaModelException {
if (!this.project.isAccessible()) return false;
Map unknownElements = new HashMap();
IClasspathEntry[][] fileEntries = readFileEntries(unknownElements);
if (fileEntries[0] != JavaProject.INVALID_CLASSPATH &&
areClasspathsEqual(newClasspath, newOutputLocation, fileEntries[0])
&& (referencedEntries == null || areClasspathsEqual(referencedEntries, fileEntries[1])) ) {
// no need to save it, it is the same
return false;
}
// actual file saving
try {
setSharedProperty(JavaProject.CLASSPATH_FILENAME, encodeClasspath(newClasspath, referencedEntries, newOutputLocation, true, unknownElements));
return true;
} catch (CoreException e) {
throw new JavaModelException(e);
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public boolean writeFileEntries(IClasspathEntry[] newClasspath, IPath newOutputLocation) throws JavaModelException {
return writeFileEntries(newClasspath, ClasspathEntry.NO_ENTRIES, newOutputLocation);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaModelException {
if (path == null) {
throw new IllegalArgumentException(Messages.path_nullPath);
}
if (path.equals(getOutputLocation())) {
return;
}
setRawClasspath(getRawClasspath(), path, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setRawClasspath(
IClasspathEntry[] entries,
boolean canModifyResources,
IProgressMonitor monitor)
throws JavaModelException {
setRawClasspath(
entries,
getOutputLocation()/*don't change output*/,
canModifyResources,
monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setRawClasspath(
IClasspathEntry[] newRawClasspath,
IPath newOutputLocation,
boolean canModifyResources,
IProgressMonitor monitor)
throws JavaModelException {
setRawClasspath(newRawClasspath, null, newOutputLocation, canModifyResources, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setRawClasspath(
IClasspathEntry[] entries,
IPath outputLocation,
IProgressMonitor monitor)
throws JavaModelException {
setRawClasspath(
entries,
outputLocation,
true/*can change resource (as per API contract)*/,
monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setRawClasspath(IClasspathEntry[] entries, IClasspathEntry[] referencedEntries, IPath outputLocation,
IProgressMonitor monitor) throws JavaModelException {
setRawClasspath(entries, referencedEntries, outputLocation, true, monitor);
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected void setRawClasspath(IClasspathEntry[] newRawClasspath, IClasspathEntry[] referencedEntries, IPath newOutputLocation,
boolean canModifyResources, IProgressMonitor monitor) throws JavaModelException {
try {
if (newRawClasspath == null) //are we already with the default classpath
newRawClasspath = defaultClasspath();
SetClasspathOperation op =
new SetClasspathOperation(
this,
newRawClasspath,
referencedEntries,
newOutputLocation,
canModifyResources);
op.runOperation(monitor);
} catch (JavaModelException e) {
JavaModelManager.getJavaModelManager().getDeltaProcessor().flush();
throw e;
}
}
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setRawClasspath(
IClasspathEntry[] entries,
IProgressMonitor monitor)
throws JavaModelException {
setRawClasspath(
entries,
getOutputLocation()/*don't change output*/,
true/*can change resource (as per API contract)*/,
monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceField.java
public Object getConstant() throws JavaModelException {
Object constant = null;
SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
final char[] constantSourceChars = info.initializationSource;
if (constantSourceChars == null) {
return null;
}
String constantSource = new String(constantSourceChars);
String signature = info.getTypeSignature();
try {
if (signature.equals(Signature.SIG_INT)) {
constant = new Integer(constantSource);
} else if (signature.equals(Signature.SIG_SHORT)) {
constant = new Short(constantSource);
} else if (signature.equals(Signature.SIG_BYTE)) {
constant = new Byte(constantSource);
} else if (signature.equals(Signature.SIG_BOOLEAN)) {
constant = Boolean.valueOf(constantSource);
} else if (signature.equals(Signature.SIG_CHAR)) {
if (constantSourceChars.length != 3) {
return null;
}
constant = new Character(constantSourceChars[1]);
} else if (signature.equals(Signature.SIG_DOUBLE)) {
constant = new Double(constantSource);
} else if (signature.equals(Signature.SIG_FLOAT)) {
constant = new Float(constantSource);
} else if (signature.equals(Signature.SIG_LONG)) {
if (constantSource.endsWith("L") || constantSource.endsWith("l")) { //$NON-NLS-1$ //$NON-NLS-2$
int index = constantSource.lastIndexOf("L");//$NON-NLS-1$
if (index != -1) {
constant = new Long(constantSource.substring(0, index));
} else {
constant = new Long(constantSource.substring(0, constantSource.lastIndexOf("l")));//$NON-NLS-1$
}
} else {
constant = new Long(constantSource);
}
} else if (signature.equals("QString;")) {//$NON-NLS-1$
constant = constantSource;
} else if (signature.equals("Qjava.lang.String;")) {//$NON-NLS-1$
constant = constantSource;
}
} catch (NumberFormatException e) {
// not a parsable constant
return null;
}
return constant;
}
// in model/org/eclipse/jdt/internal/core/SourceField.java
public String getTypeSignature() throws JavaModelException {
SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
return info.getTypeSignature();
}
// in model/org/eclipse/jdt/internal/core/SourceField.java
public boolean isEnumConstant() throws JavaModelException {
return Flags.isEnum(getFlags());
}
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
protected void executeOperation() throws JavaModelException {
try {
this.runnable.run(this.progressMonitor);
} catch (CoreException ce) {
if (ce instanceof JavaModelException) {
throw (JavaModelException)ce;
} else {
if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
Throwable e= ce.getStatus().getException();
if (e instanceof JavaModelException) {
throw (JavaModelException) e;
}
}
throw new JavaModelException(ce);
}
}
}
// in model/org/eclipse/jdt/internal/core/ChangeClasspathOperation.java
protected void classpathChanged(ClasspathChange change, boolean refreshExternalFolder) throws JavaModelException {
// reset the project's caches early since some clients rely on the project's caches being up-to-date when run inside an IWorkspaceRunnable
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=212769#c5 )
JavaProject project = change.project;
project.resetCaches();
if (this.canChangeResources) {
// workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=177922
if (isTopLevelOperation() && !ResourcesPlugin.getWorkspace().isTreeLocked()) {
new ClasspathValidation(project).validate();
}
// delta, indexing and classpath markers are going to be created by the delta processor
// while handling the resource change (either .classpath change, or project touched)
// however ensure project references are updated
// since some clients rely on the project references when run inside an IWorkspaceRunnable
new ProjectReferenceChange(project, change.oldResolvedClasspath).updateProjectReferencesIfNecessary();
// and ensure that external folders are updated as well
new ExternalFolderChange(project, change.oldResolvedClasspath).updateExternalFoldersIfNecessary(refreshExternalFolder, null);
} else {
DeltaProcessingState state = JavaModelManager.getDeltaState();
JavaElementDelta delta = new JavaElementDelta(getJavaModel());
int result = change.generateDelta(delta, true/*add classpath change*/);
if ((result & ClasspathChange.HAS_DELTA) != 0) {
// create delta
addDelta(delta);
// need to recompute root infos
state.rootsAreStale = true;
// ensure indexes are updated
change.requestIndexing();
// ensure classpath is validated on next build
state.addClasspathValidation(project);
}
if ((result & ClasspathChange.HAS_PROJECT_CHANGE) != 0) {
// ensure project references are updated on next build
state.addProjectReferenceChange(project, change.oldResolvedClasspath);
}
if ((result & ClasspathChange.HAS_LIBRARY_CHANGE) != 0) {
// ensure external folders are updated on next build
state.addExternalFolderChange(project, change.oldResolvedClasspath);
}
}
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
protected void closing(Object info) throws JavaModelException {
super.closing(info);
SourceTypeElementInfo elementInfo = (SourceTypeElementInfo) info;
ITypeParameter[] typeParameters = elementInfo.typeParameters;
for (int i = 0, length = typeParameters.length; i < length; i++) {
((TypeParameter) typeParameters[i]).close();
}
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,ICompletionRequestor requestor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,ICompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), owner);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor, IProgressMonitor monitor) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaModelException {
codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, owner, null);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public void codeComplete(
char[] snippet,
int insertion,
int position,
char[][] localVariableTypeNames,
char[][] localVariableNames,
int[] localVariableModifiers,
boolean isStatic,
CompletionRequestor requestor,
WorkingCopyOwner owner,
IProgressMonitor monitor) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
}
JavaProject project = (JavaProject) getJavaProject();
SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);
CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
String source = getCompilationUnit().getSource();
if (source != null && insertion > -1 && insertion < source.length()) {
char[] prefix = CharOperation.concat(source.substring(0, insertion).toCharArray(), new char[]{'{'});
char[] suffix = CharOperation.concat(new char[]{'}'}, source.substring(insertion).toCharArray());
char[] fakeSource = CharOperation.concat(prefix, snippet, suffix);
BasicCompilationUnit cu =
new BasicCompilationUnit(
fakeSource,
null,
getElementName(),
getParent());
engine.complete(cu, prefix.length + position, prefix.length, null/*extended context isn't computed*/);
} else {
engine.complete(this, snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic);
}
if (NameLookup.VERBOSE) {
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
CreateFieldOperation op = new CreateFieldOperation(this, contents, force);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return (IField) op.getResultElements()[0];
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
CreateInitializerOperation op = new CreateInitializerOperation(this, contents);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return (IInitializer) op.getResultElements()[0];
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
CreateMethodOperation op = new CreateMethodOperation(this, contents, force);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return (IMethod) op.getResultElements()[0];
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
CreateTypeOperation op = new CreateTypeOperation(this, contents, force);
if (sibling != null) {
op.createBefore(sibling);
}
op.runOperation(monitor);
return (IType) op.getResultElements()[0];
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IAnnotation[] getAnnotations() throws JavaModelException {
AnnotatableInfo info = (AnnotatableInfo) getElementInfo();
return info.annotations;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IJavaElement[] getChildrenForCategory(String category) throws JavaModelException {
IJavaElement[] children = getChildren();
int length = children.length;
if (length == 0) return NO_ELEMENTS;
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
HashMap categories = info.getCategories();
if (categories == null) return NO_ELEMENTS;
IJavaElement[] result = new IJavaElement[length];
int index = 0;
for (int i = 0; i < length; i++) {
IJavaElement child = children[i];
String[] elementCategories = (String[]) categories.get(child);
if (elementCategories != null)
for (int j = 0, length2 = elementCategories.length; j < length2; j++) {
if (elementCategories[j].equals(category))
result[index++] = child;
}
}
if (index == 0) return NO_ELEMENTS;
if (index < length)
System.arraycopy(result, 0, result = new IJavaElement[index], 0, index);
return result;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IField[] getFields() throws JavaModelException {
ArrayList list = getChildrenOfType(FIELD);
IField[] array= new IField[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String getFullyQualifiedParameterizedName() throws JavaModelException {
return getFullyQualifiedName('.', true/*show parameters*/);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IInitializer[] getInitializers() throws JavaModelException {
ArrayList list = getChildrenOfType(INITIALIZER);
IInitializer[] array= new IInitializer[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IMethod[] getMethods() throws JavaModelException {
ArrayList list = getChildrenOfType(METHOD);
IMethod[] array= new IMethod[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String getSuperclassName() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
char[] superclassName= info.getSuperclassName();
if (superclassName == null) {
return null;
}
return new String(superclassName);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String getSuperclassTypeSignature() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
char[] superclassName= info.getSuperclassName();
if (superclassName == null) {
return null;
}
return new String(Signature.createTypeSignature(superclassName, false));
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String[] getSuperInterfaceNames() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
char[][] names= info.getInterfaceNames();
return CharOperation.toStrings(names);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String[] getSuperInterfaceTypeSignatures() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
char[][] names= info.getInterfaceNames();
if (names == null) {
return CharOperation.NO_STRINGS;
}
String[] strings= new String[names.length];
for (int i= 0; i < names.length; i++) {
strings[i]= new String(Signature.createTypeSignature(names[i], false));
}
return strings;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeParameter[] getTypeParameters() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
return info.typeParameters;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public String[] getTypeParameterSignatures() throws JavaModelException {
ITypeParameter[] typeParameters = getTypeParameters();
int length = typeParameters.length;
String[] typeParameterSignatures = new String[length];
for (int i = 0; i < length; i++) {
TypeParameter typeParameter = (TypeParameter) typeParameters[i];
TypeParameterElementInfo info = (TypeParameterElementInfo) typeParameter.getElementInfo();
char[][] bounds = info.bounds;
if (bounds == null) {
typeParameterSignatures[i] = Signature.createTypeParameterSignature(typeParameter.getElementName(), CharOperation.NO_STRINGS);
} else {
int boundsLength = bounds.length;
char[][] boundSignatures = new char[boundsLength][];
for (int j = 0; j < boundsLength; j++) {
boundSignatures[j] = Signature.createCharArrayTypeSignature(bounds[j], false);
}
typeParameterSignatures[i] = new String(Signature.createTypeParameterSignature(typeParameter.getElementName().toCharArray(), boundSignatures));
}
}
return typeParameterSignatures;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public IType[] getTypes() throws JavaModelException {
ArrayList list= getChildrenOfType(TYPE);
IType[] array= new IType[list.size()];
list.toArray(array);
return array;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public boolean isClass() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public boolean isEnum() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.ENUM_DECL;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public boolean isInterface() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
switch (TypeDeclaration.kind(info.getModifiers())) {
case TypeDeclaration.INTERFACE_DECL:
case TypeDeclaration.ANNOTATION_TYPE_DECL: // annotation is interface too
return true;
}
return false;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public boolean isAnnotation() throws JavaModelException {
SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.ANNOTATION_TYPE_DECL;
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaModelException {
return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
// TODO monitor should be passed to TypeHierarchy.load(...)
return TypeHierarchy.load(this, input, owner);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newSupertypeHierarchy(
ICompilationUnit[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newSupertypeHierarchy(
IWorkingCopy[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] copies;
if (workingCopies == null) {
copies = null;
} else {
int length = workingCopies.length;
System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length);
}
return newSupertypeHierarchy(copies, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newSupertypeHierarchy(
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException {
return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(IJavaProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
if (project == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullProject);
}
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
ICompilationUnit[] projectWCs = null;
if (workingCopies != null) {
int length = workingCopies.length;
projectWCs = new ICompilationUnit[length];
int index = 0;
for (int i = 0; i < length; i++) {
ICompilationUnit wc = workingCopies[i];
if (project.equals(wc.getJavaProject())) {
projectWCs[index++] = wc;
}
}
if (index != length) {
System.arraycopy(projectWCs, 0, projectWCs = new ICompilationUnit[index], 0, index);
}
}
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(
this,
projectWCs,
project,
true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=228845, The new type hierarchy should consider changes in primary
// working copy.
return newTypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(
ICompilationUnit[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(
IWorkingCopy[] workingCopies,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] copies;
if (workingCopies == null) {
copies = null;
} else {
int length = workingCopies.length;
System.arraycopy(workingCopies, 0, copies = new ICompilationUnit[length], 0, length);
}
return newTypeHierarchy(copies, monitor);
}
// in model/org/eclipse/jdt/internal/core/SourceType.java
public ITypeHierarchy newTypeHierarchy(
WorkingCopyOwner owner,
IProgressMonitor monitor)
throws JavaModelException {
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
if (this.createdNode == null) {
this.source = removeIndentAndNewLines(this.source, cu);
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(this.source.toCharArray());
parser.setProject(getCompilationUnit().getJavaProject());
parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
ASTNode node = parser.createAST(this.progressMonitor);
String createdNodeSource;
if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
createdNodeSource = generateSyntaxIncorrectAST();
if (this.createdNode == null)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
} else {
TypeDeclaration typeDeclaration = (TypeDeclaration) node;
if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
createdNodeSource = generateSyntaxIncorrectAST();
if (this.createdNode == null)
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
} else {
List bodyDeclarations = typeDeclaration.bodyDeclarations();
if (bodyDeclarations.size() == 0) {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
}
this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
createdNodeSource = this.source;
}
}
if (this.alteredName != null) {
SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
SimpleName oldName = rename(this.createdNode, newName);
int nameStart = oldName.getStartPosition();
int nameEnd = nameStart + oldName.getLength();
StringBuffer newSource = new StringBuffer();
if (this.source.equals(createdNodeSource)) {
newSource.append(createdNodeSource.substring(0, nameStart));
newSource.append(this.alteredName);
newSource.append(createdNodeSource.substring(nameEnd));
} else {
// syntactically incorrect source
int createdNodeStart = this.createdNode.getStartPosition();
int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
newSource.append(this.alteredName);
newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));
}
this.source = newSource.toString();
}
}
if (rewriter == null) return this.createdNode;
// return a string place holder (instead of the created node) so has to not lose comments and formatting
return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}
// in model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
private String removeIndentAndNewLines(String code, ICompilationUnit cu) throws JavaModelException {
IJavaProject project = cu.getJavaProject();
Map options = project.getOptions(true/*inherit JavaCore options*/);
int tabWidth = IndentManipulation.getTabWidth(options);
int indentWidth = IndentManipulation.getIndentWidth(options);
int indent = IndentManipulation.measureIndentUnits(code, tabWidth, indentWidth);
int firstNonWhiteSpace = -1;
int length = code.length();
while (firstNonWhiteSpace < length-1)
if (!ScannerHelper.isWhitespace(code.charAt(++firstNonWhiteSpace)))
break;
int lastNonWhiteSpace = length;
while (lastNonWhiteSpace > 0)
if (!ScannerHelper.isWhitespace(code.charAt(--lastNonWhiteSpace)))
break;
String lineDelimiter = cu.findRecommendedLineSeparator();
return IndentManipulation.changeIndent(code.substring(firstNonWhiteSpace, lastNonWhiteSpace+1), indent, tabWidth, indentWidth, "", lineDelimiter); //$NON-NLS-1$
}
// in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
protected void executeOperation() throws JavaModelException {
checkCanceled();
try {
beginTask("", 1); //$NON-NLS-1$
if (JavaModelManager.CP_RESOLVE_VERBOSE)
verbose_set_variables();
JavaModelManager manager = JavaModelManager.getJavaModelManager();
if (manager.variablePutIfInitializingWithSameValue(this.variableNames, this.variablePaths))
return;
int varLength = this.variableNames.length;
// gather classpath information for updating
final HashMap affectedProjectClasspaths = new HashMap(5);
IJavaModel model = getJavaModel();
// filter out unmodified variables
int discardCount = 0;
for (int i = 0; i < varLength; i++){
String variableName = this.variableNames[i];
IPath oldPath = manager.variableGet(variableName); // if reentering will provide previous session value
if (oldPath == JavaModelManager.VARIABLE_INITIALIZATION_IN_PROGRESS) {
oldPath = null; //33695 - cannot filter out restored variable, must update affected project to reset cached CP
}
if (oldPath != null && oldPath.equals(this.variablePaths[i])){
this.variableNames[i] = null;
discardCount++;
}
}
if (discardCount > 0){
if (discardCount == varLength) return;
int changedLength = varLength - discardCount;
String[] changedVariableNames = new String[changedLength];
IPath[] changedVariablePaths = new IPath[changedLength];
for (int i = 0, index = 0; i < varLength; i++){
if (this.variableNames[i] != null){
changedVariableNames[index] = this.variableNames[i];
changedVariablePaths[index] = this.variablePaths[i];
index++;
}
}
this.variableNames = changedVariableNames;
this.variablePaths = changedVariablePaths;
varLength = changedLength;
}
if (isCanceled())
return;
IJavaProject[] projects = model.getJavaProjects();
nextProject : for (int i = 0, projectLength = projects.length; i < projectLength; i++){
JavaProject project = (JavaProject) projects[i];
// check to see if any of the modified variables is present on the classpath
IClasspathEntry[] classpath = project.getRawClasspath();
for (int j = 0, cpLength = classpath.length; j < cpLength; j++){
IClasspathEntry entry = classpath[j];
for (int k = 0; k < varLength; k++){
String variableName = this.variableNames[k];
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
if (variableName.equals(entry.getPath().segment(0))){
affectedProjectClasspaths.put(project, project.getResolvedClasspath());
continue nextProject;
}
IPath sourcePath, sourceRootPath;
if (((sourcePath = entry.getSourceAttachmentPath()) != null && variableName.equals(sourcePath.segment(0)))
|| ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && variableName.equals(sourceRootPath.segment(0)))) {
affectedProjectClasspaths.put(project, project.getResolvedClasspath());
continue nextProject;
}
}
}
}
}
// update variables
for (int i = 0; i < varLength; i++){
manager.variablePut(this.variableNames[i], this.variablePaths[i]);
if (this.updatePreferences)
manager.variablePreferencesPut(this.variableNames[i], this.variablePaths[i]);
}
// update affected project classpaths
if (!affectedProjectClasspaths.isEmpty()) {
String[] dbgVariableNames = this.variableNames;
try {
// propagate classpath change
Iterator projectsToUpdate = affectedProjectClasspaths.keySet().iterator();
while (projectsToUpdate.hasNext()) {
if (this.progressMonitor != null && this.progressMonitor.isCanceled()) return;
JavaProject affectedProject = (JavaProject) projectsToUpdate.next();
// force resolved classpath to be recomputed
if (JavaModelManager.CP_RESOLVE_VERBOSE_ADVANCED)
verbose_update_project(dbgVariableNames, affectedProject);
ClasspathChange classpathChange = affectedProject.getPerProjectInfo().resetResolvedClasspath();
// if needed, generate delta, update project ref, create markers, ...
classpathChanged(classpathChange, true/*refresh if external linked folder already exists*/);
if (this.canChangeResources) {
// touch project to force a build if needed
affectedProject.getProject().touch(this.progressMonitor);
}
}
} catch (CoreException e) {
if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE){
verbose_failure(dbgVariableNames);
e.printStackTrace();
}
if (e instanceof JavaModelException) {
throw (JavaModelException)e;
} else {
throw new JavaModelException(e);
}
}
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected void executeOperation() throws JavaModelException {
try {
beginTask(getMainTaskName(), getMainAmountOfWork());
JavaElementDelta delta = newJavaElementDelta();
ICompilationUnit unit = getCompilationUnit();
generateNewCompilationUnitAST(unit);
if (this.creationOccurred) {
//a change has really occurred
unit.save(null, false);
boolean isWorkingCopy = unit.isWorkingCopy();
if (!isWorkingCopy)
setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
worked(1);
this.resultElements = generateResultHandles();
if (!isWorkingCopy // if unit is working copy, then save will have already fired the delta
&& !Util.isExcluded(unit)
&& unit.getParent().exists()) {
for (int i = 0; i < this.resultElements.length; i++) {
delta.added(this.resultElements[i]);
}
addDelta(delta);
} // else unit is created outside classpath
// non-java resource delta will be notified by delta processor
}
} finally {
done();
}
}
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected void generateNewCompilationUnitAST(ICompilationUnit cu) throws JavaModelException {
this.cuAST = parse(cu);
AST ast = this.cuAST.getAST();
ASTRewrite rewriter = ASTRewrite.create(ast);
ASTNode child = generateElementAST(rewriter, cu);
if (child != null) {
ASTNode parent = ((JavaElement) getParentElement()).findNode(this.cuAST);
if (parent == null)
parent = this.cuAST;
insertASTNode(rewriter, parent, child);
TextEdit edits = rewriter.rewriteAST();
applyTextEdit(cu, edits);
}
worked(1);
}
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected void insertASTNode(ASTRewrite rewriter, ASTNode parent, ASTNode child) throws JavaModelException {
StructuralPropertyDescriptor propertyDescriptor = getChildPropertyDescriptor(parent);
if (propertyDescriptor instanceof ChildListPropertyDescriptor) {
ChildListPropertyDescriptor childListPropertyDescriptor = (ChildListPropertyDescriptor) propertyDescriptor;
ListRewrite rewrite = rewriter.getListRewrite(parent, childListPropertyDescriptor);
switch (this.insertionPolicy) {
case INSERT_BEFORE:
ASTNode element = ((JavaElement) this.anchorElement).findNode(this.cuAST);
if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass()))
rewrite.insertBefore(child, element, null);
else
// case of an empty import list: the anchor element is the top level type and cannot be used in insertBefore as it is not the same type
rewrite.insertLast(child, null);
break;
case INSERT_AFTER:
element = ((JavaElement) this.anchorElement).findNode(this.cuAST);
if (childListPropertyDescriptor.getElementType().isAssignableFrom(element.getClass()))
rewrite.insertAfter(child, element, null);
else
// case of an empty import list: the anchor element is the top level type and cannot be used in insertAfter as it is not the same type
rewrite.insertLast(child, null);
break;
case INSERT_LAST:
rewrite.insertLast(child, null);
break;
}
} else {
rewriter.set(parent, propertyDescriptor, child, null);
}
}
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected CompilationUnit parse(ICompilationUnit cu) throws JavaModelException {
// ensure cu is consistent (noop if already consistent)
cu.makeConsistent(this.progressMonitor);
// create an AST for the compilation unit
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(cu);
return (CompilationUnit) parser.createAST(this.progressMonitor);
}
// in model/org/eclipse/jdt/internal/core/Initializer.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
}
// in model/org/eclipse/jdt/internal/core/ImportDeclaration.java
public int getFlags() throws JavaModelException {
ImportDeclarationElementInfo info = (ImportDeclarationElementInfo)getElementInfo();
return info.getModifiers();
}
// in model/org/eclipse/jdt/internal/core/ImportDeclaration.java
public ISourceRange getNameRange() throws JavaModelException {
ImportDeclarationElementInfo info = (ImportDeclarationElementInfo) getElementInfo();
return info.getNameRange();
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private CompilationUnitDeclaration convert(ISourceType[] sourceTypes, CompilationResult compilationResult) throws JavaModelException {
this.unit = new CompilationUnitDeclaration(this.problemReporter, compilationResult, 0);
// not filled at this point
if (sourceTypes.length == 0) return this.unit;
SourceTypeElementInfo topLevelTypeInfo = (SourceTypeElementInfo) sourceTypes[0];
org.eclipse.jdt.core.ICompilationUnit cuHandle = topLevelTypeInfo.getHandle().getCompilationUnit();
this.cu = (ICompilationUnit) cuHandle;
if (this.has1_5Compliance && ((CompilationUnitElementInfo) ((JavaElement) this.cu).getElementInfo()).annotationNumber > 10) { // experimental value
// If more than 10 annotations, diet parse as this is faster, but not if
// the client wants local and anonymous types to be converted (https://bugs.eclipse.org/bugs/show_bug.cgi?id=254738)
if ((this.flags & LOCAL_TYPE) == 0) {
return new Parser(this.problemReporter, true).dietParse(this.cu, compilationResult);
}
}
/* only positions available */
int start = topLevelTypeInfo.getNameSourceStart();
int end = topLevelTypeInfo.getNameSourceEnd();
/* convert package and imports */
String[] packageName = ((PackageFragment) cuHandle.getParent()).names;
if (packageName.length > 0)
// if its null then it is defined in the default package
this.unit.currentPackage =
createImportReference(packageName, start, end, false, ClassFileConstants.AccDefault);
IImportDeclaration[] importDeclarations = topLevelTypeInfo.getHandle().getCompilationUnit().getImports();
int importCount = importDeclarations.length;
this.unit.imports = new ImportReference[importCount];
for (int i = 0; i < importCount; i++) {
ImportDeclaration importDeclaration = (ImportDeclaration) importDeclarations[i];
ISourceImport sourceImport = (ISourceImport) importDeclaration.getElementInfo();
String nameWithoutStar = importDeclaration.getNameWithoutStar();
this.unit.imports[i] = createImportReference(
Util.splitOn('.', nameWithoutStar, 0, nameWithoutStar.length()),
sourceImport.getDeclarationSourceStart(),
sourceImport.getDeclarationSourceEnd(),
importDeclaration.isOnDemand(),
sourceImport.getModifiers());
}
/* convert type(s) */
try {
int typeCount = sourceTypes.length;
final TypeDeclaration[] types = new TypeDeclaration[typeCount];
/*
* We used a temporary types collection to prevent this.unit.types from being null during a call to
* convert(...) when the source is syntactically incorrect and the parser is flushing the unit's types.
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97466
*/
for (int i = 0; i < typeCount; i++) {
SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) sourceTypes[i];
types[i] = convert((SourceType) typeInfo.getHandle(), compilationResult);
}
this.unit.types = types;
return this.unit;
} catch (AnonymousMemberFound e) {
return new Parser(this.problemReporter, true).parse(this.cu, compilationResult);
}
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private Initializer convert(InitializerElementInfo initializerInfo, CompilationResult compilationResult) throws JavaModelException {
Block block = new Block(0);
Initializer initializer = new Initializer(block, ClassFileConstants.AccDefault);
int start = initializerInfo.getDeclarationSourceStart();
int end = initializerInfo.getDeclarationSourceEnd();
initializer.sourceStart = initializer.declarationSourceStart = start;
initializer.sourceEnd = initializer.declarationSourceEnd = end;
initializer.modifiers = initializerInfo.getModifiers();
/* convert local and anonymous types */
IJavaElement[] children = initializerInfo.getChildren();
int typesLength = children.length;
if (typesLength > 0) {
Statement[] statements = new Statement[typesLength];
for (int i = 0; i < typesLength; i++) {
SourceType type = (SourceType) children[i];
TypeDeclaration localType = convert(type, compilationResult);
if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
expression.type = localType.superclass;
localType.superclass = null;
localType.superInterfaces = null;
localType.allocation = expression;
statements[i] = expression;
} else {
statements[i] = localType;
}
}
block.statements = statements;
}
return initializer;
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private FieldDeclaration convert(SourceField fieldHandle, TypeDeclaration type, CompilationResult compilationResult) throws JavaModelException {
SourceFieldElementInfo fieldInfo = (SourceFieldElementInfo) fieldHandle.getElementInfo();
FieldDeclaration field = new FieldDeclaration();
int start = fieldInfo.getNameSourceStart();
int end = fieldInfo.getNameSourceEnd();
field.name = fieldHandle.getElementName().toCharArray();
field.sourceStart = start;
field.sourceEnd = end;
field.declarationSourceStart = fieldInfo.getDeclarationSourceStart();
field.declarationSourceEnd = fieldInfo.getDeclarationSourceEnd();
int modifiers = fieldInfo.getModifiers();
boolean isEnumConstant = (modifiers & ClassFileConstants.AccEnum) != 0;
if (isEnumConstant) {
field.modifiers = modifiers & ~ClassFileConstants.AccEnum; // clear AccEnum bit onto AST (binding will add it)
} else {
field.modifiers = modifiers;
field.type = createTypeReference(fieldInfo.getTypeName(), start, end);
}
// convert 1.5 specific constructs only if compliance is 1.5 or above
if (this.has1_5Compliance) {
/* convert annotations */
field.annotations = convertAnnotations(fieldHandle);
}
/* conversion of field constant */
if ((this.flags & FIELD_INITIALIZATION) != 0) {
char[] initializationSource = fieldInfo.getInitializationSource();
if (initializationSource != null) {
if (this.parser == null) {
this.parser = new Parser(this.problemReporter, true);
}
this.parser.parse(field, type, this.unit, initializationSource);
}
}
/* conversion of local and anonymous types */
if ((this.flags & LOCAL_TYPE) != 0) {
IJavaElement[] children = fieldInfo.getChildren();
int childrenLength = children.length;
if (childrenLength == 1) {
field.initialization = convert(children[0], isEnumConstant ? field : null, compilationResult);
} else if (childrenLength > 1) {
ArrayInitializer initializer = new ArrayInitializer();
field.initialization = initializer;
Expression[] expressions = new Expression[childrenLength];
initializer.expressions = expressions;
for (int i = 0; i < childrenLength; i++) {
expressions[i] = convert(children[i], isEnumConstant ? field : null, compilationResult);
}
}
}
return field;
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private QualifiedAllocationExpression convert(IJavaElement localType, FieldDeclaration enumConstant, CompilationResult compilationResult) throws JavaModelException {
TypeDeclaration anonymousLocalTypeDeclaration = convert((SourceType) localType, compilationResult);
QualifiedAllocationExpression expression = new QualifiedAllocationExpression(anonymousLocalTypeDeclaration);
expression.type = anonymousLocalTypeDeclaration.superclass;
anonymousLocalTypeDeclaration.superclass = null;
anonymousLocalTypeDeclaration.superInterfaces = null;
anonymousLocalTypeDeclaration.allocation = expression;
if (enumConstant != null) {
anonymousLocalTypeDeclaration.modifiers &= ~ClassFileConstants.AccEnum;
expression.enumConstant = enumConstant;
expression.type = null;
}
return expression;
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private AbstractMethodDeclaration convert(SourceMethod methodHandle, SourceMethodElementInfo methodInfo, CompilationResult compilationResult) throws JavaModelException {
AbstractMethodDeclaration method;
/* only source positions available */
int start = methodInfo.getNameSourceStart();
int end = methodInfo.getNameSourceEnd();
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, Even when this type is being constructed
on behalf of a 1.4 project we must internalize type variables properly in order to be able to
recognize usages of them in the method signature, to apply substitutions and thus to be able to
detect overriding in the presence of generics. If we simply drop them, when the method signature
refers to the type parameter, we won't know it should be bound to the type parameter and perform
incorrect lookup and may mistakenly end up with missing types
*/
TypeParameter[] typeParams = null;
char[][] typeParameterNames = methodInfo.getTypeParameterNames();
if (typeParameterNames != null) {
int parameterCount = typeParameterNames.length;
if (parameterCount > 0) { // method's type parameters must be null if no type parameter
char[][][] typeParameterBounds = methodInfo.getTypeParameterBounds();
typeParams = new TypeParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
typeParams[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start, end);
}
}
}
int modifiers = methodInfo.getModifiers();
if (methodInfo.isConstructor()) {
ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult);
decl.bits &= ~ASTNode.IsDefaultConstructor;
method = decl;
decl.typeParameters = typeParams;
} else {
MethodDeclaration decl;
if (methodInfo.isAnnotationMethod()) {
AnnotationMethodDeclaration annotationMethodDeclaration = new AnnotationMethodDeclaration(compilationResult);
/* conversion of default value */
SourceAnnotationMethodInfo annotationMethodInfo = (SourceAnnotationMethodInfo) methodInfo;
boolean hasDefaultValue = annotationMethodInfo.defaultValueStart != -1 || annotationMethodInfo.defaultValueEnd != -1;
if ((this.flags & FIELD_INITIALIZATION) != 0) {
if (hasDefaultValue) {
char[] defaultValueSource = CharOperation.subarray(getSource(), annotationMethodInfo.defaultValueStart, annotationMethodInfo.defaultValueEnd+1);
if (defaultValueSource != null) {
Expression expression = parseMemberValue(defaultValueSource);
if (expression != null) {
annotationMethodDeclaration.defaultValue = expression;
}
} else {
// could not retrieve the default value
hasDefaultValue = false;
}
}
}
if (hasDefaultValue)
modifiers |= ClassFileConstants.AccAnnotationDefault;
decl = annotationMethodDeclaration;
} else {
decl = new MethodDeclaration(compilationResult);
}
// convert return type
decl.returnType = createTypeReference(methodInfo.getReturnTypeName(), start, end);
// type parameters
decl.typeParameters = typeParams;
method = decl;
}
method.selector = methodHandle.getElementName().toCharArray();
boolean isVarargs = (modifiers & ClassFileConstants.AccVarargs) != 0;
method.modifiers = modifiers & ~ClassFileConstants.AccVarargs;
method.sourceStart = start;
method.sourceEnd = end;
method.declarationSourceStart = methodInfo.getDeclarationSourceStart();
method.declarationSourceEnd = methodInfo.getDeclarationSourceEnd();
// convert 1.5 specific constructs only if compliance is 1.5 or above
if (this.has1_5Compliance) {
/* convert annotations */
method.annotations = convertAnnotations(methodHandle);
}
/* convert arguments */
String[] argumentTypeSignatures = methodHandle.getParameterTypes();
char[][] argumentNames = methodInfo.getArgumentNames();
int argumentCount = argumentTypeSignatures == null ? 0 : argumentTypeSignatures.length;
if (argumentCount > 0) {
long position = ((long) start << 32) + end;
method.arguments = new Argument[argumentCount];
for (int i = 0; i < argumentCount; i++) {
TypeReference typeReference = createTypeReference(argumentTypeSignatures[i], start, end);
if (isVarargs && i == argumentCount-1) {
typeReference.bits |= ASTNode.IsVarArgs;
}
method.arguments[i] =
new Argument(
argumentNames[i],
position,
typeReference,
ClassFileConstants.AccDefault);
// do not care whether was final or not
}
}
/* convert thrown exceptions */
char[][] exceptionTypeNames = methodInfo.getExceptionTypeNames();
int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length;
if (exceptionCount > 0) {
method.thrownExceptions = new TypeReference[exceptionCount];
for (int i = 0; i < exceptionCount; i++) {
method.thrownExceptions[i] =
createTypeReference(exceptionTypeNames[i], start, end);
}
}
/* convert local and anonymous types */
if ((this.flags & LOCAL_TYPE) != 0) {
IJavaElement[] children = methodInfo.getChildren();
int typesLength = children.length;
if (typesLength != 0) {
Statement[] statements = new Statement[typesLength];
for (int i = 0; i < typesLength; i++) {
SourceType type = (SourceType) children[i];
TypeDeclaration localType = convert(type, compilationResult);
if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
expression.type = localType.superclass;
localType.superclass = null;
localType.superInterfaces = null;
localType.allocation = expression;
statements[i] = expression;
} else {
statements[i] = localType;
}
}
method.statements = statements;
}
}
return method;
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private TypeDeclaration convert(SourceType typeHandle, CompilationResult compilationResult) throws JavaModelException {
SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) typeHandle.getElementInfo();
if (typeInfo.isAnonymousMember())
throw new AnonymousMemberFound();
/* create type declaration - can be member type */
TypeDeclaration type = new TypeDeclaration(compilationResult);
if (typeInfo.getEnclosingType() == null) {
if (typeHandle.isAnonymous()) {
type.name = CharOperation.NO_CHAR;
type.bits |= (ASTNode.IsAnonymousType|ASTNode.IsLocalType);
} else {
if (typeHandle.isLocal()) {
type.bits |= ASTNode.IsLocalType;
}
}
} else {
type.bits |= ASTNode.IsMemberType;
}
if ((type.bits & ASTNode.IsAnonymousType) == 0) {
type.name = typeInfo.getName();
}
type.name = typeInfo.getName();
int start, end; // only positions available
type.sourceStart = start = typeInfo.getNameSourceStart();
type.sourceEnd = end = typeInfo.getNameSourceEnd();
type.modifiers = typeInfo.getModifiers();
type.declarationSourceStart = typeInfo.getDeclarationSourceStart();
type.declarationSourceEnd = typeInfo.getDeclarationSourceEnd();
type.bodyEnd = type.declarationSourceEnd;
// convert 1.5 specific constructs only if compliance is 1.5 or above
if (this.has1_5Compliance) {
/* convert annotations */
type.annotations = convertAnnotations(typeHandle);
}
/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, even in a 1.4 project, we
must internalize type variables and observe any parameterization of super class
and/or super interfaces in order to be able to detect overriding in the presence
of generics.
*/
char[][] typeParameterNames = typeInfo.getTypeParameterNames();
if (typeParameterNames.length > 0) {
int parameterCount = typeParameterNames.length;
char[][][] typeParameterBounds = typeInfo.getTypeParameterBounds();
type.typeParameters = new TypeParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
type.typeParameters[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start, end);
}
}
/* set superclass and superinterfaces */
if (typeInfo.getSuperclassName() != null) {
type.superclass = createTypeReference(typeInfo.getSuperclassName(), start, end, true /* include generics */);
type.superclass.bits |= ASTNode.IsSuperType;
}
char[][] interfaceNames = typeInfo.getInterfaceNames();
int interfaceCount = interfaceNames == null ? 0 : interfaceNames.length;
if (interfaceCount > 0) {
type.superInterfaces = new TypeReference[interfaceCount];
for (int i = 0; i < interfaceCount; i++) {
type.superInterfaces[i] = createTypeReference(interfaceNames[i], start, end, true /* include generics */);
type.superInterfaces[i].bits |= ASTNode.IsSuperType;
}
}
/* convert member types */
if ((this.flags & MEMBER_TYPE) != 0) {
SourceType[] sourceMemberTypes = typeInfo.getMemberTypeHandles();
int sourceMemberTypeCount = sourceMemberTypes.length;
type.memberTypes = new TypeDeclaration[sourceMemberTypeCount];
for (int i = 0; i < sourceMemberTypeCount; i++) {
type.memberTypes[i] = convert(sourceMemberTypes[i], compilationResult);
type.memberTypes[i].enclosingType = type;
}
}
/* convert intializers and fields*/
InitializerElementInfo[] initializers = null;
int initializerCount = 0;
if ((this.flags & LOCAL_TYPE) != 0) {
initializers = typeInfo.getInitializers();
initializerCount = initializers.length;
}
SourceField[] sourceFields = null;
int sourceFieldCount = 0;
if ((this.flags & FIELD) != 0) {
sourceFields = typeInfo.getFieldHandles();
sourceFieldCount = sourceFields.length;
}
int length = initializerCount + sourceFieldCount;
if (length > 0) {
type.fields = new FieldDeclaration[length];
for (int i = 0; i < initializerCount; i++) {
type.fields[i] = convert(initializers[i], compilationResult);
}
int index = 0;
for (int i = initializerCount; i < length; i++) {
type.fields[i] = convert(sourceFields[index++], type, compilationResult);
}
}
/* convert methods - need to add default constructor if necessary */
boolean needConstructor = (this.flags & CONSTRUCTOR) != 0;
boolean needMethod = (this.flags & METHOD) != 0;
if (needConstructor || needMethod) {
SourceMethod[] sourceMethods = typeInfo.getMethodHandles();
int sourceMethodCount = sourceMethods.length;
/* source type has a constructor ? */
/* by default, we assume that one is needed. */
int extraConstructor = 0;
int methodCount = 0;
int kind = TypeDeclaration.kind(type.modifiers);
boolean isAbstract = kind == TypeDeclaration.INTERFACE_DECL || kind == TypeDeclaration.ANNOTATION_TYPE_DECL;
if (!isAbstract) {
extraConstructor = needConstructor ? 1 : 0;
for (int i = 0; i < sourceMethodCount; i++) {
if (sourceMethods[i].isConstructor()) {
if (needConstructor) {
extraConstructor = 0; // Does not need the extra constructor since one constructor already exists.
methodCount++;
}
} else if (needMethod) {
methodCount++;
}
}
} else {
methodCount = needMethod ? sourceMethodCount : 0;
}
type.methods = new AbstractMethodDeclaration[methodCount + extraConstructor];
if (extraConstructor != 0) { // add default constructor in first position
type.methods[0] = type.createDefaultConstructor(false, false);
}
int index = 0;
boolean hasAbstractMethods = false;
for (int i = 0; i < sourceMethodCount; i++) {
SourceMethod sourceMethod = sourceMethods[i];
SourceMethodElementInfo methodInfo = (SourceMethodElementInfo)sourceMethod.getElementInfo();
boolean isConstructor = methodInfo.isConstructor();
if ((methodInfo.getModifiers() & ClassFileConstants.AccAbstract) != 0) {
hasAbstractMethods = true;
}
if ((isConstructor && needConstructor) || (!isConstructor && needMethod)) {
AbstractMethodDeclaration method = convert(sourceMethod, methodInfo, compilationResult);
if (isAbstract || method.isAbstract()) { // fix-up flag
method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
}
type.methods[extraConstructor + index++] = method;
}
}
if (hasAbstractMethods) type.bits |= ASTNode.HasAbstractMethods;
}
return type;
}
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
private Annotation[] convertAnnotations(IAnnotatable element) throws JavaModelException {
IAnnotation[] annotations = element.getAnnotations();
int length = annotations.length;
Annotation[] astAnnotations = new Annotation[length];
if (length > 0) {
char[] cuSource = getSource();
int recordedAnnotations = 0;
for (int i = 0; i < length; i++) {
ISourceRange positions = annotations[i].getSourceRange();
int start = positions.getOffset();
int end = start + positions.getLength();
char[] annotationSource = CharOperation.subarray(cuSource, start, end);
if (annotationSource != null) {
Expression expression = parseMemberValue(annotationSource);
/*
* expression can be null or not an annotation if the source has changed between
* the moment where the annotation source positions have been retrieved and the moment were
* this parsing occurred.
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=90916
*/
if (expression instanceof Annotation) {
astAnnotations[recordedAnnotations++] = (Annotation) expression;
}
}
}
if (length != recordedAnnotations) {
// resize to remove null annotations
System.arraycopy(astAnnotations, 0, (astAnnotations = new Annotation[recordedAnnotations]), 0, recordedAnnotations);
}
}
return astAnnotations;
}
// in model/org/eclipse/jdt/internal/compiler/ExtraFlags.java
public static int getExtraFlags(IType type) throws JavaModelException {
int extraFlags = 0;
if (type.isMember()) {
extraFlags |= ExtraFlags.IsMemberType;
}
if (type.isLocal()) {
extraFlags |= ExtraFlags.IsLocalType;
}
IType[] memberTypes = type.getTypes();
int memberTypeCounter = memberTypes == null ? 0 : memberTypes.length;
if (memberTypeCounter > 0) {
done : for (int i = 0; i < memberTypeCounter; i++) {
int flags = memberTypes[i].getFlags();
// if the member type is static and not private
if ((flags & ClassFileConstants.AccStatic) != 0 && (flags & ClassFileConstants.AccPrivate) == 0 ) {
extraFlags |= ExtraFlags.HasNonPrivateStaticMemberTypes;
break done;
}
}
}
return extraFlags;
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathContainer getClasspathContainer(IPath containerPath, IJavaProject project) throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
IClasspathContainer container = manager.getClasspathContainer(containerPath, project);
if (container == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
return manager.getPreviousSessionContainer(containerPath, project);
}
return container;
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static ITypeHierarchy newTypeHierarchy(IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
if (region == null) {
throw new IllegalArgumentException(Messages.hierarchy_nullRegion);
}
ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/);
CreateTypeHierarchyOperation op =
new CreateTypeHierarchyOperation(region, workingCopies, null, true/*compute subtypes*/);
op.runOperation(monitor);
return op.getResult();
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static void setClasspathContainer(IPath containerPath, IJavaProject[] affectedProjects, IClasspathContainer[] respectiveContainers, IProgressMonitor monitor) throws JavaModelException {
if (affectedProjects.length != respectiveContainers.length)
throw new ClasspathEntry.AssertionFailedException("Projects and containers collections should have the same size"); //$NON-NLS-1$
if (affectedProjects.length == 1) {
IClasspathContainer container = respectiveContainers[0];
if (container != null) {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
IJavaProject project = affectedProjects[0];
IClasspathContainer existingCointainer = manager.containerGet(project, containerPath);
if (existingCointainer == JavaModelManager.CONTAINER_INITIALIZATION_IN_PROGRESS) {
manager.containerBeingInitializedPut(project, containerPath, container);
return;
}
}
}
SetContainerOperation operation = new SetContainerOperation(containerPath, affectedProjects, respectiveContainers);
operation.runOperation(monitor);
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static void setClasspathVariable(String variableName, IPath path)
throws JavaModelException {
setClasspathVariable(variableName, path, null);
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static void setClasspathVariable(
String variableName,
IPath path,
IProgressMonitor monitor)
throws JavaModelException {
if (path == null) throw new ClasspathEntry.AssertionFailedException("Variable path cannot be null"); //$NON-NLS-1$
setClasspathVariables(new String[]{variableName}, new IPath[]{ path }, monitor);
}
// in model/org/eclipse/jdt/core/JavaCore.java
public static void setClasspathVariables(
String[] variableNames,
IPath[] paths,
IProgressMonitor monitor)
throws JavaModelException {
if (variableNames.length != paths.length) throw new ClasspathEntry.AssertionFailedException("Variable names and paths collections should have the same size"); //$NON-NLS-1$
SetVariablesOperation operation = new SetVariablesOperation(variableNames, paths, true/*update preferences*/);
operation.runOperation(monitor);
}
// in model/org/eclipse/jdt/core/compiler/ReconcileContext.java
public org.eclipse.jdt.core.dom.CompilationUnit getAST3() throws JavaModelException {
if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
// create AST (optionally resolving bindings)
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
parser.setResolveBindings(true);
parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
parser.setSource(this.workingCopy);
parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
}
return this.operation.makeConsistent(this.workingCopy);
}
// in model/org/eclipse/jdt/core/compiler/ReconcileContext.java
public org.eclipse.jdt.core.dom.CompilationUnit getAST4() throws JavaModelException {
if (this.operation.astLevel != AST.JLS4 || !this.operation.resolveBindings) {
// create AST (optionally resolving bindings)
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
parser.setResolveBindings(true);
parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
parser.setSource(this.workingCopy);
parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
}
return this.operation.makeConsistent(this.workingCopy);
}
// in model/org/eclipse/jdt/core/CorrectionEngine.java
public void computeCorrections(IMarker marker, ICompilationUnit targetUnit, int positionOffset, ICorrectionRequestor requestor) throws JavaModelException {
IJavaElement element = targetUnit == null ? JavaCore.create(marker.getResource()) : targetUnit;
if(!(element instanceof ICompilationUnit))
return;
ICompilationUnit unit = (ICompilationUnit) element;
int id = marker.getAttribute(IJavaModelMarker.ID, -1);
String[] args = Util.getProblemArgumentsFromMarker(marker.getAttribute(IJavaModelMarker.ARGUMENTS, "")); //$NON-NLS-1$
int start = marker.getAttribute(IMarker.CHAR_START, -1);
int end = marker.getAttribute(IMarker.CHAR_END, -1);
computeCorrections(unit, id, start + positionOffset, end + positionOffset, args, requestor);
}
// in model/org/eclipse/jdt/core/CorrectionEngine.java
public void computeCorrections(IProblem problem, ICompilationUnit targetUnit, ICorrectionRequestor requestor) throws JavaModelException {
if (requestor == null) {
throw new IllegalArgumentException(Messages.correction_nullUnit);
}
this.computeCorrections(
targetUnit, problem.getID(),
problem.getSourceStart(),
problem.getSourceEnd(),
problem.getArguments(),
requestor);
}
// in model/org/eclipse/jdt/core/util/CompilationUnitSorter.java
public static void sort(ICompilationUnit compilationUnit,
int[] positions,
Comparator comparator,
int options,
IProgressMonitor monitor) throws JavaModelException {
sort(AST.JLS2, compilationUnit, positions, comparator, options, monitor);
}
// in model/org/eclipse/jdt/core/util/CompilationUnitSorter.java
public static void sort(int level, ICompilationUnit compilationUnit,
int[] positions,
Comparator comparator,
int options,
IProgressMonitor monitor) throws JavaModelException {
if (compilationUnit == null || comparator == null) {
throw new IllegalArgumentException();
}
checkASTLevel(level);
ICompilationUnit[] compilationUnits = new ICompilationUnit[] { compilationUnit };
SortElementsOperation operation = new SortElementsOperation(level, compilationUnits, positions, comparator);
operation.runOperation(monitor);
}
// in model/org/eclipse/jdt/core/util/CompilationUnitSorter.java
public static TextEdit sort(CompilationUnit unit,
Comparator comparator,
int options,
TextEditGroup group,
IProgressMonitor monitor) throws JavaModelException {
if (unit == null || comparator == null) {
throw new IllegalArgumentException();
}
SortElementsOperation operation = new SortElementsOperation(AST.JLS4, new IJavaElement[] { unit.getJavaElement() }, null, comparator);
return operation.calculateEdit(unit, group);
}
// in model/org/eclipse/jdt/core/WorkingCopyOwner.java
public final ICompilationUnit newWorkingCopy(String name, IClasspathEntry[] classpath, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
ExternalJavaProject project = new ExternalJavaProject(classpath);
IPackageFragment parent = ((PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject())).getPackageFragment(CharOperation.NO_STRINGS);
CompilationUnit result = new CompilationUnit((PackageFragment) parent, name, this);
result.becomeWorkingCopy(problemRequestor, monitor);
return result;
}
// in model/org/eclipse/jdt/core/WorkingCopyOwner.java
public final ICompilationUnit newWorkingCopy(String name, IClasspathEntry[] classpath, IProgressMonitor monitor) throws JavaModelException {
ExternalJavaProject project = new ExternalJavaProject(classpath);
IPackageFragment parent = ((PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject())).getPackageFragment(CharOperation.NO_STRINGS);
CompilationUnit result = new CompilationUnit((PackageFragment) parent, name, this);
result.becomeWorkingCopy(getProblemRequestor(result), monitor);
return result;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceType.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceType.java
public String getFullyQualifiedParameterizedName() throws JavaModelException {
if (isResolved()) {
return getFullyQualifiedParameterizedName(getFullyQualifiedName('.'), this.getKey());
}
return getFullyQualifiedName('.', true/*show parameters*/);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistCompilationUnit.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistCompilationUnit.java
public boolean hasChildren() throws JavaModelException {
JavaElementInfo info = (JavaElementInfo)this.infoCache.get(this);
return info.getChildren().length > 0;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistInitializer.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceMethod.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistAnnotation.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistImportContainer.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistImportDeclaration.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceField.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistTypeParameter.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistPackageDeclaration.java
public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
return this.infoCache.get(this);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
private IMethod findMethod(IType type, char[] selector, char[][] paramTypeNames) throws JavaModelException {
IMethod method = null;
int startingIndex = 0;
String[] args;
IType enclosingType = type.getDeclaringType();
// If the method is a constructor of a non-static inner type, add the enclosing type as an
// additional parameter to the constructor
if (enclosingType != null
&& CharOperation.equals(type.getElementName().toCharArray(), selector)
&& !Flags.isStatic(type.getFlags())) {
args = new String[paramTypeNames.length+1];
startingIndex = 1;
args[0] = Signature.createTypeSignature(enclosingType.getFullyQualifiedName(), true);
} else {
args = new String[paramTypeNames.length];
}
int length = args.length;
for(int i = startingIndex; i< length ; i++){
args[i] = new String(paramTypeNames[i-startingIndex]);
}
method = type.getMethod(new String(selector), args);
IMethod[] methods = type.findMethods(method);
if (methods != null && methods.length > 0) {
method = methods[0];
}
return method;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public void selectType(char[] typeName, IType context) throws JavaModelException {
try {
this.acceptedAnswer = false;
// only the type erasure are returned by IType.resolvedType(...)
if (CharOperation.indexOf('<', typeName) != -1) {
char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
typeSig = Signature.getTypeErasure(typeSig);
typeName = Signature.toCharArray(typeSig);
}
// find the outer most type
IType outerType = context;
IType parent = context.getDeclaringType();
while (parent != null) {
outerType = parent;
parent = parent.getDeclaringType();
}
// compute parse tree for this most outer type
CompilationUnitDeclaration parsedUnit = null;
TypeDeclaration typeDeclaration = null;
org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit();
if (cu != null) {
IType[] topLevelTypes = cu.getTypes();
int length = topLevelTypes.length;
SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
for (int i = 0; i < length; i++) {
topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType)topLevelTypes[i]).getElementInfo();
}
ISourceType outerTypeInfo = (ISourceType) ((SourceType) outerType).getElementInfo();
CompilationResult result = new CompilationResult(outerTypeInfo.getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit);
int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
if (context.isAnonymous() || context.isLocal())
flags |= SourceTypeConverter.LOCAL_TYPE;
parsedUnit =
SourceTypeConverter.buildCompilationUnit(
topLevelInfos,
flags,
this.parser.problemReporter(),
result);
if (parsedUnit != null && parsedUnit.types != null) {
if(DEBUG) {
System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
System.out.println(parsedUnit.toString());
}
// find the type declaration that corresponds to the original source type
typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context);
}
} else { // binary type
ClassFile classFile = (ClassFile) context.getClassFile();
ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo((IFile) classFile.resource(), false/*don't fully initialize so as to keep constant pool (used below)*/);
CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit);
parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0);
HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray();
BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result, typeNames);
typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit);
parsedUnit.imports = converter.buildImports(reader);
}
if (typeDeclaration != null) {
// add fake field with the type we're looking for
// note: since we didn't ask for fields above, there is no field defined yet
FieldDeclaration field = new FieldDeclaration();
int dot;
if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
this.selectedIdentifier = typeName;
field.type = new SelectionOnSingleTypeReference(typeName, -1);
// position not used
} else {
char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
char[] selectionIdentifier =
CharOperation.subarray(typeName, dot + 1, typeName.length);
this.selectedIdentifier = selectionIdentifier;
field.type =
new SelectionOnQualifiedTypeReference(
previousIdentifiers,
selectionIdentifier,
new long[previousIdentifiers.length + 1]);
}
field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
typeDeclaration.fields = new FieldDeclaration[] { field };
// build bindings
this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
if ((this.unitScope = parsedUnit.scope) != null) {
try {
// build fields
// note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
// resolve
parsedUnit.scope.faultInTypes();
parsedUnit.resolve();
} catch (SelectionNodeFound e) {
if (e.binding != null) {
if(DEBUG) {
System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$
System.out.println(e.binding.toString());
}
// if null then we found a problem in the selection node
selectFrom(e.binding, parsedUnit, e.isDeclaration);
}
}
}
}
if(this.noProposal && this.problem != null) {
this.requestor.acceptError(this.problem);
}
} catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
} finally {
reset(true);
}
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
protected MethodBinding findOverriddenMethodInType(ReferenceBinding overriddenType, MethodBinding overriding) throws JavaModelException {
if (overriddenType == null)
return null;
MethodBinding[] overriddenMethods= overriddenType.availableMethods();
LookupEnvironment lookupEnv = this.lookupEnvironment;
if (lookupEnv != null && overriddenMethods != null) {
for (int i= 0; i < overriddenMethods.length; i++) {
if (lookupEnv.methodVerifier().isMethodSubsignature(overriding, overriddenMethods[i])) {
return overriddenMethods[i];
}
}
}
return null;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
private Object findMethodWithAttachedDocInHierarchy(final MethodBinding method) throws JavaModelException {
ReferenceBinding type= method.declaringClass;
final SelectionRequestor requestor1 = (SelectionRequestor) this.requestor;
return new InheritDocVisitor() {
public Object visit(ReferenceBinding currType) throws JavaModelException {
MethodBinding overridden = findOverriddenMethodInType(currType, method);
if (overridden == null)
return InheritDocVisitor.CONTINUE;
TypeBinding args[] = overridden.parameters;
String names[] = new String[args.length];
for (int i = 0; i < args.length; i++) {
names[i] = Signature.createTypeSignature(args[i].sourceName(), false);
}
IMember member = (IMember) requestor1.findMethodFromBinding(overridden, names, overridden.declaringClass);
if (member == null)
return InheritDocVisitor.CONTINUE;
if (member.getAttachedJavadoc(null) != null ) {
// for binary methods with attached javadoc and no source attached
return overridden;
}
IOpenable openable = member.getOpenable();
if (openable == null)
return InheritDocVisitor.CONTINUE;
IBuffer buf= openable.getBuffer();
if (buf == null) {
// no source attachment found. This method maybe the one. Stop.
return InheritDocVisitor.STOP_BRANCH;
}
ISourceRange javadocRange= member.getJavadocRange();
if (javadocRange == null)
return InheritDocVisitor.CONTINUE; // this method doesn't have javadoc, continue to look.
String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength());
if (rawJavadoc != null) {
return overridden;
}
return InheritDocVisitor.CONTINUE;
}
}.visitInheritDoc(type);
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public Object visit(ReferenceBinding currType) throws JavaModelException {
MethodBinding overridden = findOverriddenMethodInType(currType, method);
if (overridden == null)
return InheritDocVisitor.CONTINUE;
TypeBinding args[] = overridden.parameters;
String names[] = new String[args.length];
for (int i = 0; i < args.length; i++) {
names[i] = Signature.createTypeSignature(args[i].sourceName(), false);
}
IMember member = (IMember) requestor1.findMethodFromBinding(overridden, names, overridden.declaringClass);
if (member == null)
return InheritDocVisitor.CONTINUE;
if (member.getAttachedJavadoc(null) != null ) {
// for binary methods with attached javadoc and no source attached
return overridden;
}
IOpenable openable = member.getOpenable();
if (openable == null)
return InheritDocVisitor.CONTINUE;
IBuffer buf= openable.getBuffer();
if (buf == null) {
// no source attachment found. This method maybe the one. Stop.
return InheritDocVisitor.STOP_BRANCH;
}
ISourceRange javadocRange= member.getJavadocRange();
if (javadocRange == null)
return InheritDocVisitor.CONTINUE; // this method doesn't have javadoc, continue to look.
String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength());
if (rawJavadoc != null) {
return overridden;
}
return InheritDocVisitor.CONTINUE;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public Object visitInheritDoc(ReferenceBinding currentType) throws JavaModelException {
ArrayList visited= new ArrayList();
visited.add(currentType);
Object result= visitInheritDocInterfaces(visited, currentType);
if (result != InheritDocVisitor.CONTINUE)
return result;
ReferenceBinding superClass= currentType.superclass();
while (superClass != null && ! visited.contains(superClass)) {
result= visit(superClass);
if (result == InheritDocVisitor.STOP_BRANCH) {
return null;
} else if (result == InheritDocVisitor.CONTINUE) {
visited.add(superClass);
result= visitInheritDocInterfaces(visited, superClass);
if (result != InheritDocVisitor.CONTINUE)
return result;
else
superClass= superClass.superclass();
} else {
return result;
}
}
return null;
}
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
private Object visitInheritDocInterfaces(ArrayList visited, ReferenceBinding currentType) throws JavaModelException {
ArrayList toVisitChildren= new ArrayList();
ReferenceBinding[] superInterfaces= currentType.superInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
ReferenceBinding superInterface= superInterfaces[i];
if (visited.contains(superInterface))
continue;
visited.add(superInterface);
Object result= visit(superInterface);
if (result == InheritDocVisitor.STOP_BRANCH) {
//skip
} else if (result == InheritDocVisitor.CONTINUE) {
toVisitChildren.add(superInterface);
} else {
return result;
}
}
for (Iterator iter= toVisitChildren.iterator(); iter.hasNext(); ) {
ReferenceBinding child= (ReferenceBinding) iter.next();
Object result= visitInheritDocInterfaces(visited, child);
if (result != InheritDocVisitor.CONTINUE)
return result;
}
return InheritDocVisitor.CONTINUE;
}
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
public MultiTextEdit getResultingEdits(IProgressMonitor monitor) throws JavaModelException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
try {
int importsStart= this.replaceRange.getOffset();
int importsLen= this.replaceRange.getLength();
String lineDelim= this.compilationUnit.findRecommendedLineSeparator();
IBuffer buffer= this.compilationUnit.getBuffer();
int currPos= importsStart;
MultiTextEdit resEdit= new MultiTextEdit();
if ((this.flags & F_NEEDS_LEADING_DELIM) != 0) {
// new import container
resEdit.addChild(new InsertEdit(currPos, lineDelim));
}
PackageEntry lastPackage= null;
Set onDemandConflicts= null;
if (this.findAmbiguousImports) {
onDemandConflicts= evaluateStarImportConflicts(monitor);
}
int spacesBetweenGroups= getSpacesBetweenImportGroups();
ArrayList stringsToInsert= new ArrayList();
int nPackageEntries= this.packageEntries.size();
for (int i= 0; i < nPackageEntries; i++) {
PackageEntry pack= (PackageEntry) this.packageEntries.get(i);
if (this.filterImplicitImports && !pack.isStatic() && isImplicitImport(pack.getName())) {
pack.filterImplicitImports(this.useContextToFilterImplicitImports);
}
int nImports= pack.getNumberOfImports();
if (nImports == 0) {
continue;
}
if (spacesBetweenGroups > 0) {
// add a space between two different groups by looking at the two adjacent imports
if (lastPackage != null && !pack.isComment() && !pack.isSameGroup(lastPackage)) {
ImportDeclEntry last= lastPackage.getImportAt(lastPackage.getNumberOfImports() - 1);
ImportDeclEntry first= pack.getImportAt(0);
if (!lastPackage.isComment() && (last.isNew() || first.isNew())) {
for (int k= spacesBetweenGroups; k > 0; k--) {
stringsToInsert.add(lineDelim);
}
}
}
}
lastPackage= pack;
boolean isStatic= pack.isStatic();
int threshold= isStatic ? this.staticImportOnDemandThreshold : this.importOnDemandThreshold;
boolean doStarImport= pack.hasStarImport(threshold, onDemandConflicts);
if (doStarImport && (pack.find("*") == null)) { //$NON-NLS-1$
String[] imports = getNewImportStrings(buffer, pack, isStatic, lineDelim);
for (int j = 0, max = imports.length; j < max; j++) {
stringsToInsert.add(imports[j]);
}
}
for (int k= 0; k < nImports; k++) {
ImportDeclEntry currDecl= pack.getImportAt(k);
IRegion region= currDecl.getSourceRange();
if (region == null) { // new entry
if (!doStarImport || currDecl.isOnDemand() || (onDemandConflicts != null && onDemandConflicts.contains(currDecl.getSimpleName()))) {
String str= getNewImportString(currDecl.getElementName(), isStatic, lineDelim);
stringsToInsert.add(str);
} else if (doStarImport && !currDecl.isOnDemand()) {
String simpleName = currDecl.getTypeQualifiedName();
if (simpleName.indexOf('.') != -1) {
String str= getNewImportString(currDecl.getElementName(), isStatic, lineDelim);
if (stringsToInsert.indexOf(str) == -1) {
stringsToInsert.add(str);
}
}
}
} else if (!doStarImport || currDecl.isOnDemand() || onDemandConflicts == null || onDemandConflicts.contains(currDecl.getSimpleName())) {
int offset= region.getOffset();
removeAndInsertNew(buffer, currPos, offset, stringsToInsert, resEdit);
stringsToInsert.clear();
currPos= offset + region.getLength();
} else if (doStarImport && !currDecl.isOnDemand()) {
String simpleName = currDecl.getTypeQualifiedName();
if (simpleName.indexOf('.') != -1) {
IRegion rangeBefore = currDecl.getPrecedingCommentRange();
if (rangeBefore != null) {
stringsToInsert.add(buffer.getText(rangeBefore.getOffset(), rangeBefore.getLength()));
}
IRegion rangeAfter = currDecl.getTrailingCommentRange();
String trailingComment = null;
if (rangeAfter != null) {
trailingComment = buffer.getText(rangeAfter.getOffset(), rangeAfter.getLength());
}
String str= getNewImportString(currDecl.getElementName(), isStatic, trailingComment, lineDelim);
if (stringsToInsert.indexOf(str) == -1) {
stringsToInsert.add(str);
}
}
}
}
}
// insert back all existing imports comments since existing imports were not preserved
if (this.preserveExistingCommentsRanges != null) {
for (int i = 0, max = this.preserveExistingCommentsRanges.length; i < max; i++) {
IRegion region = this.preserveExistingCommentsRanges[i];
String text = buffer.getText(region.getOffset(), region.getLength());
// remove preceding whitespaces
int index = 0;
int length = text.length();
loop: while (index < length) {
if (Character.isWhitespace(text.charAt(index))) {
index++;
} else {
break loop;
}
}
if (index != 0) {
text = text.substring(index);
}
if (!text.endsWith(lineDelim)) {
text += lineDelim;
}
stringsToInsert.add(text);
}
}
int end= importsStart + importsLen;
removeAndInsertNew(buffer, currPos, end, stringsToInsert, resEdit);
if (importsLen == 0) {
if (!this.importsCreated.isEmpty() || !this.staticImportsCreated.isEmpty()) { // new import container
if ((this.flags & F_NEEDS_TRAILING_DELIM) != 0) {
resEdit.addChild(new InsertEdit(currPos, lineDelim));
}
} else {
return new MultiTextEdit(); // no changes
}
}
return resEdit;
} finally {
monitor.done();
}
}
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
private Set evaluateStarImportConflicts(IProgressMonitor monitor) throws JavaModelException {
//long start= System.currentTimeMillis();
final HashSet/*String*/ onDemandConflicts= new HashSet();
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { this.compilationUnit.getJavaProject() });
ArrayList/*<char[][]>*/ starImportPackages= new ArrayList();
ArrayList/*<char[][]>*/ simpleTypeNames= new ArrayList();
int nPackageEntries= this.packageEntries.size();
for (int i= 0; i < nPackageEntries; i++) {
PackageEntry pack= (PackageEntry) this.packageEntries.get(i);
if (!pack.isStatic() && pack.hasStarImport(this.importOnDemandThreshold, null)) {
starImportPackages.add(pack.getName().toCharArray());
for (int k= 0; k < pack.getNumberOfImports(); k++) {
ImportDeclEntry curr= pack.getImportAt(k);
if (!curr.isOnDemand() && !curr.isComment()) {
simpleTypeNames.add(curr.getSimpleName().toCharArray());
}
}
}
}
if (starImportPackages.isEmpty()) {
return null;
}
starImportPackages.add(this.compilationUnit.getParent().getElementName().toCharArray());
starImportPackages.add(JAVA_LANG.toCharArray());
char[][] allPackages= (char[][]) starImportPackages.toArray(new char[starImportPackages.size()][]);
char[][] allTypes= (char[][]) simpleTypeNames.toArray(new char[simpleTypeNames.size()][]);
TypeNameRequestor requestor= new TypeNameRequestor() {
HashMap foundTypes= new HashMap();
private String getTypeContainerName(char[] packageName, char[][] enclosingTypeNames) {
StringBuffer buf= new StringBuffer();
buf.append(packageName);
for (int i= 0; i < enclosingTypeNames.length; i++) {
if (buf.length() > 0)
buf.append('.');
buf.append(enclosingTypeNames[i]);
}
return buf.toString();
}
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
String name= new String(simpleTypeName);
String containerName= getTypeContainerName(packageName, enclosingTypeNames);
String oldContainer= (String) this.foundTypes.put(name, containerName);
if (oldContainer != null && !oldContainer.equals(containerName)) {
onDemandConflicts.add(name);
}
}
};
new SearchEngine().searchAllTypeNames(allPackages, allTypes, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
return onDemandConflicts;
}
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public static ImportRewrite create(ICompilationUnit cu, boolean restoreExistingImports) throws JavaModelException {
if (cu == null) {
throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
}
List existingImport= null;
if (restoreExistingImports) {
existingImport= new ArrayList();
IImportDeclaration[] imports= cu.getImports();
for (int i= 0; i < imports.length; i++) {
IImportDeclaration curr= imports[i];
char prefix= Flags.isStatic(curr.getFlags()) ? STATIC_PREFIX : NORMAL_PREFIX;
existingImport.add(prefix + curr.getElementName());
}
}
return new ImportRewrite(cu, null, existingImport);
}
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public TextEdit rewriteAST() throws JavaModelException, IllegalArgumentException {
ASTNode rootNode= getRootNode();
if (rootNode == null) {
return new MultiTextEdit(); // no changes
}
ASTNode root= rootNode.getRoot();
if (!(root instanceof CompilationUnit)) {
throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
}
CompilationUnit astRoot= (CompilationUnit) root;
ITypeRoot typeRoot = astRoot.getTypeRoot();
if (typeRoot == null || typeRoot.getBuffer() == null) {
throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
}
char[] content= typeRoot.getBuffer().getCharacters();
LineInformation lineInfo= LineInformation.create(astRoot);
String lineDelim= typeRoot.findRecommendedLineSeparator();
Map options= typeRoot.getJavaProject().getOptions(true);
return internalRewriteAST(content, lineInfo, lineDelim, astRoot.getCommentList(), options, rootNode, (RecoveryScannerData)astRoot.getStatementsRecoveryData());
}
// in dom/org/eclipse/jdt/core/dom/NodeFinder.java
public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException {
NodeFinder finder = new NodeFinder(root, start, length);
ASTNode result= finder.getCoveredNode();
if (result == null)
return null;
int nodeStart= result.getStartPosition();
if (start <= nodeStart && ((nodeStart + result.getLength()) <= (start + length))) {
IBuffer buffer= source.getBuffer();
if (buffer != null) {
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
try {
scanner.setSource(buffer.getText(start, length).toCharArray());
int token= scanner.getNextToken();
if (token != ITerminalSymbols.TokenNameEOF) {
int tStart= scanner.getCurrentTokenStartPosition();
if (tStart == result.getStartPosition() - start) {
scanner.resetTo(tStart + result.getLength(), length - 1);
token= scanner.getNextToken();
if (token == ITerminalSymbols.TokenNameEOF)
return result;
}
}
} catch (InvalidInputException e) {
// ignore
} catch (IndexOutOfBoundsException e) {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001
return null;
}
}
}
return finder.getCoveringNode();
}
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static CompilationUnitDeclaration resolve(
org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit,
IJavaProject javaProject,
List classpaths,
NodeSearcher nodeSearcher,
Map options,
WorkingCopyOwner owner,
int flags,
IProgressMonitor monitor) throws JavaModelException {
CompilationUnitDeclaration unit = null;
INameEnvironmentWithProgress environment = null;
CancelableProblemFactory problemFactory = null;
CompilationUnitResolver resolver = null;
try {
if (javaProject == null) {
Classpath[] allEntries = new Classpath[classpaths.size()];
classpaths.toArray(allEntries);
environment = new NameEnvironmentWithProgress(allEntries, null, monitor);
} else {
environment = new CancelableNameEnvironment((JavaProject) javaProject, owner, monitor);
}
problemFactory = new CancelableProblemFactory(monitor);
CompilerOptions compilerOptions = getCompilerOptions(options, (flags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
boolean ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
compilerOptions.ignoreMethodBodies = ignoreMethodBodies;
resolver =
new CompilationUnitResolver(
environment,
getHandlingPolicy(),
compilerOptions,
getRequestor(),
problemFactory,
monitor,
javaProject != null);
boolean analyzeAndGenerateCode = !ignoreMethodBodies;
unit =
resolver.resolve(
null, // no existing compilation unit declaration
sourceUnit,
nodeSearcher,
true, // method verification
analyzeAndGenerateCode, // analyze code
analyzeAndGenerateCode); // generate code
if (resolver.hasCompilationAborted) {
// the bindings could not be resolved due to missing types in name environment
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=86541
CompilationUnitDeclaration unitDeclaration = parse(sourceUnit, nodeSearcher, options, flags);
final int problemCount = unit.compilationResult.problemCount;
if (problemCount != 0) {
unitDeclaration.compilationResult.problems = new CategorizedProblem[problemCount];
System.arraycopy(unit.compilationResult.problems, 0, unitDeclaration.compilationResult.problems, 0, problemCount);
unitDeclaration.compilationResult.problemCount = problemCount;
}
return unitDeclaration;
}
if (NameLookup.VERBOSE && environment instanceof CancelableNameEnvironment) {
CancelableNameEnvironment cancelableNameEnvironment = (CancelableNameEnvironment) environment;
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + cancelableNameEnvironment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + cancelableNameEnvironment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
}
return unit;
} finally {
if (environment != null) {
// don't hold a reference to this external object
environment.setMonitor(null);
}
if (problemFactory != null) {
problemFactory.monitor = null; // don't hold a reference to this external object
}
}
}