package org.eclipse.jdt.internal.core.util;
import java.io.*;
import java.net.URI;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.QualifiedType;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.WildcardType;
import org.eclipse.jdt.core.util.IClassFileAttribute;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ICodeAttribute;
import org.eclipse.jdt.core.util.IFieldInfo;
import org.eclipse.jdt.core.util.IMethodInfo;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Argument;
import org.eclipse.jdt.internal.compiler.ast.IntersectionCastTypeReference;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.ast.UnionTypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ClassSignature;
import org.eclipse.jdt.internal.compiler.env.EnumConstantSignature;
import org.eclipse.jdt.internal.compiler.env.IBinaryAnnotation;
import org.eclipse.jdt.internal.compiler.env.IDependent;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import org.eclipse.jdt.internal.compiler.parser.ScannerHelper;
import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
import org.eclipse.jdt.internal.core.Annotation;
import org.eclipse.jdt.internal.core.ClassFile;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.core.JavaModelManager;
import org.eclipse.jdt.internal.core.Member;
import org.eclipse.jdt.internal.core.MemberValuePair;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.internal.core.PackageFragmentRoot;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Util {
public interface Comparable {
int compareTo(Comparable c);
}
public interface Comparer {
int compare(Object a, Object b);
}
public static interface BindingsToNodesMap {
public org.eclipse.jdt.internal.compiler.ast.ASTNode get(Binding binding);
}
private static final char ARGUMENTS_DELIMITER = '#';
private static final String EMPTY_ARGUMENT = " ";
private static char[][] JAVA_LIKE_EXTENSIONS;
private static final char[] BOOLEAN = "boolean".toCharArray();
private static final char[] BYTE = "byte".toCharArray();
private static final char[] CHAR = "char".toCharArray();
private static final char[] DOUBLE = "double".toCharArray();
private static final char[] FLOAT = "float".toCharArray();
private static final char[] INT = "int".toCharArray();
private static final char[] LONG = "long".toCharArray();
private static final char[] SHORT = "short".toCharArray();
private static final char[] VOID = "void".toCharArray();
private static final char[] INIT = "<init>".toCharArray();
private static final String TASK_PRIORITIES_PROBLEM = "TASK_PRIORITIES_PB";
private static List fgRepeatedMessages= new ArrayList(5);
private Util() {
}
public static final String[] arrayConcat(String[] first, String second) {
if (second == null)
return first;
if (first == null)
return new String[] {second};
int length = first.length;
if (first.length == 0) {
return new String[] {second};
}
String[] result = new String[length + 1];
System.arraycopy(first, 0, result, 0, length);
result[length] = second;
return result;
}
private static int checkTypeSignature(String sig, int start, int end, boolean allowVoid) {
if (start >= end) return -1;
int i = start;
char c = sig.charAt(i++);
int nestingDepth = 0;
while (c == '[') {
++nestingDepth;
if (i >= end) return -1;
c = sig.charAt(i++);
}
switch (c) {
case 'B':
case 'C':
case 'D':
case 'F':
case 'I':
case 'J':
case 'S':
case 'Z':
break;
case 'V':
if (!allowVoid) return -1;
if (nestingDepth != 0) return -1;
break;
case 'L':
int semicolon = sig.indexOf(';', i);
if (semicolon <= i || semicolon >= end) return -1;
i = semicolon + 1;
break;
default:
return -1;
}
return i;
}
public static int combineHashCodes(int hashCode1, int hashCode2) {
return hashCode1 * 17 + hashCode2;
}
public static int compare(byte[] a, byte[] b) {
if (a == b)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
int len = Math.min(a.length, b.length);
for (int i = 0; i < len; ++i) {
int diff = a[i] - b[i];
if (diff != 0)
return diff;
}
if (a.length > len)
return 1;
if (b.length > len)
return -1;
return 0;
}
public static int compare(char[] str1, char[] str2) {
int len1= str1.length;
int len2= str2.length;
int n= Math.min(len1, len2);
int i= 0;
while (n-- != 0) {
char c1= str1[i];
char c2= str2[i++];
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
public static char[] concatCompoundNameToCharArray(String[] compoundName) {
if (compoundName == null) return null;
int length = compoundName.length;
if (length == 0) return new char[0];
int size = 0;
for (int i=0; i<length; i++) {
size += compoundName[i].length();
}
char[] compoundChars = new char[size+length-1];
int pos = 0;
for (int i=0; i<length; i++) {
String name = compoundName[i];
if (i > 0) compoundChars[pos++] = '.';
int nameLength = name.length();
name.getChars(0, nameLength, compoundChars, pos);
pos += nameLength;
}
return compoundChars;
}
public static String concatenateName(String name1, String name2, char separator) {
StringBuffer buf= new StringBuffer();
if (name1 != null && name1.length() > 0) {
buf.append(name1);
}
if (name2 != null && name2.length() > 0) {
if (buf.length() > 0) {
buf.append(separator);
}
buf.append(name2);
}
return buf.toString();
}
public static final String concatWith(String[] array, char separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0, length = array.length; i < length; i++) {
buffer.append(array[i]);
if (i < length - 1)
buffer.append(separator);
}
return buffer.toString();
}
public static final String concatWith(
String[] array,
String name,
char separator) {
if (array == null || array.length == 0) return name;
if (name == null || name.length() == 0) return concatWith(array, separator);
StringBuffer buffer = new StringBuffer();
for (int i = 0, length = array.length; i < length; i++) {
buffer.append(array[i]);
buffer.append(separator);
}
buffer.append(name);
return buffer.toString();
}
public static String convertTypeSignature(char[] sig, int start, int length) {
return new String(sig, start, length).replace('/', '.');
}
public static String defaultJavaExtension() {
return SuffixConstants.SUFFIX_STRING_java;
}
public final static String editedString(String original, TextEdit edit) {
if (edit == null) {
return original;
}
SimpleDocument document = new SimpleDocument(original);
try {
edit.apply(document, TextEdit.NONE);
return document.get();
} catch (MalformedTreeException | BadLocationException e) {
e.printStackTrace();
}
return original;
}
public final static boolean endsWithIgnoreCase(String str, String end) {
int strLength = str == null ? 0 : str.length();
int endLength = end == null ? 0 : end.length();
if(endLength > strLength)
return false;
for(int i = 1 ; i <= endLength; i++){
if(ScannerHelper.toLowerCase(end.charAt(endLength - i)) != ScannerHelper.toLowerCase(str.charAt(strLength - i)))
return false;
}
return true;
}
public static boolean equalArrays(Object[] a, Object[] b, int len) {
if (a == b) return true;
if (a.length < len || b.length < len) return false;
for (int i = 0; i < len; ++i) {
if (a[i] == null) {
if (b[i] != null) return false;
} else {
if (!a[i].equals(b[i])) return false;
}
}
return true;
}
public static boolean equalArraysOrNull(int[] a, int[] b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
int len = a.length;
if (len != b.length)
return false;
for (int i = 0; i < len; ++i) {
if (a[i] != b[i])
return false;
}
return true;
}
public static boolean equalArraysOrNull(Object[] a, Object[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
for (int i = len-1; i >= 0; i--) {
if (a[i] == null) {
if (b[i] != null) return false;
} else {
if (!a[i].equals(b[i])) return false;
}
}
return true;
}
public static boolean equalArraysOrNullSortFirst(Comparable[] a, Comparable[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
if (len >= 2) {
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
if (!a[i].equals(b[i])) return false;
}
return true;
}
public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) {
if (a == b) return true;
if (a == null || b == null) return false;
int len = a.length;
if (len != b.length) return false;
if (len >= 2) {
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
if (!a[i].equals(b[i])) return false;
}
return true;
}
public static boolean equalOrNull(Object a, Object b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return a.equals(b);
}
public static boolean equalsIgnoreJavaLikeExtension(String fileName, String string) {
int fileNameLength = fileName.length();
int stringLength = string.length();
if (fileNameLength < stringLength) return false;
for (int i = 0; i < stringLength; i ++) {
if (fileName.charAt(i) != string.charAt(i)) {
return false;
}
}
char[][] javaLikeExtensions = getJavaLikeExtensions();
suffixes: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] suffix = javaLikeExtensions[i];
int extensionStart = stringLength+1;
if (extensionStart + suffix.length != fileNameLength) continue;
if (fileName.charAt(stringLength) != '.') continue;
for (int j = extensionStart; j < fileNameLength; j++) {
if (fileName.charAt(j) != suffix[j-extensionStart])
continue suffixes;
}
return true;
}
return false;
}
public static String (String qualifiedName) {
int i = qualifiedName.lastIndexOf('.');
if (i == -1) return qualifiedName;
return qualifiedName.substring(i+1);
}
public static String[] (char[] sig) {
int count = getParameterCount(sig);
String[] result = new String[count];
if (count == 0)
return result;
int i = CharOperation.indexOf('(', sig) + 1;
count = 0;
int len = sig.length;
int start = i;
for (;;) {
if (i == len)
break;
char c = sig[i];
if (c == ')')
break;
if (c == '[') {
++i;
} else
if (c == 'L') {
i = CharOperation.indexOf(';', sig, i + 1) + 1;
Assert.isTrue(i != 0);
result[count++] = convertTypeSignature(sig, start, i - start);
start = i;
} else {
++i;
result[count++] = convertTypeSignature(sig, start, i - start);
start = i;
}
}
return result;
}
public static String (String sig) {
int i = sig.lastIndexOf(')');
Assert.isTrue(i != -1);
return sig.substring(i+1);
}
private static IFile findFirstClassFile(IFolder folder) {
try {
IResource[] members = folder.members();
for (int i = 0, max = members.length; i < max; i++) {
IResource member = members[i];
if (member.getType() == IResource.FOLDER) {
return findFirstClassFile((IFolder)member);
} else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(member.getName())) {
return (IFile) member;
}
}
} catch (CoreException e) {
}
return null;
}
public static String findLineSeparator(char[] text) {
int length = text.length;
if (length > 0) {
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length-1 ? text[i+1] : ' ';
switch (currentChar) {
case '\n': return "\n";
case '\r': return nextChar == '\n' ? "\r\n" : "\r";
}
}
}
return null;
}
public static IClassFileAttribute getAttribute(IClassFileReader classFileReader, char[] attributeName) {
IClassFileAttribute[] attributes = classFileReader.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(ICodeAttribute codeAttribute, char[] attributeName) {
IClassFileAttribute[] attributes = codeAttribute.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(IFieldInfo fieldInfo, char[] attributeName) {
IClassFileAttribute[] attributes = fieldInfo.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
public static IClassFileAttribute getAttribute(IMethodInfo methodInfo, char[] attributeName) {
IClassFileAttribute[] attributes = methodInfo.getAttributes();
for (int i = 0, max = attributes.length; i < max; i++) {
if (CharOperation.equals(attributes[i].getAttributeName(), attributeName)) {
return attributes[i];
}
}
return null;
}
private static IClassFile getClassFile(char[] fileName) {
int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
int pkgEnd = CharOperation.lastIndexOf('/', fileName);
if (pkgEnd == -1)
pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
if (jarSeparator != -1 && pkgEnd < jarSeparator)
pkgEnd = jarSeparator;
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
if (pkg == null) return null;
int start;
return pkg.getClassFile(new String(fileName, start = pkgEnd + 1, fileName.length - start));
}
private static ICompilationUnit getCompilationUnit(char[] fileName, WorkingCopyOwner workingCopyOwner) {
char[] slashSeparatedFileName = CharOperation.replaceOnCopy(fileName, File.separatorChar, '/');
int pkgEnd = CharOperation.lastIndexOf('/', slashSeparatedFileName);
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(slashSeparatedFileName, pkgEnd, -1);
if (pkg != null) {
int start;
ICompilationUnit cu = pkg.getCompilationUnit(new String(slashSeparatedFileName, start = pkgEnd+1, slashSeparatedFileName.length - start));
if (workingCopyOwner != null) {
ICompilationUnit workingCopy = cu.findWorkingCopy(workingCopyOwner);
if (workingCopy != null)
return workingCopy;
}
return cu;
}
IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
IFile file = wsRoot.getFile(new Path(String.valueOf(fileName)));
if (file.exists()) {
return JavaCore.createCompilationUnitFrom(file);
}
return null;
}
public static char[][] getJavaLikeExtensions() {
if (JAVA_LIKE_EXTENSIONS == null) {
IContentType javaContentType = Platform.getContentTypeManager().getContentType(JavaCore.JAVA_SOURCE_CONTENT_TYPE);
HashSet fileExtensions = new HashSet();
IContentType[] contentTypes = Platform.getContentTypeManager().getAllContentTypes();
for (int i = 0, length = contentTypes.length; i < length; i++) {
if (contentTypes[i].isKindOf(javaContentType)) {
String[] fileExtension = contentTypes[i].getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
for (int j = 0, length2 = fileExtension.length; j < length2; j++) {
fileExtensions.add(fileExtension[j]);
}
}
}
int length = fileExtensions.size();
char[][] extensions = new char[length][];
extensions[0] = SuffixConstants.EXTENSION_java.toCharArray();
int index = 1;
Iterator iterator = fileExtensions.iterator();
while (iterator.hasNext()) {
String fileExtension = (String) iterator.next();
if (SuffixConstants.EXTENSION_java.equals(fileExtension))
continue;
extensions[index++] = fileExtension.toCharArray();
}
JAVA_LIKE_EXTENSIONS = extensions;
}
return JAVA_LIKE_EXTENSIONS;
}
public static long getJdkLevel(Object targetLibrary) {
try {
ClassFileReader reader = null;
if (targetLibrary instanceof IFolder) {
IFile classFile = findFirstClassFile((IFolder) targetLibrary);
if (classFile != null)
reader = Util.newClassFileReader(classFile);
} else {
ZipFile jar = null;
try {
IPath path = null;
if (targetLibrary instanceof IResource) {
path = ((IResource)targetLibrary).getFullPath();
} else if (targetLibrary instanceof File){
File f = (File) targetLibrary;
if (!f.isDirectory()) {
path = new Path(((File)targetLibrary).getPath());
}
}
if (path != null) {
if (JavaModelManager.isJrt(path)) {
return ClassFileConstants.JDK9;
} else {
jar = JavaModelManager.getJavaModelManager().getZipFile(path);
for (Enumeration e= jar.entries(); e.hasMoreElements();) {
ZipEntry member= (ZipEntry) e.nextElement();
String entryName= member.getName();
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) {
reader = ClassFileReader.read(jar, entryName);
break;
}
}
}
}
} catch (CoreException e) {
} finally {
JavaModelManager.getJavaModelManager().closeZipFile(jar);
}
}
if (reader != null) {
return reader.getVersion();
}
} catch(CoreException | ClassFormatException | IOException e) {
}
return 0;
}
public static String getNameWithoutJavaLikeExtension(String fileName) {
int index = indexOfJavaLikeExtension(fileName);
if (index == -1)
return fileName;
return fileName.substring(0, index);
}
public static String getLineSeparator(String text, IJavaProject project) {
String lineSeparator = null;
if (text != null && text.length() != 0) {
lineSeparator = findLineSeparator(text.toCharArray());
if (lineSeparator != null)
return lineSeparator;
}
if (Platform.isRunning()) {
IScopeContext[] scopeContext;
if (project != null) {
scopeContext= new IScopeContext[] { new ProjectScope(project.getProject()) };
lineSeparator= Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null)
return lineSeparator;
}
scopeContext= new IScopeContext[] { InstanceScope.INSTANCE };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null)
return lineSeparator;
}
return org.eclipse.jdt.internal.compiler.util.Util.LINE_SEPARATOR;
}
private static String getLineSeparator(char[] text, char[] buffer) {
String lineSeparator = findLineSeparator(buffer);
if (lineSeparator == null) {
lineSeparator = findLineSeparator(text);
if (lineSeparator == null) {
return getLineSeparator((String) null, (IJavaProject) null);
}
}
return lineSeparator;
}
public static IPackageFragment getPackageFragment(char[] fileName, int pkgEnd, int jarSeparator) {
if (jarSeparator != -1) {
String jarMemento = new String(fileName, 0, jarSeparator);
PackageFragmentRoot root = (PackageFragmentRoot) JavaCore.create(jarMemento);
if (pkgEnd == jarSeparator)
return root.getPackageFragment(CharOperation.NO_STRINGS);
char[] pkgName = CharOperation.subarray(fileName, jarSeparator+1, pkgEnd);
char[][] compoundName = CharOperation.splitOn('/', pkgName);
return root.getPackageFragment(CharOperation.toStrings(compoundName));
} else {
Path path = new Path(new String(fileName, 0, pkgEnd));
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IContainer folder = path.segmentCount() == 1 ? workspaceRoot.getProject(path.lastSegment()) : (IContainer) workspaceRoot.getFolder(path);
IJavaElement element = JavaCore.create(folder);
if (element == null) return null;
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
return (IPackageFragment) element;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return ((PackageFragmentRoot) element).getPackageFragment(CharOperation.NO_STRINGS);
case IJavaElement.JAVA_PROJECT:
PackageFragmentRoot root = (PackageFragmentRoot) ((IJavaProject) element).getPackageFragmentRoot(folder);
if (root == null) return null;
return root.getPackageFragment(CharOperation.NO_STRINGS);
}
return null;
}
}
public static int getParameterCount(char[] sig) {
int i = CharOperation.indexOf('(', sig) + 1;
Assert.isTrue(i != 0);
int count = 0;
int len = sig.length;
for (;;) {
if (i == len)
break;
char c = sig[i];
if (c == ')')
break;
if (c == '[') {
++i;
} else
if (c == 'L') {
++count;
i = CharOperation.indexOf(';', sig, i + 1) + 1;
Assert.isTrue(i != 0);
} else {
++count;
++i;
}
}
return count;
}
public static String getProblemArgumentsForMarker(String[] arguments){
StringBuffer args = new StringBuffer(10);
args.append(arguments.length);
args.append(':');
for (int j = 0; j < arguments.length; j++) {
if(j != 0)
args.append(ARGUMENTS_DELIMITER);
if(arguments[j].length() == 0) {
args.append(EMPTY_ARGUMENT);
} else {
encodeArgument(arguments[j], args);
}
}
return args.toString();
}
private static void encodeArgument(String argument, StringBuffer buffer) {
for (int i = 0, max = argument.length(); i < max; i++) {
char charAt = argument.charAt(i);
switch(charAt) {
case ARGUMENTS_DELIMITER :
buffer.append(ARGUMENTS_DELIMITER).append(ARGUMENTS_DELIMITER);
break;
default:
buffer.append(charAt);
}
}
}
public static String[] getProblemArgumentsFromMarker(String argumentsString){
if (argumentsString == null) {
return null;
}
int index = argumentsString.indexOf(':');
if(index == -1)
return null;
int length = argumentsString.length();
int numberOfArg = 0;
try{
numberOfArg = Integer.parseInt(argumentsString.substring(0 , index));
} catch (NumberFormatException e) {
return null;
}
argumentsString = argumentsString.substring(index + 1, length);
return decodeArgumentString(numberOfArg, argumentsString);
}
private static String[] decodeArgumentString(int length, String argumentsString) {
if (length == 0) {
if (argumentsString.length() != 0) {
return null;
}
return CharOperation.NO_STRINGS;
}
String[] result = new String[length];
int count = 0;
StringBuffer buffer = new StringBuffer();
for (int i = 0, max = argumentsString.length(); i < max; i++) {
char current = argumentsString.charAt(i);
switch(current) {
case ARGUMENTS_DELIMITER :
if ((i + 1) == max) {
return null;
}
char next = argumentsString.charAt(i + 1);
if (next == ARGUMENTS_DELIMITER) {
buffer.append(ARGUMENTS_DELIMITER);
i++;
} else {
String currentArgumentContents = String.valueOf(buffer);
if (EMPTY_ARGUMENT.equals(currentArgumentContents)) {
currentArgumentContents = org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING;
}
result[count++] = currentArgumentContents;
if (count > length) {
return null;
}
buffer.delete(0, buffer.length());
}
break;
default :
buffer.append(current);
}
}
String currentArgumentContents = String.valueOf(buffer);
if (EMPTY_ARGUMENT.equals(currentArgumentContents)) {
currentArgumentContents = org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING;
}
result[count++] = currentArgumentContents;
if (count > length) {
return null;
}
buffer.delete(0, buffer.length());
return result;
}
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) {
}
}
}
public static char[] getResourceContentsAsCharArray(IFile file) throws JavaModelException {
String encoding;
try {
encoding = file.getCharset();
} catch(CoreException ce) {
encoding = null;
}
return getResourceContentsAsCharArray(file, encoding);
}
public static char[] getResourceContentsAsCharArray(IFile file, String encoding) throws JavaModelException {
IPath location = file.getLocation();
long length;
if (location == null) {
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 {
length = location.toFile().length();
}
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) {
}
}
}
public static String getSignature(Type type) {
StringBuffer buffer = new StringBuffer();
getFullyQualifiedName(type, buffer);
return Signature.createTypeSignature(buffer.toString(), false);
}
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;
}
private static QualifiedName getSourceAttachmentPropertyName(IPath path) {
return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + path.toOSString());
}
public static void setSourceAttachmentProperty(IPath path, String property) {
if (property == null) {
JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, PackageFragmentRoot.NO_SOURCE_ATTACHMENT);
} else {
JavaModelManager.getJavaModelManager().rootPathToAttachments.put(path, property);
}
try {
ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(getSourceAttachmentPropertyName(path), property);
} catch (CoreException e) {
e.printStackTrace();
}
}
public static String getDeclaringTypeSignature(String key) {
KeyToSignature keyToSignature = new KeyToSignature(key, KeyToSignature.DECLARING_TYPE);
keyToSignature.parse();
return keyToSignature.signature.toString();
}
private static void getFullyQualifiedName(Type type, StringBuffer buffer) {
switch (type.getNodeType()) {
case ASTNode.ARRAY_TYPE:
ArrayType arrayType = (ArrayType) type;
getFullyQualifiedName(arrayType.getElementType(), buffer);
for (int i = 0, length = arrayType.getDimensions(); i < length; i++) {
buffer.append('[');
buffer.append(']');
}
break;
case ASTNode.PARAMETERIZED_TYPE:
ParameterizedType parameterizedType = (ParameterizedType) type;
getFullyQualifiedName(parameterizedType.getType(), buffer);
buffer.append('<');
Iterator iterator = parameterizedType.typeArguments().iterator();
boolean isFirst = true;
while (iterator.hasNext()) {
if (!isFirst)
buffer.append(',');
else
isFirst = false;
Type typeArgument = (Type) iterator.next();
getFullyQualifiedName(typeArgument, buffer);
}
buffer.append('>');
break;
case ASTNode.PRIMITIVE_TYPE:
buffer.append(((PrimitiveType) type).getPrimitiveTypeCode().toString());
break;
case ASTNode.QUALIFIED_TYPE:
buffer.append(((QualifiedType) type).getName().getFullyQualifiedName());
break;
case ASTNode.SIMPLE_TYPE:
buffer.append(((SimpleType) type).getName().getFullyQualifiedName());
break;
case ASTNode.WILDCARD_TYPE:
buffer.append('?');
WildcardType wildcardType = (WildcardType) type;
Type bound = wildcardType.getBound();
if (bound == null) return;
if (wildcardType.isUpperBound()) {
buffer.append(" extends ");
} else {
buffer.append(" super ");
}
getFullyQualifiedName(bound, buffer);
break;
}
}
public static String[] getTrimmedSimpleNames(String name) {
String[] result = Signature.getSimpleNames(name);
for (int i = 0, length = result.length; i < length; i++) {
result[i] = result[i].trim();
}
return result;
}
public static JavaElement getUnresolvedJavaElement(FieldBinding binding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
if (binding.declaringClass == null) return null;
JavaElement unresolvedJavaElement = getUnresolvedJavaElement(binding.declaringClass, workingCopyOwner, bindingsToNodes);
if (unresolvedJavaElement == null || unresolvedJavaElement.getElementType() != IJavaElement.TYPE) {
return null;
}
return (JavaElement) ((IType) unresolvedJavaElement).getField(String.valueOf(binding.name));
}
public static JavaElement getUnresolvedJavaElement(int localSourceStart, int localSourceEnd, JavaElement type) {
try {
if (!(type instanceof IType))
return null;
IInitializer[] initializers = ((IType) type).getInitializers();
for (int i = 0; i < initializers.length; i++) {
IInitializer initializer = initializers[i];
ISourceRange sourceRange = initializer.getSourceRange();
if (sourceRange != null) {
int initializerStart = sourceRange.getOffset();
int initializerEnd = initializerStart + sourceRange.getLength();
if (initializerStart <= localSourceStart && localSourceEnd <= initializerEnd) {
return (JavaElement) initializer;
}
}
}
return null;
} catch (JavaModelException e) {
return null;
}
}
public static JavaElement getUnresolvedJavaElement(MethodBinding methodBinding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
JavaElement unresolvedJavaElement = getUnresolvedJavaElement(methodBinding.declaringClass, workingCopyOwner, bindingsToNodes);
if (unresolvedJavaElement == null || unresolvedJavaElement.getElementType() != IJavaElement.TYPE) {
return null;
}
IType declaringType = (IType) unresolvedJavaElement;
org.eclipse.jdt.internal.compiler.ast.ASTNode node = bindingsToNodes == null ? null : bindingsToNodes.get(methodBinding);
if (node != null && !declaringType.isBinary()) {
if (node instanceof AnnotationMethodDeclaration) {
AnnotationMethodDeclaration typeMemberDeclaration = (AnnotationMethodDeclaration) node;
return (JavaElement) declaringType.getMethod(String.valueOf(typeMemberDeclaration.selector), CharOperation.NO_STRINGS);
} else {
MethodDeclaration methodDeclaration = (MethodDeclaration) node;
Argument[] arguments = methodDeclaration.arguments;
String[] parameterSignatures;
if (arguments != null) {
parameterSignatures = new String[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Argument argument = arguments[i];
TypeReference typeReference = argument.type;
int arrayDim = typeReference.dimensions();
String typeSig =
Signature.createTypeSignature(
CharOperation.concatWith(
typeReference.getTypeName(), '.'), false);
if (arrayDim > 0) {
typeSig = Signature.createArraySignature(typeSig, arrayDim);
}
parameterSignatures[i] = typeSig;
}
} else {
parameterSignatures = CharOperation.NO_STRINGS;
}
return (JavaElement) declaringType.getMethod(String.valueOf(methodDeclaration.selector), parameterSignatures);
}
} else {
org.eclipse.jdt.internal.compiler.lookup.MethodBinding original = methodBinding.original();
String selector = original.isConstructor() ? declaringType.getElementName() : new String(original.selector);
boolean isBinary = declaringType.isBinary();
ReferenceBinding enclosingType = original.declaringClass.enclosingType();
boolean isInnerBinaryTypeConstructor = isBinary && original.isConstructor() && !original.declaringClass.isStatic() && enclosingType != null;
TypeBinding[] parameters = original.parameters;
int length = parameters == null ? 0 : parameters.length;
int declaringIndex = isInnerBinaryTypeConstructor ? 1 : 0;
String[] parameterSignatures = new String[declaringIndex + length];
if (isInnerBinaryTypeConstructor)
parameterSignatures[0] = new String(enclosingType.genericTypeSignature()).replace('/', '.');
for (int i = 0; i < length; i++) {
char[] signature = parameters[i].genericTypeSignature();
if (isBinary) {
signature = CharOperation.replaceOnCopy(signature, '/', '.');
} else {
signature = toUnresolvedTypeSignature(signature);
}
parameterSignatures[declaringIndex + i] = new String(signature);
}
IMethod result = declaringType.getMethod(selector, parameterSignatures);
if (isBinary)
return (JavaElement) result;
if (result.exists())
return (JavaElement) result;
IMethod[] methods = null;
try {
methods = declaringType.getMethods();
} catch (JavaModelException e) {
return null;
}
IMethod[] candidates = Member.findMethods(result, methods);
if (candidates == null || candidates.length == 0)
return null;
return (JavaElement) candidates[0];
}
}
public static JavaElement getUnresolvedJavaElement(TypeBinding typeBinding, WorkingCopyOwner workingCopyOwner, BindingsToNodesMap bindingsToNodes) {
if (typeBinding == null)
return null;
switch (typeBinding.kind()) {
case Binding.ARRAY_TYPE :
typeBinding = ((org.eclipse.jdt.internal.compiler.lookup.ArrayBinding) typeBinding).leafComponentType();
return getUnresolvedJavaElement(typeBinding, workingCopyOwner, bindingsToNodes);
case Binding.BASE_TYPE :
case Binding.WILDCARD_TYPE :
case Binding.INTERSECTION_TYPE:
return null;
default :
if (typeBinding.isCapture())
return null;
}
ReferenceBinding referenceBinding;
if (typeBinding.isParameterizedType() || typeBinding.isRawType())
referenceBinding = (ReferenceBinding) typeBinding.erasure();
else
referenceBinding = (ReferenceBinding) typeBinding;
char[] fileName = referenceBinding.getFileName();
if (referenceBinding.isLocalType() || referenceBinding.isAnonymousType()) {
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fileName)) {
int jarSeparator = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR, fileName);
int pkgEnd = CharOperation.lastIndexOf('/', fileName);
if (pkgEnd == -1)
pkgEnd = CharOperation.lastIndexOf(File.separatorChar, fileName);
if (jarSeparator != -1 && pkgEnd < jarSeparator)
pkgEnd = jarSeparator;
if (pkgEnd == -1)
return null;
IPackageFragment pkg = getPackageFragment(fileName, pkgEnd, jarSeparator);
char[] constantPoolName = referenceBinding.constantPoolName();
if (constantPoolName == null) {
ClassFile classFile = (ClassFile) getClassFile(fileName);
return classFile == null ? null : (JavaElement) classFile.getType();
}
pkgEnd = CharOperation.lastIndexOf('/', constantPoolName);
char[] classFileName = CharOperation.subarray(constantPoolName, pkgEnd+1, constantPoolName.length);
ClassFile classFile = (ClassFile) pkg.getClassFile(new String(classFileName) + SuffixConstants.SUFFIX_STRING_class);
return (JavaElement) classFile.getType();
}
ICompilationUnit cu = getCompilationUnit(fileName, workingCopyOwner);
if (cu == null) return null;
try {
int sourceStart = ((org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding) referenceBinding).sourceStart;
return (JavaElement) cu.getElementAt(sourceStart);
} catch (JavaModelException e) {
return null;
}
} else if (referenceBinding.isTypeVariable()) {
final String typeVariableName = new String(referenceBinding.sourceName());
org.eclipse.jdt.internal.compiler.lookup.Binding declaringElement = ((org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding) referenceBinding).declaringElement;
if (declaringElement instanceof MethodBinding) {
IMethod declaringMethod = (IMethod) getUnresolvedJavaElement((MethodBinding) declaringElement, workingCopyOwner, bindingsToNodes);
return (JavaElement) declaringMethod.getTypeParameter(typeVariableName);
} else {
IType declaringType = (IType) getUnresolvedJavaElement((TypeBinding) declaringElement, workingCopyOwner, bindingsToNodes);
if (declaringType == null)
return null;
return (JavaElement) declaringType.getTypeParameter(typeVariableName);
}
} else {
if (fileName == null) return null;
TypeBinding declaringTypeBinding = typeBinding.enclosingType();
if (declaringTypeBinding == null) {
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(fileName)) {
ClassFile classFile = (ClassFile) getClassFile(fileName);
if (classFile == null) return null;
return (JavaElement) classFile.getType();
}
ICompilationUnit cu = getCompilationUnit(fileName, workingCopyOwner);
if (cu == null) return null;
return (JavaElement) cu.getType(new String(referenceBinding.sourceName()));
} else {
IType declaringType = (IType) getUnresolvedJavaElement(declaringTypeBinding, workingCopyOwner, bindingsToNodes);
if (declaringType == null) return null;
return (JavaElement) declaringType.getType(new String(referenceBinding.sourceName()));
}
}
}
public static int indexOfEnclosingPath(IPath checkedPath, IPath[] paths, int pathCount) {
int bestMatch = -1, bestLength = -1;
for (int i = 0; i < pathCount; i++){
if (paths[i].equals(checkedPath)) continue;
if (paths[i].isPrefixOf(checkedPath)) {
int currentLength = paths[i].segmentCount();
if (currentLength > bestLength) {
bestLength = currentLength;
bestMatch = i;
}
}
}
return bestMatch;
}
public static int indexOfJavaLikeExtension(String fileName) {
int fileNameLength = fileName.length();
char[][] javaLikeExtensions = getJavaLikeExtensions();
extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] extension = javaLikeExtensions[i];
int extensionLength = extension.length;
int extensionStart = fileNameLength - extensionLength;
int dotIndex = extensionStart - 1;
if (dotIndex < 0) continue;
if (fileName.charAt(dotIndex) != '.') continue;
for (int j = 0; j < extensionLength; j++) {
if (fileName.charAt(extensionStart + j) != extension[j])
continue extensions;
}
return dotIndex;
}
return -1;
}
public static int indexOfMatchingPath(IPath checkedPath, IPath[] paths, int pathCount) {
for (int i = 0; i < pathCount; i++){
if (paths[i].equals(checkedPath)) return i;
}
return -1;
}
public static int indexOfNestedPath(IPath checkedPath, IPath[] paths, int pathCount) {
for (int i = 0; i < pathCount; i++){
if (checkedPath.equals(paths[i])) continue;
if (checkedPath.isPrefixOf(paths[i])) return i;
}
return -1;
}
protected static boolean isAttributeSupported(int attribute) {
return (EFS.getLocalFileSystem().attributes() & attribute) != 0;
}
public static boolean isReadOnly(IResource resource) {
if (isReadOnlySupported()) {
ResourceAttributes resourceAttributes = resource.getResourceAttributes();
if (resourceAttributes == null) return false;
return resourceAttributes.isReadOnly();
}
return false;
}
public static boolean isReadOnlySupported() {
return isAttributeSupported(EFS.ATTRIBUTE_READ_ONLY);
}
public static final boolean isExcluded(IJavaElement element) {
int elementType = element.getElementType();
switch (elementType) {
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return false;
case IJavaElement.PACKAGE_FRAGMENT:
PackageFragmentRoot root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
IResource resource = ((PackageFragment) element).resource();
return resource != null && isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars());
case IJavaElement.COMPILATION_UNIT:
root = (PackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
resource = element.getResource();
if (resource == null)
return false;
if (isExcluded(resource, root.fullInclusionPatternChars(), root.fullExclusionPatternChars()))
return true;
return isExcluded(element.getParent());
default:
IJavaElement cu = element.getAncestor(IJavaElement.COMPILATION_UNIT);
return cu != null && isExcluded(cu);
}
}
public final static boolean isExcluded(IPath resourcePath, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean isFolderPath) {
if (inclusionPatterns == null && exclusionPatterns == null) return false;
return org.eclipse.jdt.internal.compiler.util.Util.isExcluded(resourcePath.toString().toCharArray(), inclusionPatterns, exclusionPatterns, isFolderPath);
}
public final static boolean isExcluded(IResource resource, char[][] inclusionPatterns, char[][] exclusionPatterns) {
IPath path = resource.getFullPath();
int resourceType = resource.getType();
return isExcluded(path, inclusionPatterns, exclusionPatterns, resourceType == IResource.FOLDER || resourceType == IResource.PROJECT);
}
public static boolean isValidClassFileName(String name, String sourceLevel, String complianceLevel) {
return JavaConventions.validateClassFileName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
public static boolean isValidCompilationUnitName(String name, String sourceLevel, String complianceLevel) {
return JavaConventions.validateCompilationUnitName(name, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
public static boolean isValidFolderNameForPackage(String folderName, String sourceLevel, String complianceLevel) {
return JavaConventions.validateIdentifier(folderName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR;
}
public static boolean isValidMethodSignature(String sig) {
int len = sig.length();
if (len == 0) return false;
int i = 0;
char c = sig.charAt(i++);
if (c != '(') return false;
if (i >= len) return false;
while (sig.charAt(i) != ')') {
i = checkTypeSignature(sig, i, len, false);
if (i == -1) return false;
if (i >= len) return false;
}
++i;
i = checkTypeSignature(sig, i, len, true);
return i == len;
}
public static boolean isValidTypeSignature(String sig, boolean allowVoid) {
int len = sig.length();
return checkTypeSignature(sig, 0, len, allowVoid) == len;
}
public static String localTypeName(String binaryTypeName, int lastDollar, int end) {
if (lastDollar > 0 && binaryTypeName.charAt(lastDollar-1) == '$')
return binaryTypeName;
int nameStart = lastDollar+1;
while (nameStart < end && Character.isDigit(binaryTypeName.charAt(nameStart)))
nameStart++;
return binaryTypeName.substring(nameStart, end);
}
public static void log(Throwable e, String message) {
Throwable nestedException;
if (e instanceof JavaModelException
&& (nestedException = ((JavaModelException)e).getException()) != null) {
e = nestedException;
}
log(new Status(
IStatus.ERROR,
JavaCore.PLUGIN_ID,
IStatus.ERROR,
message,
e));
}
public static void logRepeatedMessage(String key, Exception e) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
if (fgRepeatedMessages.contains(key)) {
return;
}
fgRepeatedMessages.add(key);
log(e);
}
public static void logRepeatedMessage(String key, int statusErrorID, String message) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
if (fgRepeatedMessages.contains(key)) {
return;
}
fgRepeatedMessages.add(key);
log(statusErrorID, message);
}
public static void log(int statusErrorID, String message) {
log(new Status(
statusErrorID,
JavaCore.PLUGIN_ID,
message));
}
public static void log(IStatus status) {
Plugin plugin = JavaCore.getPlugin();
if (plugin == null) {
System.err.println(status.toString());
} else {
plugin.getLog().log(status);
}
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Messages.internal_error, e));
}
public static ClassFileReader newClassFileReader(IResource resource) throws CoreException, ClassFormatException, IOException {
InputStream in = null;
try {
in = ((IFile) resource).getContents(true);
return ClassFileReader.read(in, resource.getFullPath().toString());
} finally {
if (in != null)
in.close();
}
}
public static char[] normalizeCRs(char[] text, char[] buffer) {
CharArrayBuffer result = new CharArrayBuffer();
int lineStart = 0;
int length = text.length;
if (length == 0) return text;
String lineSeparator = getLineSeparator(text, buffer);
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length-1 ? text[i+1] : ' ';
switch (currentChar) {
case '\n':
int lineLength = i-lineStart;
char[] line = new char[lineLength];
System.arraycopy(text, lineStart, line, 0, lineLength);
result.append(line);
result.append(lineSeparator);
lineStart = i+1;
break;
case '\r':
lineLength = i-lineStart;
if (lineLength >= 0) {
line = new char[lineLength];
System.arraycopy(text, lineStart, line, 0, lineLength);
result.append(line);
result.append(lineSeparator);
if (nextChar == '\n') {
nextChar = ' ';
lineStart = i+2;
} else {
lineStart = i+1;
}
} else {
lineStart = i+1;
}
break;
}
}
char[] lastLine;
if (lineStart > 0) {
int lastLineLength = length-lineStart;
if (lastLineLength > 0) {
lastLine = new char[lastLineLength];
System.arraycopy(text, lineStart, lastLine, 0, lastLineLength);
result.append(lastLine);
}
return result.getContents();
}
return text;
}
public static String normalizeCRs(String text, String buffer) {
return new String(normalizeCRs(text.toCharArray(), buffer.toCharArray()));
}
public static String packageName(IPath pkgPath, String sourceLevel, String complianceLevel) {
StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
String segment = pkgPath.segment(j);
if (!isValidFolderNameForPackage(segment, sourceLevel, complianceLevel)) {
return null;
}
pkgName.append(segment);
if (j < pkgPath.segmentCount() - 1) {
pkgName.append("." );
}
}
return pkgName.toString();
}
public static int prefixLength(char[] s1, char[] s2) {
int len= 0;
int max= Math.min(s1.length, s2.length);
for (int i= 0; i < max && s1[i] == s2[i]; ++i)
++len;
return len;
}
public static int prefixLength(String s1, String s2) {
int len= 0;
int max= Math.min(s1.length(), s2.length());
for (int i= 0; i < max && s1.charAt(i) == s2.charAt(i); ++i)
++len;
return len;
}
private static void quickSort(char[][] list, int left, int right) {
int original_left= left;
int original_right= right;
char[] mid= list[left + (right - left) / 2];
do {
while (compare(list[left], mid) < 0) {
left++;
}
while (compare(mid, list[right]) < 0) {
right--;
}
if (left <= right) {
char[] tmp= list[left];
list[left]= list[right];
list[right]= tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(list, original_left, right);
}
if (left < original_right) {
quickSort(list, left, original_right);
}
}
private static void quickSort(Comparable[] sortedCollection, int left, int right) {
int original_left = left;
int original_right = right;
Comparable mid = sortedCollection[ left + (right - left) / 2];
do {
while (sortedCollection[left].compareTo(mid) < 0) {
left++;
}
while (mid.compareTo(sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
Comparable tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right);
}
}
private static void quickSort(int[] list, int left, int right) {
int original_left= left;
int original_right= right;
int mid= list[left + (right - left) / 2];
do {
while (list[left] < mid) {
left++;
}
while (mid < list[right]) {
right--;
}
if (left <= right) {
int tmp= list[left];
list[left]= list[right];
list[right]= tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(list, original_left, right);
}
if (left < original_right) {
quickSort(list, left, original_right);
}
}
private static void quickSort(Object[] sortedCollection, int left, int right, Comparer comparer) {
int original_left = left;
int original_right = right;
Object mid = sortedCollection[ left + (right - left) / 2];
do {
while (comparer.compare(sortedCollection[left], mid) < 0) {
left++;
}
while (comparer.compare(mid, sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
Object tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right, comparer);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right, comparer);
}
}
private static void quickSort(String[] sortedCollection, int left, int right) {
int original_left = left;
int original_right = right;
String mid = sortedCollection[ left + (right - left) / 2];
do {
while (sortedCollection[left].compareTo(mid) < 0) {
left++;
}
while (mid.compareTo(sortedCollection[right]) < 0) {
right--;
}
if (left <= right) {
String tmp = sortedCollection[left];
sortedCollection[left] = sortedCollection[right];
sortedCollection[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (original_left < right) {
quickSort(sortedCollection, original_left, right);
}
if (left < original_right) {
quickSort(sortedCollection, left, original_right);
}
}
public static String relativePath(IPath fullPath, int skipSegmentCount) {
boolean hasTrailingSeparator = fullPath.hasTrailingSeparator();
String[] segments = fullPath.segments();
int length = 0;
int max = segments.length;
if (max > skipSegmentCount) {
for (int i1 = skipSegmentCount; i1 < max; i1++) {
length += segments[i1].length();
}
length += max - skipSegmentCount - 1;
}
if (hasTrailingSeparator)
length++;
char[] result = new char[length];
int offset = 0;
int len = segments.length - 1;
if (len >= skipSegmentCount) {
for (int i = skipSegmentCount; i < len; i++) {
int size = segments[i].length();
segments[i].getChars(0, size, result, offset);
offset += size;
result[offset++] = '/';
}
int size = segments[len].length();
segments[len].getChars(0, size, result, offset);
offset += size;
}
if (hasTrailingSeparator)
result[offset++] = '/';
return new String(result);
}
public static void resetJavaLikeExtensions() {
JAVA_LIKE_EXTENSIONS = null;
}
public static int scanTypeSignature(char[] string, int start) {
return org.eclipse.jdt.internal.compiler.util.Util.scanTypeSignature(string, start);
}
public static final String[] splitOn(
char divider,
String string,
int start,
int end) {
int length = string == null ? 0 : string.length();
if (length == 0 || start > end)
return CharOperation.NO_STRINGS;
int wordCount = 1;
for (int i = start; i < end; i++)
if (string.charAt(i) == divider)
wordCount++;
String[] split = new String[wordCount];
int last = start, currentWord = 0;
for (int i = start; i < end; i++) {
if (string.charAt(i) == divider) {
split[currentWord++] = string.substring(last, i);
last = i + 1;
}
}
split[currentWord] = string.substring(last, end);
return split;
}
public static void setReadOnly(IResource resource, boolean readOnly) {
if (isReadOnlySupported()) {
ResourceAttributes resourceAttributes = resource.getResourceAttributes();
if (resourceAttributes == null) return;
resourceAttributes.setReadOnly(readOnly);
try {
resource.setResourceAttributes(resourceAttributes);
} catch (CoreException e) {
}
}
}
public static void sort(char[][] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
public static void sort(Comparable[] objects) {
if (objects.length > 1)
quickSort(objects, 0, objects.length - 1);
}
public static void sort(int[] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
public static void sort(Object[] objects, Comparer comparer) {
if (objects.length > 1)
quickSort(objects, 0, objects.length - 1, comparer);
}
public static void sort(String[] strings) {
if (strings.length > 1)
quickSort(strings, 0, strings.length - 1);
}
public static Comparable[] sortCopy(Comparable[] objects) {
int len = objects.length;
Comparable[] copy = new Comparable[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy);
return copy;
}
public static IJavaElement[] sortCopy(IJavaElement[] elements) {
int len = elements.length;
IJavaElement[] copy = new IJavaElement[len];
System.arraycopy(elements, 0, copy, 0, len);
sort(copy, new Comparer() {
@Override
public int compare(Object a, Object b) {
return ((JavaElement) a).toStringWithAncestors().compareTo(((JavaElement) b).toStringWithAncestors());
}
});
return copy;
}
public static Object[] sortCopy(Object[] objects, Comparer comparer) {
int len = objects.length;
Object[] copy = new Object[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy, comparer);
return copy;
}
public static String[] sortCopy(String[] objects) {
int len = objects.length;
String[] copy = new String[len];
System.arraycopy(objects, 0, copy, 0, len);
sort(copy);
return copy;
}
public static boolean startsWithIgnoreCase(String[] compoundName, String[] prefix, boolean partialMatch) {
int prefixLength = prefix.length;
int nameLength = compoundName.length;
if (prefixLength > nameLength) return false;
for (int i = 0; i < prefixLength - 1; i++) {
if (!compoundName[i].equalsIgnoreCase(prefix[i]))
return false;
}
return (partialMatch || prefixLength == nameLength) && compoundName[prefixLength-1].toLowerCase().startsWith(prefix[prefixLength-1].toLowerCase());
}
public static char[][] toCharArrays(String[] a) {
int len = a.length;
if (len == 0) return CharOperation.NO_CHAR_CHAR;
char[][] result = new char[len][];
for (int i = 0; i < len; ++i) {
result[i] = a[i].toCharArray();
}
return result;
}
public static char[][] toCompoundChars(String s) {
int len = s.length();
if (len == 0) {
return CharOperation.NO_CHAR_CHAR;
}
int segCount = 1;
for (int off = s.indexOf('.'); off != -1; off = s.indexOf('.', off + 1)) {
++segCount;
}
char[][] segs = new char[segCount][];
int start = 0;
for (int i = 0; i < segCount; ++i) {
int dot = s.indexOf('.', start);
int end = (dot == -1 ? s.length() : dot);
segs[i] = new char[end - start];
s.getChars(start, end, segs[i], 0);
start = end + 1;
}
return segs;
}
public static File toLocalFile(URI uri, IProgressMonitor monitor) throws CoreException {
IFileStore fileStore = EFS.getStore(uri);
File localFile = fileStore.toLocalFile(EFS.NONE, monitor);
if (localFile ==null)
localFile= fileStore.toLocalFile(EFS.CACHE, monitor);
return localFile;
}
public static String toString(char[][] c) {
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
if (i != 0) sb.append('.');
sb.append(c[i]);
}
return sb.toString();
}
public static String toString(char[][] c, char[] d) {
if (c == null) return new String(d);
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
sb.append(c[i]);
sb.append('.');
}
sb.append(d);
return sb.toString();
}
public static String[] toStrings(char[][] a) {
int len = a.length;
String[] result = new String[len];
for (int i = 0; i < len; ++i) {
result[i] = new String(a[i]);
}
return result;
}
private static char[] toUnresolvedTypeSignature(char[] signature) {
int length = signature.length;
if (length <= 1)
return signature;
StringBuffer buffer = new StringBuffer(length);
toUnresolvedTypeSignature(signature, 0, length, buffer);
int bufferLength = buffer.length();
char[] result = new char[bufferLength];
buffer.getChars(0, bufferLength, result, 0);
return result;
}
private static int toUnresolvedTypeSignature(char[] signature, int start, int length, StringBuffer buffer) {
if (signature[start] == Signature.C_RESOLVED)
buffer.append(Signature.C_UNRESOLVED);
else
buffer.append(signature[start]);
for (int i = start+1; i < length; i++) {
char c = signature[i];
switch (c) {
case '/':
case Signature.C_DOLLAR:
buffer.append(Signature.C_DOT);
break;
case Signature.C_GENERIC_START:
buffer.append(Signature.C_GENERIC_START);
i = toUnresolvedTypeSignature(signature, i+1, length, buffer);
break;
case Signature.C_GENERIC_END:
buffer.append(Signature.C_GENERIC_END);
return i;
default:
buffer.append(c);
break;
}
}
return length;
}
private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
int length = string.length;
if (start >= length - 1) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
if (c != Signature.C_ARRAY) {
throw newUnexpectedCharacterException(string, start, c);
}
int index = start;
c = string[++index];
while(c == Signature.C_ARRAY) {
if (index >= length - 1) {
throw newIllegalArgumentException(string, start);
}
c = string[++index];
}
appendTypeSignature(string, index, buffer, compact);
for(int i = 0, dims = index - start; i < dims; i++) {
buffer.append('[').append(']');
}
}
private static void appendClassTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
char c = string[start];
if (c != Signature.C_RESOLVED) {
return;
}
int p = start + 1;
int checkpoint = buffer.length();
while (true) {
c = string[p];
switch(c) {
case Signature.C_SEMICOLON :
return;
case Signature.C_DOT :
case '/' :
if (compact) {
buffer.setLength(checkpoint);
} else {
buffer.append('.');
}
break;
case Signature.C_DOLLAR :
buffer.append('.');
break;
default :
buffer.append(c);
}
p++;
}
}
static void appendTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) {
char c = string[start];
switch (c) {
case Signature.C_ARRAY :
appendArrayTypeSignature(string, start, buffer, compact);
break;
case Signature.C_RESOLVED :
appendClassTypeSignature(string, start, buffer, compact);
break;
case Signature.C_TYPE_VARIABLE :
int e = org.eclipse.jdt.internal.compiler.util.Util.scanTypeVariableSignature(string, start);
buffer.append(string, start + 1, e - start - 1);
break;
case Signature.C_BOOLEAN :
buffer.append(BOOLEAN);
break;
case Signature.C_BYTE :
buffer.append(BYTE);
break;
case Signature.C_CHAR :
buffer.append(CHAR);
break;
case Signature.C_DOUBLE :
buffer.append(DOUBLE);
break;
case Signature.C_FLOAT :
buffer.append(FLOAT);
break;
case Signature.C_INT :
buffer.append(INT);
break;
case Signature.C_LONG :
buffer.append(LONG);
break;
case Signature.C_SHORT :
buffer.append(SHORT);
break;
case Signature.C_VOID :
buffer.append(VOID);
break;
}
}
public static String toString(char[] declaringClass, char[] methodName, char[] methodSignature, boolean includeReturnType, boolean compact) {
final boolean isConstructor = CharOperation.equals(methodName, INIT);
int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
if (firstParen == -1) {
return "";
}
StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
if (declaringClass != null && declaringClass.length > 0) {
char[] declaringClassSignature = null;
if (declaringClass[0] == Signature.C_ARRAY) {
CharOperation.replace(declaringClass, '/', '.');
declaringClassSignature = Signature.toCharArray(declaringClass);
} else {
CharOperation.replace(declaringClass, '/', '.');
declaringClassSignature = declaringClass;
}
int lastIndexOfSlash = CharOperation.lastIndexOf('.', declaringClassSignature);
if (compact && lastIndexOfSlash != -1) {
buffer.append(declaringClassSignature, lastIndexOfSlash + 1, declaringClassSignature.length - lastIndexOfSlash - 1);
} else {
buffer.append(declaringClassSignature);
}
if (!isConstructor) {
buffer.append('.');
}
}
if (!isConstructor && methodName != null) {
buffer.append(methodName);
}
buffer.append('(');
char[][] pts = Signature.getParameterTypes(methodSignature);
for (int i = 0, max = pts.length; i < max; i++) {
appendTypeSignature(pts[i], 0 , buffer, compact);
if (i != pts.length - 1) {
buffer.append(',');
buffer.append(' ');
}
}
buffer.append(')');
if (!isConstructor) {
buffer.append(" : ");
if (includeReturnType) {
char[] rts = Signature.getReturnType(methodSignature);
appendTypeSignature(rts, 0 , buffer, compact);
}
}
return String.valueOf(buffer);
}
public static String[] typeParameterSignatures(AbstractMethodDeclaration method) {
Argument[] args = method.arguments;
if (args != null) {
int length = args.length;
String[] signatures = new String[length];
for (int i = 0; i < args.length; i++) {
Argument arg = args[i];
signatures[i] = typeSignature(arg.type);
}
return signatures;
}
return CharOperation.NO_STRINGS;
}
public static String typeSignature(TypeReference type) {
String signature = null;
if ((type.bits & org.eclipse.jdt.internal.compiler.ast.ASTNode.IsUnionType) != 0) {
UnionTypeReference unionTypeReference = (UnionTypeReference) type;
TypeReference[] typeReferences = unionTypeReference.typeReferences;
String[] typeSignatures = typeSignatures(typeReferences);
signature = Signature.createIntersectionTypeSignature(typeSignatures);
} else if (type instanceof IntersectionCastTypeReference) {
IntersectionCastTypeReference intersection = (IntersectionCastTypeReference) type;
TypeReference[] typeReferences = intersection.typeReferences;
String[] typeSignatures = typeSignatures(typeReferences);
signature = Signature.createUnionTypeSignature(typeSignatures);
} else {
char[][] compoundName = type.getParameterizedTypeName();
char[] typeName =CharOperation.concatWith(compoundName, '.');
signature = Signature.createTypeSignature(typeName, false);
}
return signature;
}
private static String[] typeSignatures(TypeReference[] types) {
int length = types.length;
String[] typeSignatures = new String[length];
for(int i = 0; i < length; i++) {
char[][] compoundName = types[i].getParameterizedTypeName();
char[] typeName = CharOperation.concatWith(compoundName, '.');
typeSignatures[i] = Signature.createTypeSignature(typeName, false);
}
return typeSignatures;
}
public static void validateMethodSignature(String sig) {
Assert.isTrue(isValidMethodSignature(sig));
}
public static void validateTypeSignature(String sig, boolean allowVoid) {
Assert.isTrue(isValidTypeSignature(sig, allowVoid));
}
public static void verbose(String log) {
verbose(log, System.out);
}
public static synchronized void verbose(String log, PrintStream printStream) {
int start = 0;
do {
int end = log.indexOf('\n', start);
printStream.print(Thread.currentThread());
printStream.print(" ");
printStream.print(log.substring(start, end == -1 ? log.length() : end+1));
start = end+1;
} while (start != 0);
printStream.println();
}
public final static boolean isJavaLikeFileName(String name) {
if (name == null) return false;
return indexOfJavaLikeExtension(name) != -1;
}
public final static boolean isJavaLikeFileName(char[] fileName) {
if (fileName == null) return false;
int fileNameLength = fileName.length;
char[][] javaLikeExtensions = getJavaLikeExtensions();
extensions: for (int i = 0, length = javaLikeExtensions.length; i < length; i++) {
char[] extension = javaLikeExtensions[i];
int extensionLength = extension.length;
int extensionStart = fileNameLength - extensionLength;
if (extensionStart-1 < 0) continue;
if (fileName[extensionStart-1] != '.') continue;
for (int j = 0; j < extensionLength; j++) {
if (fileName[extensionStart + j] != extension[j])
continue extensions;
}
return true;
}
return false;
}
public final static char[][][] getAllTypeArguments(char[][] typeSignatures) {
if (typeSignatures == null) return null;
int length = typeSignatures.length;
char[][][] typeArguments = new char[length][][];
for (int i=0; i<length; i++){
typeArguments[i] = Signature.getTypeArguments(typeSignatures[i]);
}
return typeArguments;
}
public static IAnnotation getAnnotation(JavaElement parent, IBinaryAnnotation binaryAnnotation, String memberValuePairName) {
char[] typeName = org.eclipse.jdt.core.Signature.toCharArray(CharOperation.replaceOnCopy(binaryAnnotation.getTypeName(), '/', '.'));
return new Annotation(parent, new String(typeName), memberValuePairName);
}
public static Object getAnnotationMemberValue(JavaElement parent, MemberValuePair memberValuePair, Object binaryValue) {
if (binaryValue instanceof Constant) {
return getAnnotationMemberValue(memberValuePair, (Constant) binaryValue);
} else if (binaryValue instanceof IBinaryAnnotation) {
memberValuePair.valueKind = IMemberValuePair.K_ANNOTATION;
return getAnnotation(parent, (IBinaryAnnotation) binaryValue, memberValuePair.getMemberName());
} else if (binaryValue instanceof ClassSignature) {
memberValuePair.valueKind = IMemberValuePair.K_CLASS;
char[] className = Signature.toCharArray(CharOperation.replaceOnCopy(((ClassSignature) binaryValue).getTypeName(), '/', '.'));
return new String(className);
} else if (binaryValue instanceof EnumConstantSignature) {
memberValuePair.valueKind = IMemberValuePair.K_QUALIFIED_NAME;
EnumConstantSignature enumConstant = (EnumConstantSignature) binaryValue;
char[] enumName = Signature.toCharArray(CharOperation.replaceOnCopy(enumConstant.getTypeName(), '/', '.'));
char[] qualifiedName = CharOperation.concat(enumName, enumConstant.getEnumConstantName(), '.');
return new String(qualifiedName);
} else if (binaryValue instanceof Object[]) {
memberValuePair.valueKind = -1;
Object[] binaryValues = (Object[]) binaryValue;
int length = binaryValues.length;
Object[] values = new Object[length];
for (int i = 0; i < length; i++) {
int previousValueKind = memberValuePair.valueKind;
Object value = getAnnotationMemberValue(parent, memberValuePair, binaryValues[i]);
if (previousValueKind != -1 && memberValuePair.valueKind != previousValueKind) {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
}
if (value instanceof Annotation) {
Annotation annotation = (Annotation) value;
for (int j = 0; j < i; j++) {
if (annotation.equals(values[j])) {
annotation.occurrenceCount++;
}
}
}
values[i] = value;
}
if (memberValuePair.valueKind == -1)
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return values;
} else {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
public static Object getAnnotationMemberValue(MemberValuePair memberValuePair, Constant constant) {
if (constant == null) {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
switch (constant.typeID()) {
case TypeIds.T_int :
memberValuePair.valueKind = IMemberValuePair.K_INT;
return Integer.valueOf(constant.intValue());
case TypeIds.T_byte :
memberValuePair.valueKind = IMemberValuePair.K_BYTE;
return Byte.valueOf(constant.byteValue());
case TypeIds.T_short :
memberValuePair.valueKind = IMemberValuePair.K_SHORT;
return Short.valueOf(constant.shortValue());
case TypeIds.T_char :
memberValuePair.valueKind = IMemberValuePair.K_CHAR;
return Character.valueOf(constant.charValue());
case TypeIds.T_float :
memberValuePair.valueKind = IMemberValuePair.K_FLOAT;
return new Float(constant.floatValue());
case TypeIds.T_double :
memberValuePair.valueKind = IMemberValuePair.K_DOUBLE;
return new Double(constant.doubleValue());
case TypeIds.T_boolean :
memberValuePair.valueKind = IMemberValuePair.K_BOOLEAN;
return Boolean.valueOf(constant.booleanValue());
case TypeIds.T_long :
memberValuePair.valueKind = IMemberValuePair.K_LONG;
return Long.valueOf(constant.longValue());
case TypeIds.T_JavaLangString :
memberValuePair.valueKind = IMemberValuePair.K_STRING;
return constant.stringValue();
default:
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
public static Object getNegativeAnnotationMemberValue(MemberValuePair memberValuePair, Constant constant) {
if (constant == null) {
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
switch (constant.typeID()) {
case TypeIds.T_int :
memberValuePair.valueKind = IMemberValuePair.K_INT;
return Integer.valueOf(constant.intValue() * -1);
case TypeIds.T_float :
memberValuePair.valueKind = IMemberValuePair.K_FLOAT;
return new Float(constant.floatValue() * -1.0f);
case TypeIds.T_double :
memberValuePair.valueKind = IMemberValuePair.K_DOUBLE;
return new Double(constant.doubleValue() * -1.0);
case TypeIds.T_long :
memberValuePair.valueKind = IMemberValuePair.K_LONG;
return Long.valueOf(constant.longValue() * -1L);
default:
memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
return null;
}
}
public final static char[][] splitTypeLevelsSignature(String typeSignature) {
char[] source = Signature.removeCapture(typeSignature.toCharArray());
CharOperation.replace(source, '$', '.');
char[][] signatures = new char[10][];
int signaturesCount = 0;
int paramOpening = 0;
for (int idx=0, ln = source.length; idx < ln; idx++) {
switch (source[idx]) {
case '>':
paramOpening--;
if (paramOpening == 0) {
if (signaturesCount == signatures.length) {
System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
}
}
break;
case '<':
paramOpening++;
break;
case '.':
if (paramOpening == 0) {
if (signaturesCount == signatures.length) {
System.arraycopy(signatures, 0, signatures = new char[signaturesCount+10][], 0, signaturesCount);
}
signatures[signaturesCount] = new char[idx+1];
System.arraycopy(source, 0, signatures[signaturesCount], 0, idx);
signatures[signaturesCount][idx] = Signature.C_SEMICOLON;
signaturesCount++;
}
break;
case '/':
source[idx] = '.';
break;
}
}
char[][] typeSignatures = new char[signaturesCount+1][];
typeSignatures[0] = source;
for (int i=1, j=signaturesCount-1; i<=signaturesCount; i++, j--){
typeSignatures[i] = signatures[j];
}
return typeSignatures;
}
public static String toAnchor(int startingIndex, char[] methodSignature, String methodName, boolean isVarArgs) {
try {
return new String(toAnchor(startingIndex, methodSignature, methodName.toCharArray(), isVarArgs));
} catch(IllegalArgumentException e) {
return null;
}
}
public static char[] toAnchor(int startingIndex, char[] methodSignature, char[] methodName, boolean isVargArgs) {
int firstParen = CharOperation.indexOf(Signature.C_PARAM_START, methodSignature);
if (firstParen == -1) {
throw new IllegalArgumentException(String.valueOf(methodSignature));
}
StringBuffer buffer = new StringBuffer(methodSignature.length + 10);
if (methodName != null) {
buffer.append(methodName);
}
buffer.append('(');
char[][] pts = Signature.getParameterTypes(methodSignature);
for (int i = startingIndex, max = pts.length; i < max; i++) {
if (i == max - 1) {
appendTypeSignatureForAnchor(pts[i], 0 , buffer, isVargArgs);
} else {
appendTypeSignatureForAnchor(pts[i], 0 , buffer, false);
}
if (i != pts.length - 1) {
buffer.append(',');
buffer.append(' ');
}
}
buffer.append(')');
char[] result = new char[buffer.length()];
buffer.getChars(0, buffer.length(), result, 0);
return result;
}
private static int appendTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
if (start >= string.length) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
if (isVarArgs) {
switch (c) {
case Signature.C_ARRAY :
return appendArrayTypeSignatureForAnchor(string, start, buffer, true);
case Signature.C_RESOLVED :
case Signature.C_TYPE_VARIABLE :
case Signature.C_BOOLEAN :
case Signature.C_BYTE :
case Signature.C_CHAR :
case Signature.C_DOUBLE :
case Signature.C_FLOAT :
case Signature.C_INT :
case Signature.C_LONG :
case Signature.C_SHORT :
case Signature.C_VOID :
case Signature.C_STAR:
case Signature.C_EXTENDS:
case Signature.C_SUPER:
case Signature.C_CAPTURE:
default:
throw newUnexpectedCharacterException(string, start, c);
}
} else {
switch (c) {
case Signature.C_ARRAY :
return appendArrayTypeSignatureForAnchor(string, start, buffer, false);
case Signature.C_RESOLVED :
return appendClassTypeSignatureForAnchor(string, start, buffer);
case Signature.C_TYPE_VARIABLE :
int e = org.eclipse.jdt.internal.compiler.util.Util.scanTypeVariableSignature(string, start);
buffer.append(string, start + 1, e - start - 1);
return e;
case Signature.C_BOOLEAN :
buffer.append(BOOLEAN);
return start;
case Signature.C_BYTE :
buffer.append(BYTE);
return start;
case Signature.C_CHAR :
buffer.append(CHAR);
return start;
case Signature.C_DOUBLE :
buffer.append(DOUBLE);
return start;
case Signature.C_FLOAT :
buffer.append(FLOAT);
return start;
case Signature.C_INT :
buffer.append(INT);
return start;
case Signature.C_LONG :
buffer.append(LONG);
return start;
case Signature.C_SHORT :
buffer.append(SHORT);
return start;
case Signature.C_VOID :
buffer.append(VOID);
return start;
case Signature.C_CAPTURE :
return appendCaptureTypeSignatureForAnchor(string, start, buffer);
case Signature.C_STAR:
case Signature.C_EXTENDS:
case Signature.C_SUPER:
return appendTypeArgumentSignatureForAnchor(string, start, buffer);
default :
throw newIllegalArgumentException(string, start);
}
}
}
private static int appendTypeArgumentSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
if (start >= string.length) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
switch(c) {
case Signature.C_STAR :
return start;
case Signature.C_EXTENDS :
return appendTypeSignatureForAnchor(string, start + 1, buffer, false);
case Signature.C_SUPER :
return appendTypeSignatureForAnchor(string, start + 1, buffer, false);
default :
return appendTypeSignatureForAnchor(string, start, buffer, false);
}
}
private static int appendCaptureTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
if (start >= string.length - 1) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
if (c != Signature.C_CAPTURE) {
throw newUnexpectedCharacterException(string, start, c);
}
return appendTypeArgumentSignatureForAnchor(string, start + 1, buffer);
}
private static int appendArrayTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) {
int length = string.length;
if (start >= length - 1) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
if (c != Signature.C_ARRAY) {
throw newUnexpectedCharacterException(string, start, c);
}
int index = start;
c = string[++index];
while(c == Signature.C_ARRAY) {
if (index >= length - 1) {
throw newIllegalArgumentException(string, start);
}
c = string[++index];
}
int e = appendTypeSignatureForAnchor(string, index, buffer, false);
for(int i = 1, dims = index - start; i < dims; i++) {
buffer.append('[').append(']');
}
if (isVarArgs) {
buffer.append('.').append('.').append('.');
} else {
buffer.append('[').append(']');
}
return e;
}
private static int appendClassTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) {
if (start >= string.length - 2) {
throw newIllegalArgumentException(string, start);
}
char c = string[start];
if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) {
throw newUnexpectedCharacterException(string, start, c);
}
int p = start + 1;
while (true) {
if (p >= string.length) {
throw newIllegalArgumentException(string, start);
}
c = string[p];
switch(c) {
case Signature.C_SEMICOLON :
return p;
case Signature.C_GENERIC_START :
int e = scanGenericEnd(string, p + 1);
p = e;
break;
case Signature.C_DOT :
buffer.append('.');
break;
case '/' :
buffer.append('/');
break;
case Signature.C_DOLLAR :
buffer.append('.');
break;
default :
buffer.append(c);
}
p++;
}
}
private static IllegalArgumentException newIllegalArgumentException(char[] string, int index) {
return new IllegalArgumentException("\"" + String.valueOf(string) + "\" at " + index);
}
private static IllegalArgumentException newUnexpectedCharacterException(char[] string, int start, char unexpected) {
return new IllegalArgumentException("Unexpected '" + unexpected + "' in \"" + String.valueOf(string) + "\" starting at " + start);
}
private static int scanGenericEnd(char[] string, int start) {
if (string[start] == Signature.C_GENERIC_END) {
return start;
}
int length = string.length;
int balance = 1;
start++;
while (start <= length) {
switch(string[start]) {
case Signature.C_GENERIC_END :
balance--;
if (balance == 0) {
return start;
}
break;
case Signature.C_GENERIC_START :
balance++;
break;
}
start++;
}
return start;
}
public static void fixTaskTags(Map defaultOptionsMap) {
Object taskTagsValue = defaultOptionsMap.get(JavaCore.COMPILER_TASK_TAGS);
char[][] taskTags = null;
if (taskTagsValue instanceof String) {
taskTags = CharOperation.splitAndTrimOn(',', ((String) taskTagsValue).toCharArray());
}
Object taskPrioritiesValue = defaultOptionsMap.get(JavaCore.COMPILER_TASK_PRIORITIES);
char[][] taskPriorities = null;
if (taskPrioritiesValue instanceof String) {
taskPriorities = CharOperation.splitAndTrimOn(',', ((String) taskPrioritiesValue).toCharArray());
}
if (taskPriorities == null) {
if (taskTags != null) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags (not null) and task priorities (null)");
defaultOptionsMap.remove(JavaCore.COMPILER_TASK_TAGS);
}
return;
} else if (taskTags == null) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags (null) and task priorities (not null)");
defaultOptionsMap.remove(JavaCore.COMPILER_TASK_PRIORITIES);
return;
}
int taskTagsLength = taskTags.length;
int taskPrioritiesLength = taskPriorities.length;
if (taskTagsLength != taskPrioritiesLength) {
Util.logRepeatedMessage(TASK_PRIORITIES_PROBLEM, IStatus.ERROR, "Inconsistent values for taskTags and task priorities : length is different");
if (taskTagsLength > taskPrioritiesLength) {
System.arraycopy(taskTags, 0, (taskTags = new char[taskPrioritiesLength][]), 0, taskPrioritiesLength);
defaultOptionsMap.put(JavaCore.COMPILER_TASK_TAGS, new String(CharOperation.concatWith(taskTags,',')));
} else {
System.arraycopy(taskPriorities, 0, (taskPriorities = new char[taskTagsLength][]), 0, taskTagsLength);
defaultOptionsMap.put(JavaCore.COMPILER_TASK_PRIORITIES, new String(CharOperation.concatWith(taskPriorities,',')));
}
}
}
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 (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] = 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;
}
}