Exception Fact Sheet for "org-eclipse-jdt-core"

The goal of an Exception Fact Sheet is to reveal the design of exception handling in an application.

--Maxence, Martin

For feedback, please contact Martin

Table of contents

Basic Statistics

Number of Classes 1493
Number of Domain Exception Types (Thrown or Caught) 23
Number of Domain Checked Exception Types 3
Number of Domain Runtime Exception Types 19
Number of Domain Unknown Exception Types 1
nTh = Number of Throw 1426
nTh = Number of Throw in Catch 266
Number of Catch-Rethrow (may not be correct) 93
nC = Number of Catch 1430
nCTh = Number of Catch with Throw 247
Number of Empty Catch (really Empty) 0
Number of Empty Catch (with comments) 423
Number of Empty Catch 423
nM = Number of Methods 18140
nbFunctionWithCatch = Number of Methods with Catch 877 / 18140
nbFunctionWithThrow = Number of Methods with Throw 799 / 18140
nbFunctionWithThrowS = Number of Methods with ThrowS 1172 / 18140
nbFunctionTransmitting = Number of Methods with "Throws" but NO catch, NO throw (only transmitting) 847 / 18140
P1 = nCTh / nC 17.3% (0.173)
P2 = nMC / nM 4.8% (0.048)
P3 = nbFunctionWithThrow / nbFunction 4.4% (0.044)
P4 = nbFunctionTransmitting / nbFunction 4.7% (0.047)
P5 = nbThrowInCatch / nbThrow 18.7% (0.187)
R2 = nCatch / nThrow 1.003
A1 = Number of Caught Exception Types From External Libraries 41
A2 = Number of Reused Exception Types From External Libraries (thrown from application code) 16

W1 is a rough estimation of the richness of the exception model. It does not take into account the inheritance relationships between domain exceptions.

Proportion P1 measures the overall exception flow. According to our experience, it varies from 5% to 70%. Early-catch design generally yields a low P1, libraries that must warn clients about errors (e.g. databases) generally have a high P1.

Proportion P2 measures the dispersion of catch blocks in the application. According to our experience, it varies from 2% to 15%. A small P2 indicates a rather centralized management of errors.

R1 shows how many exceptions types from libraries (incl. JDK) are thrown from application code. For instance, IllegalArgumentException comes from the JDK but is used in many applications.

A1 measures the awareness of the application to library exceptions. A high value of A1 means either that the application is polluted with checked exceptions or that it is able to apply specific recovery depending on the library exception.

Exception Hierachy

Exception Map

Each exception that is used at least once in the project is a dot. A orange dot represents a domain exception that is defined in the application. A blue dot exception is defined in the JDK or in a library. The x-axis represents the number of times an exception is caught, the y-axis the number of times an exception is thrown.

Exceptions With State

State means fields. Number of exceptions with state: 14
ClassFormatException
              package org.eclipse.jdt.core.util;public class ClassFormatException extends Exception {

	public static final int ERROR_MALFORMED_UTF8 = 1;
	public static final int ERROR_TRUNCATED_INPUT = 2;
	public static final int INVALID_CONSTANT_POOL_ENTRY = 3;
	public static final int TOO_MANY_BYTES = 4;
	public static final int INVALID_ARGUMENTS_FOR_INVOKEINTERFACE = 5;
	public static final int INVALID_BYTECODE = 6;

	/**
	 * @since 3.0
	 */
	public static final int INVALID_TAG_CONSTANT = 7;

	/**
	 * @since 3.0
	 */
	public static final int INVALID_MAGIC_NUMBER = 8;

	private static final long serialVersionUID = 6582900558320612988L; // backward compatible

	/**
	 * Constructor for ClassFormatException.
	 * @param errorID the given error ID
	 */
	public ClassFormatException(int errorID) {
		// TODO (olivier) what is the errorID?
	}

	/**
	 * Constructor for ClassFormatException.
	 * @param message the message for the exception
	 */
	public ClassFormatException(String message) {
		super(message);
	}

	/**
	 * Constructor for ClassFormatException.
	 * @param message the message for the exception
	 * @param  cause  the cause of the exception
	 * @since 3.5
	 */
	public ClassFormatException(String message, Throwable cause) {
		super(message, cause);
	}
}
              package org.eclipse.jdt.internal.compiler.classfmt;public class ClassFormatException extends Exception {

	public static final int ErrBadMagic = 1;
	public static final int ErrBadMinorVersion = 2;
	public static final int ErrBadMajorVersion = 3;
	public static final int ErrBadConstantClass = 4;
	public static final int ErrBadConstantString = 5;
	public static final int ErrBadConstantNameAndType = 6;
	public static final int ErrBadConstantFieldRef = 7;
	public static final int ErrBadConstantMethodRef = 8;
	public static final int ErrBadConstantInterfaceMethodRef = 9;
	public static final int ErrBadConstantPoolIndex = 10;
	public static final int ErrBadSuperclassName = 11;
	public static final int ErrInterfaceCannotBeFinal = 12;
	public static final int ErrInterfaceMustBeAbstract = 13;
	public static final int ErrBadModifiers = 14;
	public static final int ErrClassCannotBeAbstractFinal = 15;
	public static final int ErrBadClassname = 16;
	public static final int ErrBadFieldInfo = 17;
	public static final int ErrBadMethodInfo = 17;
	public static final int ErrEmptyConstantPool = 18;
	public static final int ErrMalformedUtf8 = 19;
	public static final int ErrUnknownConstantTag = 20;
	public static final int ErrTruncatedInput = 21;
	public static final int ErrMethodMustBeAbstract = 22;
	public static final int ErrMalformedAttribute = 23;
	public static final int ErrBadInterface = 24;
	public static final int ErrInterfaceMustSubclassObject = 25;
	public static final int ErrIncorrectInterfaceMethods = 26;
	public static final int ErrInvalidMethodName = 27;
	public static final int ErrInvalidMethodSignature = 28;

	private static final long serialVersionUID = 6667458511042774540L; // backward compatible

	private int errorCode;
	private int bufferPosition;
	private RuntimeException nestedException;
	private char[] fileName;

	public ClassFormatException(RuntimeException e, char[] fileName) {
		this.nestedException = e;
		this.fileName = fileName;
	}
	public ClassFormatException(int code) {
		this.errorCode = code;
	}
	public ClassFormatException(int code, int bufPos) {
		this.errorCode = code;
		this.bufferPosition = bufPos;
	}
	/**
	 * @return int
	 */
	public int getErrorCode() {
		return this.errorCode;
	}
	/**
	 * @return int
	 */
	public int getBufferPosition() {
		return this.bufferPosition;
	}
	/**
	 * Returns the underlying <code>Throwable</code> that caused the failure.
	 *
	 * @return the wrappered <code>Throwable</code>, or <code>null</code>
	 *         if the direct case of the failure was at the Java model layer
	 */
	public Throwable getException() {
		return this.nestedException;
	}
	public void printStackTrace() {
		printStackTrace(System.err);
	}
	/**
	 * Prints this exception's stack trace to the given print stream.
	 *
	 * @param output
	 *            the print stream
	 * @since 3.0
	 */
	public void printStackTrace(PrintStream output) {
		synchronized (output) {
			super.printStackTrace(output);
			Throwable throwable = getException();
			if (throwable != null) {
				if (this.fileName != null) {
					output.print("Caused in "); //$NON-NLS-1$
					output.print(this.fileName);
					output.print(" by: "); //$NON-NLS-1$
				} else {
					output.print("Caused by: "); //$NON-NLS-1$
				}
				throwable.printStackTrace(output);
			}
		}
	}
	/**
	 * Prints this exception's stack trace to the given print writer.
	 *
	 * @param output
	 *            the print writer
	 * @since 3.0
	 */
	public void printStackTrace(PrintWriter output) {
		synchronized (output) {
			super.printStackTrace(output);
			Throwable throwable = getException();
			if (throwable != null) {
				if (this.fileName != null) {
					output.print("Caused in "); //$NON-NLS-1$
					output.print(this.fileName);
					output.print(" by: "); //$NON-NLS-1$
				} else {
					output.print("Caused by: "); //$NON-NLS-1$
				}
				throwable.printStackTrace(output);
			}
		}
	}
}
            
AbortCompilationUnit
              package org.eclipse.jdt.internal.compiler.problem;public class AbortCompilationUnit extends AbortCompilation {

	private static final long serialVersionUID = -4253893529982226734L; // backward compatible

	public String encoding;

public AbortCompilationUnit(CompilationResult compilationResult, CategorizedProblem problem) {
	super(compilationResult, problem);
}

/**
 * Used to surface encoding issues when reading sources
 */
public AbortCompilationUnit(CompilationResult compilationResult, IOException exception, String encoding) {
	super(compilationResult, exception);
	this.encoding = encoding;
}
}
            
WrappedCoreException
              package org.eclipse.jdt.internal.core.search.matching;public static class WrappedCoreException extends RuntimeException {
	private static final long serialVersionUID = 8354329870126121212L; // backward compatible
	public CoreException coreException;
	public WrappedCoreException(CoreException coreException) {
		this.coreException = coreException;
	}
}
            
AbortIncrementalBuildException
              package org.eclipse.jdt.internal.core.builder;public class AbortIncrementalBuildException extends RuntimeException {

protected String qualifiedTypeName;
private static final long serialVersionUID = -8874662133883858502L; // backward compatible

public AbortIncrementalBuildException(String qualifiedTypeName) {
	this.qualifiedTypeName = qualifiedTypeName;
}
}
            
MissingSourceFileException
              package org.eclipse.jdt.internal.core.builder;public class MissingSourceFileException extends RuntimeException {

	protected String missingSourceFile;
	private static final long serialVersionUID = -1416609004971115719L; // backward compatible

public MissingSourceFileException(String missingSourceFile) {
	this.missingSourceFile = missingSourceFile;
}
}
            
ImageBuilderInternalException
              package org.eclipse.jdt.internal.core.builder;public class ImageBuilderInternalException extends RuntimeException {

private static final long serialVersionUID = 28252254530437336L; // backward compatible
protected CoreException coreException;

public ImageBuilderInternalException(CoreException e) {
	this.coreException = e;
}

public CoreException getThrowable() {
	return this.coreException;
}

public void printStackTrace() {
	if (this.coreException != null) {
		System.err.println(this);
		System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$
		this.coreException.printStackTrace();
	} else {
		super.printStackTrace();
	}
}
}
            
AbortFormatting
              package org.eclipse.jdt.internal.formatter;public class AbortFormatting extends RuntimeException {

	Throwable nestedException;
	private static final long serialVersionUID = -5796507276311428526L; // backward compatible

	public AbortFormatting(String message) {
		super(message);
	}
	public AbortFormatting(Throwable nestedException) {
		super(nestedException.getMessage());
		this.nestedException = nestedException;
	}
}
            
AlignmentException
              package org.eclipse.jdt.internal.formatter.align;public class AlignmentException extends RuntimeException {

	public static final int LINE_TOO_LONG = 1;
	public static final int ALIGN_TOO_SMALL = 2;
	private static final long serialVersionUID = -3324134986466253314L; // backward compatible

	int reason;
	int value;
	public int relativeDepth;

	public AlignmentException(int reason, int relativeDepth) {
		this(reason, 0, relativeDepth);
	}

	public AlignmentException(int reason, int value, int relativeDepth) {
		this.reason = reason;
		this.value = value;
		this.relativeDepth = relativeDepth;
	}

	public String toString(){
		StringBuffer buffer = new StringBuffer(10);
		switch(this.reason){
			case LINE_TOO_LONG :
				buffer.append("LINE_TOO_LONG");	//$NON-NLS-1$
				break;
			case ALIGN_TOO_SMALL :
				buffer.append("ALIGN_TOO_SMALL");	//$NON-NLS-1$
				break;
		}
		buffer
			.append("<relativeDepth: ")	//$NON-NLS-1$
			.append(this.relativeDepth)
			.append(">\n");	//$NON-NLS-1$
		return buffer.toString();
	}
}
            
CompletionNodeFound
              package org.eclipse.jdt.internal.codeassist.complete;public class CompletionNodeFound extends RuntimeException {

	public ASTNode astNode;
	public Binding qualifiedBinding;
	public Scope scope;
	public boolean insideTypeAnnotation = false;

	private static final long serialVersionUID = 6981437684184091462L; // backward compatible

public CompletionNodeFound() {
	this(null, null, null, false); // we found a problem in the completion node
}
public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope) {
	this(astNode, qualifiedBinding, scope, false);
}
public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope, boolean insideTypeAnnotation) {
	this.astNode = astNode;
	this.qualifiedBinding = qualifiedBinding;
	this.scope = scope;
	this.insideTypeAnnotation = insideTypeAnnotation;
}
public CompletionNodeFound(ASTNode astNode, Scope scope) {
	this(astNode, null, scope, false);
}
public CompletionNodeFound(ASTNode astNode, Scope scope, boolean insideTypeAnnotation) {
	this(astNode, null, scope, insideTypeAnnotation);
}
}
            
InvalidCursorLocation
              package org.eclipse.jdt.internal.codeassist.complete;public class InvalidCursorLocation extends RuntimeException {

	public String irritant;

	/* Possible irritants */
	public static final String NO_COMPLETION_INSIDE_UNICODE = "No Completion Inside Unicode"; //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_COMMENT = "No Completion Inside Comment";      //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_STRING = "No Completion Inside String";        //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_NUMBER = "No Completion Inside Number";        //$NON-NLS-1$

	private static final long serialVersionUID = -3443160725735779590L; // backward compatible

public InvalidCursorLocation(String irritant){
	this.irritant = irritant;
}
}
            
SelectionNodeFound
              package org.eclipse.jdt.internal.codeassist.select;public class SelectionNodeFound extends RuntimeException {

	public Binding binding;
	public boolean isDeclaration;
	private static final long serialVersionUID = -7335444736618092295L; // backward compatible

public SelectionNodeFound() {
	this(null, false); // we found a problem in the selection node
}
public SelectionNodeFound(Binding binding) {
	this(binding, false);
}
public SelectionNodeFound(Binding binding, boolean isDeclaration) {
	this.binding = binding;
	this.isDeclaration = isDeclaration;
}
}
            
AbortCompilation
              package org.eclipse.jdt.internal.compiler.problem;public class AbortCompilation extends RuntimeException {

	public CompilationResult compilationResult;
	public Throwable exception;
	public CategorizedProblem problem;

	/* special fields used to abort silently (e.g. when canceling build process) */
	public boolean isSilent;
	public RuntimeException silentException;

	private static final long serialVersionUID = -2047226595083244852L; // backward compatible

	public AbortCompilation() {
		// empty
	}

	public AbortCompilation(CompilationResult compilationResult, CategorizedProblem problem) {
		this();
		this.compilationResult = compilationResult;
		this.problem = problem;
	}

	public AbortCompilation(CompilationResult compilationResult, Throwable exception) {
		this();
		this.compilationResult = compilationResult;
		this.exception = exception;
	}

	public AbortCompilation(boolean isSilent, RuntimeException silentException) {
		this();
		this.isSilent = isSilent;
		this.silentException = silentException;
	}
	public String getMessage() {
		String message = super.getMessage();
		StringBuffer buffer = new StringBuffer(message == null ? Util.EMPTY_STRING : message);
		if (this.problem != null) {
			buffer.append(this.problem);
		} else if (this.exception != null) {
			message = this.exception.getMessage();
			buffer.append(message == null ? Util.EMPTY_STRING : message);
		} else if (this.silentException != null) {
			message = this.silentException.getMessage();
			buffer.append(message == null ? Util.EMPTY_STRING : message);
		}
		return String.valueOf(buffer);
	}
	public void updateContext(InvocationSite invocationSite, CompilationResult unitResult) {
		if (this.problem == null) return;
		if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
		this.problem.setSourceStart(invocationSite.sourceStart());
		this.problem.setSourceEnd(invocationSite.sourceEnd());
		int[] lineEnds = unitResult.getLineSeparatorPositions();
		this.problem.setSourceLineNumber(Util.getLineNumber(invocationSite.sourceStart(), lineEnds, 0, lineEnds.length-1));
		this.compilationResult = unitResult;
	}

	public void updateContext(ASTNode astNode, CompilationResult unitResult) {
		if (this.problem == null) return;
		if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
		this.problem.setSourceStart(astNode.sourceStart());
		this.problem.setSourceEnd(astNode.sourceEnd());
		int[] lineEnds = unitResult.getLineSeparatorPositions();
		this.problem.setSourceLineNumber(Util.getLineNumber(astNode.sourceStart(), lineEnds, 0, lineEnds.length-1));
		this.compilationResult = unitResult;
	}

	public String getKey() {
		StringBuffer buffer = new StringBuffer();
		if (this.problem != null) {
			buffer.append(this.problem);
		}
		return String.valueOf(buffer);
	}
}
            
SourceTypeCollisionException
              package org.eclipse.jdt.internal.compiler.lookup;public class SourceTypeCollisionException extends RuntimeException {
	private static final long serialVersionUID = 4798247636899127380L;

	public ICompilationUnit[] newAnnotationProcessorUnits;
}
            
JavaModelException
              package org.eclipse.jdt.core;public class JavaModelException extends CoreException {

	private static final long serialVersionUID = -760398656505871287L; // backward compatible

	CoreException nestedCoreException;
/**
 * Creates a Java model exception that wrappers the given <code>Throwable</code>.
 * The exception contains a Java-specific status object with severity
 * <code>IStatus.ERROR</code> and the given status code.
 *
 * @param e the <code>Throwable</code>
 * @param code one of the Java-specific status codes declared in
 *   <code>IJavaModelStatusConstants</code>
 * @see IJavaModelStatusConstants
 * @see org.eclipse.core.runtime.IStatus#ERROR
 */
public JavaModelException(Throwable e, int code) {
	this(new JavaModelStatus(code, e));
}
/**
 * Creates a Java model exception for the given <code>CoreException</code>.
 * Equivalent to
 * <code>JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION</code>.
 *
 * @param exception the <code>CoreException</code>
 */
public JavaModelException(CoreException exception) {
	super(exception.getStatus());
	this.nestedCoreException = exception;
}
/**
 * Creates a Java model exception for the given Java-specific status object.
 *
 * @param status the Java-specific status object
 */
public JavaModelException(IJavaModelStatus status) {
	super(status);
}
/**
 * Returns the underlying <code>Throwable</code> that caused the failure.
 *
 * @return the wrappered <code>Throwable</code>, or <code>null</code> if the
 *   direct case of the failure was at the Java model layer
 */
public Throwable getException() {
	if (this.nestedCoreException == null) {
		return getStatus().getException();
	} else {
		return this.nestedCoreException;
	}
}
/**
 * Returns the Java model status object for this exception.
 * Equivalent to <code>(IJavaModelStatus) getStatus()</code>.
 *
 * @return a status object
 */
public IJavaModelStatus getJavaModelStatus() {
	IStatus status = getStatus();
	if (status instanceof IJavaModelStatus) {
		return (IJavaModelStatus)status;
	} else {
		// A regular IStatus is created only in the case of a CoreException.
		// See bug 13492 Should handle JavaModelExceptions that contains CoreException more gracefully
		return new JavaModelStatus(this.nestedCoreException);
	}
}
/**
 * Returns whether this exception indicates that a Java model element does not
 * exist. Such exceptions have a status with a code of
 * <code>IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code> or
 * <code>IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH</code>.
 * This is a convenience method.
 *
 * @return <code>true</code> if this exception indicates that a Java model
 *   element does not exist
 * @see IJavaModelStatus#isDoesNotExist()
 * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
 * @see IJavaModelStatusConstants#ELEMENT_NOT_ON_CLASSPATH
 */
public boolean isDoesNotExist() {
	IJavaModelStatus javaModelStatus = getJavaModelStatus();
	return javaModelStatus != null && javaModelStatus.isDoesNotExist();
}

/**
 * Prints this exception's stack trace to the given print stream.
 *
 * @param output the print stream
 * @since 3.0
 */
public void printStackTrace(PrintStream output) {
	synchronized(output) {
		super.printStackTrace(output);
		Throwable throwable = getException();
		if (throwable != null) {
			output.print("Caused by: "); //$NON-NLS-1$
			throwable.printStackTrace(output);
		}
	}
}

/**
 * Prints this exception's stack trace to the given print writer.
 *
 * @param output the print writer
 * @since 3.0
 */
public void printStackTrace(PrintWriter output) {
	synchronized(output) {
		super.printStackTrace(output);
		Throwable throwable = getException();
		if (throwable != null) {
			output.print("Caused by: "); //$NON-NLS-1$
			throwable.printStackTrace(output);
		}
	}
}
/*
 * Returns a printable representation of this exception suitable for debugging
 * purposes only.
 */
public String toString() {
	StringBuffer buffer= new StringBuffer();
	buffer.append("Java Model Exception: "); //$NON-NLS-1$
	if (getException() != null) {
		if (getException() instanceof CoreException) {
			CoreException c= (CoreException)getException();
			buffer.append("Core Exception [code "); //$NON-NLS-1$
			buffer.append(c.getStatus().getCode());
			buffer.append("] "); //$NON-NLS-1$
			buffer.append(c.getStatus().getMessage());
		} else {
			buffer.append(getException().toString());
		}
	} else {
		buffer.append(getStatus().toString());
	}
	return buffer.toString();
}
}
            

Thrown Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be thrown, thrown from within a catch, or declared in the signature of a method (usually for checked exceptions). Hovering over a number triggers showing code snippets from the application code.

Type Exception Thrown Thrown
from Catch
Declared
- Unknown 147
              
//in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
throw e;

              
//in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
throw new InstallException()

              
//in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
throw (JavaModelException) e;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw (JavaModelException) e;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw binaryType.newNotPresentException();

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e.coreException;

              
//in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e.coreException;

              
//in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw e;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw oom;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
//in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
//in search/org/eclipse/jdt/core/search/SearchEngine.java
throw (JavaModelException) e;

              
//in search/org/eclipse/jdt/core/search/SearchEngine.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/ClassFile.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/ClassFile.java
throw (JavaModelException)e;

              
//in model/org/eclipse/jdt/internal/core/ClassFile.java
throw (JavaModelException)e;

              
//in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw (Error) exception;

              
//in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw (OperationCanceledException) exception;

              
//in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException)ce;

              
//in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException)ce;

              
//in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/Openable.java
throw newJavaModelException(status);

              
//in model/org/eclipse/jdt/internal/core/Openable.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/Openable.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/CompilationUnit.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw ((JavaProject)JavaCore.create(project)).newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw internalException(e);

              
//in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw internalException(e);

              
//in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw internalException(e);

              
//in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw internalException(e);

              
//in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
throw internalException(e);

              
//in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw jme;

              
//in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/Buffer.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JavaElement.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/PackageFragment.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
throw (JavaModelException)e;

              
//in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
throw (JavaModelException)e;

              
//in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/SourceRefElement.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/SourceRefElement.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/JavaProject.java
throw elementFinder.exception;

              
//in model/org/eclipse/jdt/internal/core/JavaProject.java
throw newNotPresentException();

              
//in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
//in model/org/eclipse/jdt/internal/core/BatchOperation.java
throw (JavaModelException)ce;

              
//in model/org/eclipse/jdt/internal/core/BatchOperation.java
throw (JavaModelException) e;

              
//in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
throw (JavaModelException)e;

              
//in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
//in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
//in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
//in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw ex;

              
//in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
//in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
//in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
//in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw e;

              
//in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
throw e;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
//in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
throw (Error) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
throw (RuntimeException) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (Error) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (RuntimeException) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (Error) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (RuntimeException) this.caughtException;

              
//in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
throw exception;

              
//in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
throw abort;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw abortException.silentException;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
throw e;

              
//in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
throw e;

              
//in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
throw runtimeException;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
//in dom/org/eclipse/jdt/core/dom/ASTConverter.java
throw e;

            
- -
- Builder 20
              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw binaryType.newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/ClassFile.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/Openable.java
throw newJavaModelException(status);

              
// in model/org/eclipse/jdt/internal/core/Openable.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw ((JavaProject)JavaCore.create(project)).newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw internalException(e);

              
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw internalException(e);

              
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw internalException(e);

              
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw internalException(e);

              
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
throw internalException(e);

              
// in model/org/eclipse/jdt/internal/core/JarPackageFragment.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/JavaElement.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
throw newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
throw newNotPresentException();

            
- -
- Variable 127
              
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
throw e;

              
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
throw (JavaModelException) e;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw (JavaModelException) e;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e.coreException;

              
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
throw e.coreException;

              
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw e;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw oom;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
throw ioe;

              
// in search/org/eclipse/jdt/core/search/SearchEngine.java
throw (JavaModelException) e;

              
// in search/org/eclipse/jdt/core/search/SearchEngine.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/ClassFile.java
throw (JavaModelException)e;

              
// in model/org/eclipse/jdt/internal/core/ClassFile.java
throw (JavaModelException)e;

              
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw (Error) exception;

              
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
throw (OperationCanceledException) exception;

              
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException)ce;

              
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException)ce;

              
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/Openable.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw ((JavaProject)JavaCore.create(project)).newNotPresentException();

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw jme;

              
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/Buffer.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
throw (JavaModelException)e;

              
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
throw (JavaModelException)e;

              
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
throw elementFinder.exception;

              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
throw e;

              
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
throw (JavaModelException)ce;

              
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
throw (JavaModelException) e;

              
// in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
throw (JavaModelException)e;

              
// in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
// in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
// in model/org/eclipse/jdt/core/JavaCore.java
throw e;

              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw ex;

              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw alignmentException;

              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
throw e;

              
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
throw e;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
throw WRONG_ARGUMENT;

              
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
throw (Error) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
throw (RuntimeException) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (Error) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (RuntimeException) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (Error) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
throw (RuntimeException) this.caughtException;

              
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
throw exception;

              
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
throw abort;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw abortException.silentException;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
throw e;

              
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
throw e;

              
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
throw runtimeException;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
throw e;

              
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
throw e;

            
- -
(Lib) IllegalArgumentException 529
              
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void setLog(String logFileName) { final Date date = new Date(); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.getDefault()); try { int index = logFileName.lastIndexOf('.'); if (index != -1) { if (logFileName.substring(index).toLowerCase().equals(".xml")) { //$NON-NLS-1$ this.log = new GenericXMLWriter(new OutputStreamWriter(new FileOutputStream(logFileName, false), Util.UTF_8), Util.LINE_SEPARATOR, true); this.tagBits |= Logger.XML; // insert time stamp as comment this.log.println("<!-- " + dateFormat.format(date) + " -->");//$NON-NLS-1$//$NON-NLS-2$ this.log.println(Logger.XML_DTD_DECLARATION); this.parameters.put(Logger.COMPILER_NAME, this.main.bind("compiler.name")); //$NON-NLS-1$ this.parameters.put(Logger.COMPILER_VERSION, this.main.bind("compiler.version")); //$NON-NLS-1$ this.parameters.put(Logger.COMPILER_COPYRIGHT, this.main.bind("compiler.copyright")); //$NON-NLS-1$ printTag(Logger.COMPILER, this.parameters, true, false); } else { this.log = new PrintWriter(new FileOutputStream(logFileName, false)); this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$ } } else { this.log = new PrintWriter(new FileOutputStream(logFileName, false)); this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$ } } catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void addNewEntry(ArrayList paths, String currentClasspathName, ArrayList currentRuleSpecs, String customEncoding, String destPath, boolean isSourceOnly, boolean rejectDestinationPathOnJars) { int rulesSpecsSize = currentRuleSpecs.size(); AccessRuleSet accessRuleSet = null; if (rulesSpecsSize != 0) { AccessRule[] accessRules = new AccessRule[currentRuleSpecs.size()]; boolean rulesOK = true; Iterator i = currentRuleSpecs.iterator(); int j = 0; while (i.hasNext()) { String ruleSpec = (String) i.next(); char key = ruleSpec.charAt(0); String pattern = ruleSpec.substring(1); if (pattern.length() > 0) { switch (key) { case '+': accessRules[j++] = new AccessRule(pattern .toCharArray(), 0); break; case '~': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.DiscouragedReference); break; case '-': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.ForbiddenReference); break; case '?': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.ForbiddenReference, true/*keep looking for accessible type*/); break; default: rulesOK = false; } } else { rulesOK = false; } } if (rulesOK) { accessRuleSet = new AccessRuleSet(accessRules, AccessRestriction.COMMAND_LINE, currentClasspathName); } else { if (currentClasspathName.length() != 0) { // we go on anyway addPendingErrors(this.bind("configure.incorrectClasspath", currentClasspathName));//$NON-NLS-1$ } return; } } if (NONE.equals(destPath)) { destPath = NONE; // keep == comparison valid } if (rejectDestinationPathOnJars && destPath != null && Util.isPotentialZipArchive(currentClasspathName)) { throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntryFile", //$NON-NLS-1$ currentClasspathName)); } FileSystem.Classpath currentClasspath = FileSystem.getClasspath( currentClasspathName, customEncoding, isSourceOnly, accessRuleSet, destPath); if (currentClasspath != null) { paths.add(currentClasspath); } else if (currentClasspathName.length() != 0) { // we go on anyway addPendingErrors(this.bind("configure.incorrectClasspath", currentClasspathName));//$NON-NLS-1$ } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void configure(String[] argv) { if ((argv == null) || (argv.length == 0)) { printUsage(); return; } final int INSIDE_CLASSPATH_start = 1; final int INSIDE_DESTINATION_PATH = 3; final int INSIDE_TARGET = 4; final int INSIDE_LOG = 5; final int INSIDE_REPETITION = 6; final int INSIDE_SOURCE = 7; final int INSIDE_DEFAULT_ENCODING = 8; final int INSIDE_BOOTCLASSPATH_start = 9; final int INSIDE_MAX_PROBLEMS = 11; final int INSIDE_EXT_DIRS = 12; final int INSIDE_SOURCE_PATH_start = 13; final int INSIDE_ENDORSED_DIRS = 15; final int INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH = 16; final int INSIDE_PROCESSOR_PATH_start = 17; final int INSIDE_PROCESSOR_start = 18; final int INSIDE_S_start = 19; final int INSIDE_CLASS_NAMES = 20; final int INSIDE_WARNINGS_PROPERTIES = 21; final int DEFAULT = 0; ArrayList bootclasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); String sourcepathClasspathArg = null; ArrayList sourcepathClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); ArrayList classpaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); ArrayList extdirsClasspaths = null; ArrayList endorsedDirClasspaths = null; int index = -1; int filesCount = 0; int classCount = 0; int argCount = argv.length; int mode = DEFAULT; this.maxRepetition = 0; boolean printUsageRequired = false; String usageSection = null; boolean printVersionRequired = false; boolean didSpecifyDeprecation = false; boolean didSpecifyCompliance = false; boolean didSpecifyDisabledAnnotationProcessing = false; String customEncoding = null; String customDestinationPath = null; String currentSourceDirectory = null; String currentArg = Util.EMPTY_STRING; Set specifiedEncodings = null; // expand the command line if necessary boolean needExpansion = false; loop: for (int i = 0; i < argCount; i++) { if (argv[i].startsWith("@")) { //$NON-NLS-1$ needExpansion = true; break loop; } } String[] newCommandLineArgs = null; if (needExpansion) { newCommandLineArgs = new String[argCount]; index = 0; for (int i = 0; i < argCount; i++) { String[] newArgs = null; String arg = argv[i].trim(); if (arg.startsWith("@")) { //$NON-NLS-1$ try { LineNumberReader reader = new LineNumberReader(new StringReader(new String(Util.getFileCharContent(new File(arg.substring(1)), null)))); StringBuffer buffer = new StringBuffer(); String line; while((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { //$NON-NLS-1$ buffer.append(line).append(" "); //$NON-NLS-1$ } } newArgs = tokenize(buffer.toString()); } catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ } } if (newArgs != null) { int newCommandLineArgsLength = newCommandLineArgs.length; int newArgsLength = newArgs.length; System.arraycopy(newCommandLineArgs, 0, (newCommandLineArgs = new String[newCommandLineArgsLength + newArgsLength - 1]), 0, index); System.arraycopy(newArgs, 0, newCommandLineArgs, index, newArgsLength); index += newArgsLength; } else { newCommandLineArgs[index++] = arg; } } index = -1; } else { newCommandLineArgs = argv; for (int i = 0; i < argCount; i++) { newCommandLineArgs[i] = newCommandLineArgs[i].trim(); } } argCount = newCommandLineArgs.length; this.expandedCommandLine = newCommandLineArgs; while (++index < argCount) { if (customEncoding != null) { throw new IllegalArgumentException( this.bind("configure.unexpectedCustomEncoding", currentArg, customEncoding)); //$NON-NLS-1$ } currentArg = newCommandLineArgs[index]; switch(mode) { case DEFAULT : if (currentArg.startsWith("[")) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } if (currentArg.endsWith("]")) { //$NON-NLS-1$ // look for encoding specification int encodingStart = currentArg.indexOf('[') + 1; if (encodingStart <= 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", currentArg)); //$NON-NLS-1$ } int encodingEnd = currentArg.length() - 1; if (encodingStart >= 1) { if (encodingStart < encodingEnd) { customEncoding = currentArg.substring(encodingStart, encodingEnd); try { // ensure encoding is supported new InputStreamReader(new ByteArrayInputStream(new byte[0]), customEncoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ } } currentArg = currentArg.substring(0, encodingStart - 1); } } if (currentArg.endsWith(SuffixConstants.SUFFIX_STRING_java)) { if (this.filenames == null) { this.filenames = new String[argCount - index]; this.encodings = new String[argCount - index]; this.destinationPaths = new String[argCount - index]; } else if (filesCount == this.filenames.length) { int length = this.filenames.length; System.arraycopy( this.filenames, 0, (this.filenames = new String[length + argCount - index]), 0, length); System.arraycopy( this.encodings, 0, (this.encodings = new String[length + argCount - index]), 0, length); System.arraycopy( this.destinationPaths, 0, (this.destinationPaths = new String[length + argCount - index]), 0, length); } this.filenames[filesCount] = currentArg; this.encodings[filesCount++] = customEncoding; // destination path cannot be specified upon an individual file customEncoding = null; mode = DEFAULT; continue; } if (currentArg.equals("-log")) { //$NON-NLS-1$ if (this.log != null) throw new IllegalArgumentException( this.bind("configure.duplicateLog", currentArg)); //$NON-NLS-1$ mode = INSIDE_LOG; continue; } if (currentArg.equals("-repeat")) { //$NON-NLS-1$ if (this.maxRepetition > 0) throw new IllegalArgumentException( this.bind("configure.duplicateRepeat", currentArg)); //$NON-NLS-1$ mode = INSIDE_REPETITION; continue; } if (currentArg.equals("-maxProblems")) { //$NON-NLS-1$ if (this.maxProblems > 0) throw new IllegalArgumentException( this.bind("configure.duplicateMaxProblems", currentArg)); //$NON-NLS-1$ mode = INSIDE_MAX_PROBLEMS; continue; } if (currentArg.equals("-source")) { //$NON-NLS-1$ mode = INSIDE_SOURCE; continue; } if (currentArg.equals("-encoding")) { //$NON-NLS-1$ mode = INSIDE_DEFAULT_ENCODING; continue; } if (currentArg.equals("-1.3")) { //$NON-NLS-1$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg));//$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_3); mode = DEFAULT; continue; } if (currentArg.equals("-1.4")) { //$NON-NLS-1$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); mode = DEFAULT; continue; } if (currentArg.equals("-1.5") || currentArg.equals("-5") || currentArg.equals("-5.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); mode = DEFAULT; continue; } if (currentArg.equals("-1.6") || currentArg.equals("-6") || currentArg.equals("-6.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6); mode = DEFAULT; continue; } if (currentArg.equals("-1.7") || currentArg.equals("-7") || currentArg.equals("-7.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7); mode = DEFAULT; continue; } if (currentArg.equals("-d")) { //$NON-NLS-1$ if (this.destinationPath != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateOutputPath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_DESTINATION_PATH; continue; } if (currentArg.equals("-classpath") //$NON-NLS-1$ || currentArg.equals("-cp")) { //$NON-NLS-1$ mode = INSIDE_CLASSPATH_start; continue; } if (currentArg.equals("-bootclasspath")) {//$NON-NLS-1$ if (bootclasspaths.size() > 0) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateBootClasspath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_BOOTCLASSPATH_start; continue; } if (currentArg.equals("-sourcepath")) {//$NON-NLS-1$ if (sourcepathClasspathArg != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateSourcepath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_SOURCE_PATH_start; continue; } if (currentArg.equals("-extdirs")) {//$NON-NLS-1$ if (extdirsClasspaths != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateExtDirs", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_EXT_DIRS; continue; } if (currentArg.equals("-endorseddirs")) { //$NON-NLS-1$ if (endorsedDirClasspaths != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateEndorsedDirs", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_ENDORSED_DIRS; continue; } if (currentArg.equals("-progress")) { //$NON-NLS-1$ mode = DEFAULT; this.showProgress = true; continue; } if (currentArg.startsWith("-proceedOnError")) { //$NON-NLS-1$ mode = DEFAULT; int length = currentArg.length(); if (length > 15) { if (currentArg.equals("-proceedOnError:Fatal")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_FatalOptionalError, CompilerOptions.ENABLED); } else { throw new IllegalArgumentException( this.bind("configure.invalidWarningConfiguration", currentArg)); //$NON-NLS-1$ } } else { this.options.put(CompilerOptions.OPTION_FatalOptionalError, CompilerOptions.DISABLED); } this.proceedOnError = true; continue; } if (currentArg.equals("-time")) { //$NON-NLS-1$ mode = DEFAULT; this.timing = TIMING_ENABLED; continue; } if (currentArg.equals("-time:detail")) { //$NON-NLS-1$ mode = DEFAULT; this.timing = TIMING_ENABLED|TIMING_DETAILED; continue; } if (currentArg.equals("-version") //$NON-NLS-1$ || currentArg.equals("-v")) { //$NON-NLS-1$ this.logger.logVersion(true); this.proceed = false; return; } if (currentArg.equals("-showversion")) { //$NON-NLS-1$ printVersionRequired = true; mode = DEFAULT; continue; } if ("-deprecation".equals(currentArg)) { //$NON-NLS-1$ didSpecifyDeprecation = true; this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); mode = DEFAULT; continue; } if (currentArg.equals("-help") || currentArg.equals("-?")) { //$NON-NLS-1$ //$NON-NLS-2$ printUsageRequired = true; mode = DEFAULT; continue; } if (currentArg.equals("-help:warn") || //$NON-NLS-1$ currentArg.equals("-?:warn")) { //$NON-NLS-1$ printUsageRequired = true; usageSection = "misc.usage.warn"; //$NON-NLS-1$ continue; } if (currentArg.equals("-noExit")) { //$NON-NLS-1$ this.systemExitWhenFinished = false; mode = DEFAULT; continue; } if (currentArg.equals("-verbose")) { //$NON-NLS-1$ this.verbose = true; mode = DEFAULT; continue; } if (currentArg.equals("-referenceInfo")) { //$NON-NLS-1$ this.produceRefInfo = true; mode = DEFAULT; continue; } if (currentArg.equals("-inlineJSR")) { //$NON-NLS-1$ mode = DEFAULT; this.options.put( CompilerOptions.OPTION_InlineJsr, CompilerOptions.ENABLED); continue; } if (currentArg.startsWith("-g")) { //$NON-NLS-1$ mode = DEFAULT; String debugOption = currentArg; int length = currentArg.length(); if (length == 2) { this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); continue; } if (length > 3) { this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE); if (length == 7 && debugOption.equals("-g:" + NONE)) //$NON-NLS-1$ continue; StringTokenizer tokenizer = new StringTokenizer(debugOption.substring(3, debugOption.length()), ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.equals("vars")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } else if (token.equals("lines")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } else if (token.equals("source")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } else { throw new IllegalArgumentException( this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$ } } continue; } throw new IllegalArgumentException( this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$ } if (currentArg.startsWith("-nowarn")) { //$NON-NLS-1$ disableWarnings(); mode = DEFAULT; continue; } if (currentArg.startsWith("-warn")) { //$NON-NLS-1$ mode = DEFAULT; String warningOption = currentArg; int length = currentArg.length(); if (length == 10 && warningOption.equals("-warn:" + NONE)) { //$NON-NLS-1$ disableWarnings(); continue; } if (length <= 6) { throw new IllegalArgumentException( this.bind("configure.invalidWarningConfiguration", warningOption)); //$NON-NLS-1$ } int warnTokenStart; boolean isEnabling, allowPlusOrMinus; switch (warningOption.charAt(6)) { case '+' : warnTokenStart = 7; isEnabling = true; allowPlusOrMinus = true; break; case '-' : warnTokenStart = 7; isEnabling = false; // specified warnings are disabled allowPlusOrMinus = true; break; default: disableWarnings(); warnTokenStart = 6; isEnabling = true; allowPlusOrMinus = false; } StringTokenizer tokenizer = new StringTokenizer(warningOption.substring(warnTokenStart, warningOption.length()), ","); //$NON-NLS-1$ int tokenCounter = 0; if (didSpecifyDeprecation) { // deprecation could have also been set through -deprecation option this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); } while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); tokenCounter++; switch(token.charAt(0)) { case '+' : if (allowPlusOrMinus) { isEnabling = true; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$ } break; case '-' : if (allowPlusOrMinus) { isEnabling = false; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$ } } handleWarningToken(token, isEnabling); } if (tokenCounter == 0) { throw new IllegalArgumentException( this.bind("configure.invalidWarningOption", currentArg)); //$NON-NLS-1$ } continue; } if (currentArg.startsWith("-err")) { //$NON-NLS-1$ mode = DEFAULT; String errorOption = currentArg; int length = currentArg.length(); if (length <= 5) { throw new IllegalArgumentException( this.bind("configure.invalidErrorConfiguration", errorOption)); //$NON-NLS-1$ } int errorTokenStart; boolean isEnabling, allowPlusOrMinus; switch (errorOption.charAt(5)) { case '+' : errorTokenStart = 6; isEnabling = true; allowPlusOrMinus = true; break; case '-' : errorTokenStart = 6; isEnabling = false; // specified errors are disabled allowPlusOrMinus = true; break; default: disableErrors(); errorTokenStart = 5; isEnabling = true; allowPlusOrMinus = false; } StringTokenizer tokenizer = new StringTokenizer(errorOption.substring(errorTokenStart, errorOption.length()), ","); //$NON-NLS-1$ int tokenCounter = 0; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); tokenCounter++; switch(token.charAt(0)) { case '+' : if (allowPlusOrMinus) { isEnabling = true; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$ } break; case '-' : if (allowPlusOrMinus) { isEnabling = false; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$ } break; } handleErrorToken(token, isEnabling); } if (tokenCounter == 0) { throw new IllegalArgumentException( this.bind("configure.invalidErrorOption", currentArg)); //$NON-NLS-1$ } continue; } if (currentArg.equals("-target")) { //$NON-NLS-1$ mode = INSIDE_TARGET; continue; } if (currentArg.equals("-preserveAllLocals")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); mode = DEFAULT; continue; } if (currentArg.equals("-enableJavadoc")) {//$NON-NLS-1$ mode = DEFAULT; this.enableJavadocOn = true; continue; } if (currentArg.equals("-Xemacs")) { //$NON-NLS-1$ mode = DEFAULT; this.logger.setEmacs(); continue; } // annotation processing if (currentArg.startsWith("-A")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-processorpath")) { //$NON-NLS-1$ mode = INSIDE_PROCESSOR_PATH_start; continue; } if (currentArg.equals("-processor")) { //$NON-NLS-1$ mode = INSIDE_PROCESSOR_start; continue; } if (currentArg.equals("-proc:only")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_GenerateClassFiles, CompilerOptions.DISABLED); mode = DEFAULT; continue; } if (currentArg.equals("-proc:none")) { //$NON-NLS-1$ didSpecifyDisabledAnnotationProcessing = true; this.options.put( CompilerOptions.OPTION_Process_Annotations, CompilerOptions.DISABLED); mode = DEFAULT; continue; } if (currentArg.equals("-s")) { //$NON-NLS-1$ mode = INSIDE_S_start; continue; } if (currentArg.equals("-XprintProcessorInfo") //$NON-NLS-1$ || currentArg.equals("-XprintRounds")) { //$NON-NLS-1$ mode = DEFAULT; continue; } // tolerated javac options - quietly filtered out if (currentArg.startsWith("-X")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.startsWith("-J")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-O")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-classNames")) { //$NON-NLS-1$ mode = INSIDE_CLASS_NAMES; continue; } if (currentArg.equals("-properties")) { //$NON-NLS-1$ mode = INSIDE_WARNINGS_PROPERTIES; continue; } break; case INSIDE_TARGET : if (this.didSpecifyTarget) { throw new IllegalArgumentException( this.bind("configure.duplicateTarget", currentArg));//$NON-NLS-1$ } this.didSpecifyTarget = true; if (currentArg.equals("1.1")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1); } else if (currentArg.equals("1.2")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } else if (currentArg.equals("1.3")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3); } else if (currentArg.equals("1.4")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } else if (currentArg.equals("jsr14")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_JSR14); } else if (currentArg.equals("cldc1.1")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_CLDC1_1); this.options.put(CompilerOptions.OPTION_InlineJsr, CompilerOptions.ENABLED); }else { throw new IllegalArgumentException(this.bind("configure.targetJDK", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_LOG : this.log = currentArg; mode = DEFAULT; continue; case INSIDE_REPETITION : try { this.maxRepetition = Integer.parseInt(currentArg); if (this.maxRepetition <= 0) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ } } catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_MAX_PROBLEMS : try { this.maxProblems = Integer.parseInt(currentArg); if (this.maxProblems <= 0) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ } this.options.put(CompilerOptions.OPTION_MaxProblemPerUnit, currentArg); } catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_SOURCE : if (this.didSpecifySource) { throw new IllegalArgumentException( this.bind("configure.duplicateSource", currentArg));//$NON-NLS-1$ } this.didSpecifySource = true; if (currentArg.equals("1.3")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); } else if (currentArg.equals("1.4")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6); } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7); } else { throw new IllegalArgumentException(this.bind("configure.source", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_DEFAULT_ENCODING : if (specifiedEncodings != null) { // check already defined encoding if (!specifiedEncodings.contains(currentArg)) { if (specifiedEncodings.size() > 1) { this.logger.logWarning( this.bind("configure.differentencodings", //$NON-NLS-1$ currentArg, getAllEncodings(specifiedEncodings))); } else { this.logger.logWarning( this.bind("configure.differentencoding", //$NON-NLS-1$ currentArg, getAllEncodings(specifiedEncodings))); } } } else { specifiedEncodings = new HashSet(); } try { // ensure encoding is supported new InputStreamReader(new ByteArrayInputStream(new byte[0]), currentArg); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ } specifiedEncodings.add(currentArg); this.options.put(CompilerOptions.OPTION_Encoding, currentArg); mode = DEFAULT; continue; case INSIDE_DESTINATION_PATH : setDestinationPath(currentArg.equals(NONE) ? NONE : currentArg); mode = DEFAULT; continue; case INSIDE_CLASSPATH_start: mode = DEFAULT; index += processPaths(newCommandLineArgs, index, currentArg, classpaths); continue; case INSIDE_BOOTCLASSPATH_start: mode = DEFAULT; index += processPaths(newCommandLineArgs, index, currentArg, bootclasspaths); continue; case INSIDE_SOURCE_PATH_start: mode = DEFAULT; String[] sourcePaths = new String[1]; index += processPaths(newCommandLineArgs, index, currentArg, sourcePaths); sourcepathClasspathArg = sourcePaths[0]; continue; case INSIDE_EXT_DIRS: if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$ "-extdir")); //$NON-NLS-1$ } StringTokenizer tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false); extdirsClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); while (tokenizer.hasMoreTokens()) extdirsClasspaths.add(tokenizer.nextToken()); mode = DEFAULT; continue; case INSIDE_ENDORSED_DIRS: if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$ "-endorseddirs")); //$NON-NLS-1$ } tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false); endorsedDirClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); while (tokenizer.hasMoreTokens()) endorsedDirClasspaths.add(tokenizer.nextToken()); mode = DEFAULT; continue; case INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH: if (currentArg.endsWith("]")) { //$NON-NLS-1$ customDestinationPath = currentArg.substring(0, currentArg.length() - 1); } else { throw new IllegalArgumentException( this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$ "[-d " + currentArg)); //$NON-NLS-1$ } break; case INSIDE_PROCESSOR_PATH_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_PROCESSOR_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_S_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_CLASS_NAMES : tokenizer = new StringTokenizer(currentArg, ","); //$NON-NLS-1$ if (this.classNames == null) { this.classNames = new String[DEFAULT_SIZE_CLASSPATH]; } while (tokenizer.hasMoreTokens()) { if (this.classNames.length == classCount) { // resize System.arraycopy( this.classNames, 0, (this.classNames = new String[classCount * 2]), 0, classCount); } this.classNames[classCount++] = tokenizer.nextToken(); } mode = DEFAULT; continue; case INSIDE_WARNINGS_PROPERTIES : initializeWarnings(currentArg); mode = DEFAULT; continue; } // default is input directory, if no custom destination path exists if (customDestinationPath == null) { if (File.separatorChar != '/') { currentArg = currentArg.replace('/', File.separatorChar); } if (currentArg.endsWith("[-d")) { //$NON-NLS-1$ currentSourceDirectory = currentArg.substring(0, currentArg.length() - 3); mode = INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH; continue; } currentSourceDirectory = currentArg; } File dir = new File(currentSourceDirectory); if (!dir.isDirectory()) { throw new IllegalArgumentException( this.bind("configure.unrecognizedOption", currentSourceDirectory)); //$NON-NLS-1$ } String[] result = FileFinder.find(dir, SuffixConstants.SUFFIX_STRING_JAVA); if (NONE.equals(customDestinationPath)) { customDestinationPath = NONE; // ensure == comparison } if (this.filenames != null) { // some source files were specified explicitly int length = result.length; System.arraycopy( this.filenames, 0, (this.filenames = new String[length + filesCount]), 0, filesCount); System.arraycopy( this.encodings, 0, (this.encodings = new String[length + filesCount]), 0, filesCount); System.arraycopy( this.destinationPaths, 0, (this.destinationPaths = new String[length + filesCount]), 0, filesCount); System.arraycopy(result, 0, this.filenames, filesCount, length); for (int i = 0; i < length; i++) { this.encodings[filesCount + i] = customEncoding; this.destinationPaths[filesCount + i] = customDestinationPath; } filesCount += length; customEncoding = null; customDestinationPath = null; currentSourceDirectory = null; } else { this.filenames = result; filesCount = this.filenames.length; this.encodings = new String[filesCount]; this.destinationPaths = new String[filesCount]; for (int i = 0; i < filesCount; i++) { this.encodings[i] = customEncoding; this.destinationPaths[i] = customDestinationPath; } customEncoding = null; customDestinationPath = null; currentSourceDirectory = null; } mode = DEFAULT; continue; } // set DocCommentSupport, with appropriate side effects on defaults if // javadoc is not enabled if (this.enableJavadocOn) { this.options.put( CompilerOptions.OPTION_DocCommentSupport, CompilerOptions.ENABLED); } else if (this.warnJavadocOn || this.warnAllJavadocOn) { this.options.put( CompilerOptions.OPTION_DocCommentSupport, CompilerOptions.ENABLED); // override defaults: references that are embedded in javadoc are ignored // from the perspective of parameters and thrown exceptions usage this.options.put( CompilerOptions.OPTION_ReportUnusedParameterIncludeDocCommentReference, CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportUnusedDeclaredThrownExceptionIncludeDocCommentReference, CompilerOptions.DISABLED); } // configure warnings for javadoc contents if (this.warnJavadocOn) { this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTags, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTagsDeprecatedRef, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTagsNotVisibleRef, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportMissingJavadocTagsVisibility, CompilerOptions.PRIVATE); } if (printUsageRequired || (filesCount == 0 && classCount == 0)) { if (usageSection == null) { printUsage(); // default } else { printUsage(usageSection); } this.proceed = false; return; } if (this.log != null) { this.logger.setLog(this.log); } else { this.showProgress = false; } this.logger.logVersion(printVersionRequired); validateOptions(didSpecifyCompliance); // Enable annotation processing by default in batch mode when compliance is at least 1.6 // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=185768 if (!didSpecifyDisabledAnnotationProcessing && CompilerOptions.versionToJdkLevel(this.options.get(CompilerOptions.OPTION_Compliance)) >= ClassFileConstants.JDK1_6) { this.options.put(CompilerOptions.OPTION_Process_Annotations, CompilerOptions.ENABLED); } this.logger.logCommandLineArguments(newCommandLineArgs); this.logger.logOptions(this.options); if (this.maxRepetition == 0) { this.maxRepetition = 1; } if (this.maxRepetition >= 3 && (this.timing & TIMING_ENABLED) != 0) { this.compilerStats = new CompilerStats[this.maxRepetition]; } if (filesCount != 0) { System.arraycopy( this.filenames, 0, (this.filenames = new String[filesCount]), 0, filesCount); } if (classCount != 0) { System.arraycopy( this.classNames, 0, (this.classNames = new String[classCount]), 0, classCount); } setPaths(bootclasspaths, sourcepathClasspathArg, sourcepathClasspaths, classpaths, extdirsClasspaths, endorsedDirClasspaths, customEncoding); if (specifiedEncodings != null && specifiedEncodings.size() > 1) { this.logger.logWarning(this.bind("configure.multipleencodings", //$NON-NLS-1$ (String) this.options.get(CompilerOptions.OPTION_Encoding), getAllEncodings(specifiedEncodings))); } if (this.pendingErrors != null) { for (Iterator iterator = this.pendingErrors.iterator(); iterator.hasNext(); ) { String message = (String) iterator.next(); this.logger.logPendingError(message); } this.pendingErrors = null; } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private void initializeWarnings(String propertiesFile) { File file = new File(propertiesFile); if (!file.exists()) { throw new IllegalArgumentException(this.bind("configure.missingwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ } BufferedInputStream stream = null; Properties properties = null; try { stream = new BufferedInputStream(new FileInputStream(propertiesFile)); properties = new Properties(); properties.load(stream); } catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ } finally { if (stream != null) { try { stream.close(); } catch(IOException e) { // ignore } } } for (Iterator iterator = properties.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); final String key = (String) entry.getKey(); if (key.startsWith("org.eclipse.jdt.core.compiler.problem")) { //$NON-NLS-1$ this.options.put(key, entry.getValue()); } } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public CompilationUnit[] getCompilationUnits() { int fileCount = this.filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = (String) this.options.get(CompilerOptions.OPTION_Encoding); if (Util.EMPTY_STRING.equals(defaultEncoding)) defaultEncoding = null; for (int i = 0; i < fileCount; i++) { char[] charName = this.filenames[i].toCharArray(); if (knownFileNames.get(charName) != null) throw new IllegalArgumentException(this.bind("unit.more", this.filenames[i])); //$NON-NLS-1$ knownFileNames.put(charName, charName); File file = new File(this.filenames[i]); if (!file.exists()) throw new IllegalArgumentException(this.bind("unit.missing", this.filenames[i])); //$NON-NLS-1$ String encoding = this.encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, this.filenames[i], encoding, this.destinationPaths[i]); } return units; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private void handleErrorOrWarningToken(String token, boolean isEnabling, int severity) { if (token.length() == 0) return; switch(token.charAt(0)) { case 'a' : if (token.equals("allDeprecation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeprecation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("allJavadoc")) { //$NON-NLS-1$ this.warnAllJavadocOn = this.warnJavadocOn = isEnabling; setSeverity(CompilerOptions.OPTION_ReportInvalidJavadoc, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocTags, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocComments, severity, isEnabling); return; } else if (token.equals("assertIdentifier")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAssertIdentifier, severity, isEnabling); return; } else if (token.equals("allDeadCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeadCode, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("allOver-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingOverrideAnnotation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportMissingOverrideAnnotationForInterfaceMethodImplementation, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("all-static-method")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMethodCanBePotentiallyStatic, severity, isEnabling); return; } break; case 'b' : if (token.equals("boxing")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAutoboxing, severity, isEnabling); return; } break; case 'c' : if (token.equals("constructorName")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodWithConstructorName, severity, isEnabling); return; } else if (token.equals("conditionAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportPossibleAccidentalBooleanAssignment, severity, isEnabling); return; } else if (token.equals("compareIdentical")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportComparingIdentical, severity, isEnabling); return; } else if (token.equals("charConcat") /*|| token.equals("noImplicitStringConversion")/*backward compatible*/) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoImplicitStringConversion, severity, isEnabling); return; } break; case 'd' : if (token.equals("deprecation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeprecation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED); return; } else if (token.equals("dep-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingDeprecatedAnnotation, severity, isEnabling); return; } else if (token.equals("discouraged")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDiscouragedReference, severity, isEnabling); return; } else if (token.equals("deadCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeadCode, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, CompilerOptions.DISABLED); return; } break; case 'e' : if (token.equals("enumSwitch") //$NON-NLS-1$ || token.equals("incomplete-switch")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportIncompleteEnumSwitch, severity, isEnabling); return; } else if (token.equals("emptyBlock")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUndocumentedEmptyBlock, severity, isEnabling); return; } else if (token.equals("enumIdentifier")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportEnumIdentifier, severity, isEnabling); return; } break; case 'f' : if (token.equals("fieldHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFieldHiding, severity, isEnabling); return; } else if (token.equals("finalBound")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFinalParameterBound, severity, isEnabling); return; } else if (token.equals("finally")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFinallyBlockNotCompletingNormally, severity, isEnabling); return; } else if (token.equals("forbidden")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportForbiddenReference, severity, isEnabling); return; } else if (token.equals("fallthrough")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFallthroughCase, severity, isEnabling); return; } break; case 'h' : if (token.equals("hiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportHiddenCatchBlock, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportLocalVariableHiding, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportFieldHiding, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportTypeParameterHiding, severity, isEnabling); return; } else if (token.equals("hashCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingHashCodeMethod, severity, isEnabling); return; } break; case 'i' : if (token.equals("indirectStatic")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportIndirectStaticAccess, severity, isEnabling); return; } else if (token.equals("intfNonInherited") || token.equals("interfaceNonInherited")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportIncompatibleNonInheritedInterfaceMethod, severity, isEnabling); return; } else if (token.equals("intfAnnotation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAnnotationSuperInterface, severity, isEnabling); return; } else if (token.equals("intfRedundant") /*|| token.equals("redundantSuperinterface")*/) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling); return; } else if (token.equals("includeAssertNull")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_IncludeNullInfoFromAsserts, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } break; case 'j' : if (token.equals("javadoc")) {//$NON-NLS-1$ this.warnJavadocOn = isEnabling; setSeverity(CompilerOptions.OPTION_ReportInvalidJavadoc, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocTags, severity, isEnabling); return; } break; case 'l' : if (token.equals("localHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportLocalVariableHiding, severity, isEnabling); return; } break; case 'm' : if (token.equals("maskedCatchBlock") || token.equals("maskedCatchBlocks")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportHiddenCatchBlock, severity, isEnabling); return; } break; case 'n' : if (token.equals("nls")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, severity, isEnabling); return; } else if (token.equals("noEffectAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoEffectAssignment, severity, isEnabling); return; } else if (/*token.equals("charConcat") ||*/ token.equals("noImplicitStringConversion")/*backward compatible*/) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoImplicitStringConversion, severity, isEnabling); return; } else if (token.equals("null")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNullReference, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportPotentialNullReference, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, severity, isEnabling); return; } else if (token.equals("nullDereference")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNullReference, severity, isEnabling); if (!isEnabling) { setSeverity(CompilerOptions.OPTION_ReportPotentialNullReference, ProblemSeverities.Ignore, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, ProblemSeverities.Ignore, isEnabling); } return; } break; case 'o' : if (token.equals("over-sync") /*|| token.equals("syncOverride")*/) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSynchronizedOnInheritedMethod, severity, isEnabling); return; } else if (token.equals("over-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingOverrideAnnotation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportMissingOverrideAnnotationForInterfaceMethodImplementation, CompilerOptions.DISABLED); return; } break; case 'p' : if (token.equals("pkgDefaultMethod") || token.equals("packageDefaultMethod")/*backward compatible*/ ) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, severity, isEnabling); return; } else if (token.equals("paramAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportParameterAssignment, severity, isEnabling); return; } break; case 'r' : if (token.equals("raw")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRawTypeReference, severity, isEnabling); return; } else if (/*token.equals("intfRedundant") ||*/ token.equals("redundantSuperinterface")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling); return; } break; case 's' : if (token.equals("specialParamHiding")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_ReportSpecialParameterHidingField, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("syntheticAccess") || token.equals("synthetic-access")) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, severity, isEnabling); return; } else if (token.equals("staticReceiver")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonStaticAccessToStatic, severity, isEnabling); return; } else if (/*token.equals("over-sync") ||*/ token.equals("syncOverride")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSynchronizedOnInheritedMethod, severity, isEnabling); return; } else if (token.equals("semicolon")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportEmptyStatement, severity, isEnabling); return; } else if (token.equals("serial")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSerialVersion, severity, isEnabling); return; } else if (token.equals("suppress")) {//$NON-NLS-1$ switch(severity) { case ProblemSeverities.Warning : this.options.put( CompilerOptions.OPTION_SuppressWarnings, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_SuppressOptionalErrors, CompilerOptions.DISABLED); break; case ProblemSeverities.Error : this.options.put( CompilerOptions.OPTION_SuppressWarnings, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_SuppressOptionalErrors, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); } return; } else if (token.equals("static-access")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonStaticAccessToStatic, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportIndirectStaticAccess, severity, isEnabling); return; } else if (token.equals("super")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportOverridingMethodWithoutSuperInvocation, severity, isEnabling); return; } else if (token.equals("static-method")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling); return; } break; case 't' : if (token.startsWith("tasks")) { //$NON-NLS-1$ String taskTags = Util.EMPTY_STRING; int start = token.indexOf('('); int end = token.indexOf(')'); if (start >= 0 && end >= 0 && start < end){ taskTags = token.substring(start+1, end).trim(); taskTags = taskTags.replace('|',','); } if (taskTags.length() == 0){ throw new IllegalArgumentException(this.bind("configure.invalidTaskTag", token)); //$NON-NLS-1$ } this.options.put( CompilerOptions.OPTION_TaskTags, isEnabling ? taskTags : Util.EMPTY_STRING); setSeverity(CompilerOptions.OPTION_ReportTasks, severity, isEnabling); return; } else if (token.equals("typeHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportTypeParameterHiding, severity, isEnabling); return; } break; case 'u' : if (token.equals("unusedLocal") || token.equals("unusedLocals")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedLocal, severity, isEnabling); return; } else if (token.equals("unusedArgument") || token.equals("unusedArguments")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedParameter, severity, isEnabling); return; } else if (token.equals("unusedImport") || token.equals("unusedImports")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedImport, severity, isEnabling); return; } else if (token.equals("unusedAllocation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedObjectAllocation, severity, isEnabling); return; } else if (token.equals("unusedPrivate")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedPrivateMember, severity, isEnabling); return; } else if (token.equals("unusedLabel")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedLabel, severity, isEnabling); return; } else if (token.equals("uselessTypeCheck")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnnecessaryTypeCheck, severity, isEnabling); return; } else if (token.equals("unchecked") || token.equals("unsafe")) {//$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUncheckedTypeOperation, severity, isEnabling); return; } else if (token.equals("unnecessaryElse")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnnecessaryElse, severity, isEnabling); return; } else if (token.equals("unusedThrown")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedDeclaredThrownException, severity, isEnabling); return; } else if (token.equals("unqualifiedField") || token.equals("unqualified-field-access")) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnqualifiedFieldAccess, severity, isEnabling); return; } else if (token.equals("unused")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedLocal, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedParameter, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedImport, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedPrivateMember, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedDeclaredThrownException, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedLabel, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedTypeArgumentsForMethodInvocation, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantSpecificationOfTypeArguments, severity, isEnabling); return; } else if (token.equals("unusedTypeArgs")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedTypeArgumentsForMethodInvocation, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantSpecificationOfTypeArguments, severity, isEnabling); return; } else if (token.equals("unavoidableGenericProblems")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } break; case 'v' : if (token.equals("varargsCast")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportVarargsArgumentNeedCast, severity, isEnabling); return; } break; case 'w' : if (token.equals("warningToken")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnhandledWarningToken, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedWarningToken, severity, isEnabling); return; } break; } String message = null; switch(severity) { case ProblemSeverities.Warning : message = this.bind("configure.invalidWarning", token); //$NON-NLS-1$ break; case ProblemSeverities.Error : message = this.bind("configure.invalidError", token); //$NON-NLS-1$ } addPendingErrors(message); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private ReferenceBinding[] processClassNames(LookupEnvironment environment) { // check for .class file presence in case of apt processing int length = this.classNames.length; ReferenceBinding[] referenceBindings = new ReferenceBinding[length]; for (int i = 0; i < length; i++) { String currentName = this.classNames[i]; char[][] compoundName = null; if (currentName.indexOf('.') != -1) { // consider names with '.' as fully qualified names char[] typeName = currentName.toCharArray(); compoundName = CharOperation.splitOn('.', typeName); } else { compoundName = new char[][] { currentName.toCharArray() }; } ReferenceBinding type = environment.getType(compoundName); if (type != null && type.isValidBinding()) { if (type.isBinaryBinding()) { referenceBindings[i] = type; } } else { throw new IllegalArgumentException( this.bind("configure.invalidClassName", currentName));//$NON-NLS-1$ } } return referenceBindings; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void processPathEntries(final int defaultSize, final ArrayList paths, final String currentPath, String customEncoding, boolean isSourceOnly, boolean rejectDestinationPathOnJars) { String currentClasspathName = null; String currentDestinationPath = null; ArrayList currentRuleSpecs = new ArrayList(defaultSize); StringTokenizer tokenizer = new StringTokenizer(currentPath, File.pathSeparator + "[]", true); //$NON-NLS-1$ ArrayList tokens = new ArrayList(); while (tokenizer.hasMoreTokens()) { tokens.add(tokenizer.nextToken()); } // state machine final int start = 0; final int readyToClose = 1; // 'path' 'path1[rule];path2' final int readyToCloseEndingWithRules = 2; // 'path[rule]' 'path1;path2[rule]' final int readyToCloseOrOtherEntry = 3; // 'path[rule];' 'path;' 'path1;path2;' final int rulesNeedAnotherRule = 4; // 'path[rule1;' final int rulesStart = 5; // 'path[' 'path1;path2[' final int rulesReadyToClose = 6; // 'path[rule' 'path[rule1;rule2' final int destinationPathReadyToClose = 7; // 'path[-d bin' final int readyToCloseEndingWithDestinationPath = 8; // 'path[-d bin]' 'path[rule][-d bin]' final int destinationPathStart = 9; // 'path[rule][' final int bracketOpened = 10; // '.*[.*' final int bracketClosed = 11; // '.*([.*])+' final int error = 99; int state = start; String token = null; int cursor = 0, tokensNb = tokens.size(), bracket = -1; while (cursor < tokensNb && state != error) { token = (String) tokens.get(cursor++); if (token.equals(File.pathSeparator)) { switch (state) { case start: case readyToCloseOrOtherEntry: case bracketOpened: break; case readyToClose: case readyToCloseEndingWithRules: case readyToCloseEndingWithDestinationPath: state = readyToCloseOrOtherEntry; addNewEntry(paths, currentClasspathName, currentRuleSpecs, customEncoding, currentDestinationPath, isSourceOnly, rejectDestinationPathOnJars); currentRuleSpecs.clear(); break; case rulesReadyToClose: state = rulesNeedAnotherRule; break; case destinationPathReadyToClose: throw new IllegalArgumentException( this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$ currentPath)); case bracketClosed: cursor = bracket + 1; state = rulesStart; break; default: state = error; } } else if (token.equals("[")) { //$NON-NLS-1$ switch (state) { case start: currentClasspathName = ""; //$NON-NLS-1$ //$FALL-THROUGH$ case readyToClose: bracket = cursor - 1; //$FALL-THROUGH$ case bracketClosed: state = bracketOpened; break; case readyToCloseEndingWithRules: state = destinationPathStart; break; case readyToCloseEndingWithDestinationPath: state = rulesStart; break; case bracketOpened: default: state = error; } } else if (token.equals("]")) { //$NON-NLS-1$ switch (state) { case rulesReadyToClose: state = readyToCloseEndingWithRules; break; case destinationPathReadyToClose: state = readyToCloseEndingWithDestinationPath; break; case bracketOpened: state = bracketClosed; break; case bracketClosed: default: state = error; } } else { // regular word switch (state) { case start: case readyToCloseOrOtherEntry: state = readyToClose; currentClasspathName = token; break; case rulesStart: if (token.startsWith("-d ")) { //$NON-NLS-1$ if (currentDestinationPath != null) { throw new IllegalArgumentException( this.bind("configure.duplicateDestinationPathEntry", //$NON-NLS-1$ currentPath)); } currentDestinationPath = token.substring(3).trim(); state = destinationPathReadyToClose; break; } // else we proceed with a rule //$FALL-THROUGH$ case rulesNeedAnotherRule: if (currentDestinationPath != null) { throw new IllegalArgumentException( this.bind("configure.accessRuleAfterDestinationPath", //$NON-NLS-1$ currentPath)); } state = rulesReadyToClose; currentRuleSpecs.add(token); break; case destinationPathStart: if (!token.startsWith("-d ")) { //$NON-NLS-1$ state = error; } else { currentDestinationPath = token.substring(3).trim(); state = destinationPathReadyToClose; } break; case bracketClosed: for (int i = bracket; i < cursor ; i++) { currentClasspathName += (String) tokens.get(i); } state = readyToClose; break; case bracketOpened: break; default: state = error; } } if (state == bracketClosed && cursor == tokensNb) { cursor = bracket + 1; state = rulesStart; } } switch(state) { case readyToCloseOrOtherEntry: break; case readyToClose: case readyToCloseEndingWithRules: case readyToCloseEndingWithDestinationPath: addNewEntry(paths, currentClasspathName, currentRuleSpecs, customEncoding, currentDestinationPath, isSourceOnly, rejectDestinationPathOnJars); break; case bracketOpened: case bracketClosed: default : // we go on anyway if (currentPath.length() != 0) { addPendingErrors(this.bind("configure.incorrectClasspath", currentPath));//$NON-NLS-1$ } } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private int processPaths(String[] args, int index, String currentArg, ArrayList paths) { int localIndex = index; int count = 0; for (int i = 0, max = currentArg.length(); i < max; i++) { switch(currentArg.charAt(i)) { case '[' : count++; break; case ']' : count--; break; } } if (count == 0) { paths.add(currentArg); } else if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } else { StringBuffer currentPath = new StringBuffer(currentArg); while (true) { if (localIndex >= args.length) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } localIndex++; String nextArg = args[localIndex]; for (int i = 0, max = nextArg.length(); i < max; i++) { switch(nextArg.charAt(i)) { case '[' : if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ nextArg)); } count++; break; case ']' : count--; break; } } if (count == 0) { currentPath.append(' '); currentPath.append(nextArg); paths.add(currentPath.toString()); return localIndex - index; } else if (count < 0) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ nextArg)); } else { currentPath.append(' '); currentPath.append(nextArg); } } } return localIndex - index; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private int processPaths(String[] args, int index, String currentArg, String[] paths) { int localIndex = index; int count = 0; for (int i = 0, max = currentArg.length(); i < max; i++) { switch(currentArg.charAt(i)) { case '[' : count++; break; case ']' : count--; break; } } if (count == 0) { paths[0] = currentArg; } else { StringBuffer currentPath = new StringBuffer(currentArg); while (true) { localIndex++; if (localIndex >= args.length) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } String nextArg = args[localIndex]; for (int i = 0, max = nextArg.length(); i < max; i++) { switch(nextArg.charAt(i)) { case '[' : if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } count++; break; case ']' : count--; break; } } if (count == 0) { currentPath.append(' '); currentPath.append(nextArg); paths[0] = currentPath.toString(); return localIndex - index; } else if (count < 0) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } else { currentPath.append(' '); currentPath.append(nextArg); } } } return localIndex - index; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void validateOptions(boolean didSpecifyCompliance) { if (didSpecifyCompliance) { Object version = this.options.get(CompilerOptions.OPTION_Compliance); if (CompilerOptions.VERSION_1_3.equals(version)) { if (!this.didSpecifySource) this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1); } else if (CompilerOptions.VERSION_1_4.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } else if (CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } } else if (CompilerOptions.VERSION_1_5.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else if (CompilerOptions.VERSION_1_6.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source) || CompilerOptions.VERSION_1_6.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } } else if (CompilerOptions.VERSION_1_7.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source) || CompilerOptions.VERSION_1_6.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (CompilerOptions.VERSION_1_7.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } } else if (this.didSpecifySource) { Object version = this.options.get(CompilerOptions.OPTION_Source); // default is source 1.3 target 1.2 and compliance 1.4 if (CompilerOptions.VERSION_1_4.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } else if (CompilerOptions.VERSION_1_6.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (CompilerOptions.VERSION_1_7.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } final Object sourceVersion = this.options.get(CompilerOptions.OPTION_Source); final Object compliance = this.options.get(CompilerOptions.OPTION_Compliance); if (sourceVersion.equals(CompilerOptions.VERSION_1_7) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_7) { // compliance must be 1.7 if source is 1.7 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_7)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_6) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_6) { // compliance must be 1.6 if source is 1.6 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_6)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_5) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_5) { // compliance must be 1.5 if source is 1.5 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_5)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_4) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_4) { // compliance must be 1.4 if source is 1.4 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_4)); //$NON-NLS-1$ } // check and set compliance/source/target compatibilities if (this.didSpecifyTarget) { final Object targetVersion = this.options.get(CompilerOptions.OPTION_TargetPlatform); // tolerate jsr14 target if (CompilerOptions.VERSION_JSR14.equals(targetVersion)) { // expecting source >= 1.5 if (CompilerOptions.versionToJdkLevel(sourceVersion) < ClassFileConstants.JDK1_5) { throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForGenericSource", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } } else if (CompilerOptions.VERSION_CLDC1_1.equals(targetVersion)) { if (this.didSpecifySource && CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_4) { throw new IllegalArgumentException(this.bind("configure.incompatibleSourceForCldcTarget", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } if (CompilerOptions.versionToJdkLevel(compliance) >= ClassFileConstants.JDK1_5) { throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForCldcTarget", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } } else { // target must be 1.7 if source is 1.7 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_7 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_7){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_7)); //$NON-NLS-1$ } // target must be 1.6 if source is 1.6 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_6 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_6){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_6)); //$NON-NLS-1$ } // target must be 1.5 if source is 1.5 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_5 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_5){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_5)); //$NON-NLS-1$ } // target must be 1.4 if source is 1.4 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_4 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_4){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_4)); //$NON-NLS-1$ } // target cannot be greater than compliance level if (CompilerOptions.versionToJdkLevel(compliance) < CompilerOptions.versionToJdkLevel(targetVersion)){ throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForTarget", (String)this.options.get(CompilerOptions.OPTION_Compliance), (String) targetVersion)); //$NON-NLS-1$ } } } }
// 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/indexing/IndexManager.java
private synchronized void updateIndexState(IPath indexLocation, Integer indexState) { if (indexLocation.isEmpty()) throw new IllegalArgumentException(); getIndexStates(); // ensure the states are initialized if (indexState != null) { if (indexState.equals(this.indexStates.get(indexLocation))) return; // not changed this.indexStates.put(indexLocation, indexState); } else { if (!this.indexStates.containsKey(indexLocation)) return; // did not exist anyway this.indexStates.removeKey(indexLocation); } writeSavedIndexNamesFile(); if (VERBOSE) { if (indexState == null) { Util.verbose("-> index state removed for: "+indexLocation); //$NON-NLS-1$ } else { String state = "?"; //$NON-NLS-1$ if (indexState == SAVED_STATE) state = "SAVED"; //$NON-NLS-1$ else if (indexState == UPDATING_STATE) state = "UPDATING"; //$NON-NLS-1$ else if (indexState == UNKNOWN_STATE) state = "UNKNOWN"; //$NON-NLS-1$ else if (indexState == REBUILDING_STATE) state = "REBUILDING"; //$NON-NLS-1$ Util.verbose("-> index state updated to: " + state + " for: "+indexLocation); //$NON-NLS-1$ //$NON-NLS-2$ } } }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public String containerRelativePath(String documentPath) { int index = documentPath.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR); if (index == -1) { index = this.containerPath.length(); if (documentPath.length() <= index) throw new IllegalArgumentException("Document path " + documentPath + " must be relative to " + this.containerPath); //$NON-NLS-1$ //$NON-NLS-2$ } return documentPath.substring(index + 1); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeAllDocumentNames(String[] sortedDocNames, FileOutputStream stream) throws IOException { if (sortedDocNames.length == 0) throw new IllegalArgumentException(); // assume the file was just created by initializeFrom() this.streamBuffer = new byte[BUFFER_WRITE_SIZE]; this.bufferIndex = 0; this.streamEnd = 0; // in order, write: SIGNATURE & headerInfoOffset place holder, then each compressed chunk of document names writeStreamChars(stream, SIGNATURE_CHARS); this.headerInfoOffset = this.streamEnd; writeStreamInt(stream, -1); // will overwrite with correct value later int size = sortedDocNames.length; this.numberOfChunks = (size / CHUNK_SIZE) + 1; this.sizeOfLastChunk = size % CHUNK_SIZE; if (this.sizeOfLastChunk == 0) { this.numberOfChunks--; this.sizeOfLastChunk = CHUNK_SIZE; } this.documentReferenceSize = size <= 0x7F ? 1 : (size <= 0x7FFF ? 2 : 4); // number of bytes used to encode a reference this.chunkOffsets = new int[this.numberOfChunks]; int lastIndex = this.numberOfChunks - 1; for (int i = 0; i < this.numberOfChunks; i++) { this.chunkOffsets[i] = this.streamEnd; int chunkSize = i == lastIndex ? this.sizeOfLastChunk : CHUNK_SIZE; int chunkIndex = i * CHUNK_SIZE; String current = sortedDocNames[chunkIndex]; writeStreamChars(stream, current.toCharArray()); for (int j = 1; j < chunkSize; j++) { String next = sortedDocNames[chunkIndex + j]; int len1 = current.length(); int len2 = next.length(); int max = len1 < len2 ? len1 : len2; int start = 0; // number of identical characters at the beginning (also the index of first character that is different) while (current.charAt(start) == next.charAt(start)) { start++; if (max == start) break; // current is 'abba', next is 'abbab' } if (start > 255) start = 255; int end = 0; // number of identical characters at the end while (current.charAt(--len1) == next.charAt(--len2)) { end++; if (len2 == start) break; // current is 'abbba', next is 'abba' if (len1 == 0) break; // current is 'xabc', next is 'xyabc' } if (end > 255) end = 255; if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) start; this.streamBuffer[this.bufferIndex++] = (byte) end; this.streamEnd += 2; int last = next.length() - end; writeStreamChars(stream, (start < last ? CharOperation.subarray(next.toCharArray(), start, last) : CharOperation.NO_CHAR)); current = next; } } this.startOfCategoryTables = this.streamEnd + 1; }
// 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/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, 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 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/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/NameLookup.java
public IPackageFragment findPackageFragment(IPath path) { if (!path.isAbsolute()) { throw new IllegalArgumentException(Messages.path_mustBeAbsolute); } /* * TODO (jerome) this code should rather use the package fragment map to find the candidate package, then * check if the respective enclosing root maps to the one on this given IPath. */ IResource possibleFragment = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (possibleFragment == null) { //external jar for (int i = 0; i < this.packageFragmentRoots.length; i++) { IPackageFragmentRoot root = this.packageFragmentRoots[i]; if (!root.isExternal()) { continue; } IPath rootPath = root.getPath(); if (rootPath.isPrefixOf(path)) { String name = path.toOSString(); // + 1 is for the File.separatorChar name = name.substring(rootPath.toOSString().length() + 1, name.length()); name = name.replace(File.separatorChar, '.'); IJavaElement[] list = null; try { list = root.getChildren(); } catch (JavaModelException npe) { continue; // the package fragment root is not present; } int elementCount = list.length; for (int j = 0; j < elementCount; j++) { IPackageFragment packageFragment = (IPackageFragment) list[j]; if (nameMatches(name, packageFragment, false)) { return packageFragment; } } } } } else { IJavaElement fromFactory = JavaCore.create(possibleFragment); if (fromFactory == null) { return null; } switch (fromFactory.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: return (IPackageFragment) fromFactory; case IJavaElement.JAVA_PROJECT: // default package in a default root JavaProject project = (JavaProject) fromFactory; try { IClasspathEntry entry = project.getClasspathEntryFor(path); if (entry != null) { IPackageFragmentRoot root = project.getPackageFragmentRoot(project.getResource()); Object defaultPkgRoot = this.packageFragments.get(CharOperation.NO_STRINGS); if (defaultPkgRoot == null) { return null; } if (defaultPkgRoot instanceof PackageFragmentRoot && defaultPkgRoot.equals(root)) return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS); else { IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) defaultPkgRoot; for (int i = 0; i < roots.length; i++) { if (roots[i].equals(root)) { return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS); } } } } } catch (JavaModelException e) { return null; } return null; case IJavaElement.PACKAGE_FRAGMENT_ROOT: return ((PackageFragmentRoot)fromFactory).getPackageFragment(CharOperation.NO_STRINGS); } } return null; }
// 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/JavaModel.java
public IJavaProject getJavaProject(IResource resource) { switch(resource.getType()){ case IResource.FOLDER: return new JavaProject(((IFolder)resource).getProject(), this); case IResource.FILE: return new JavaProject(((IFile)resource).getProject(), this); case IResource.PROJECT: return new JavaProject((IProject)resource, this); default: throw new IllegalArgumentException(Messages.element_invalidResourceForProject); } }
// 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 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 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
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/OverflowingLRUCache.java
public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException { if(newLoadFactor <= 1.0 && newLoadFactor > 0.0) this.loadFactor = newLoadFactor; else throw new IllegalArgumentException(Messages.cache_invalidLoadFactor); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getImport(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public void setName(String name) { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } becomeDetailed(); super.setName(name); this.fOnDemand = name.endsWith(".*"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getPackageDeclaration(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { return ((IType)parent).getField(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); setTypeAltered(true); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setType(String typeName) throws IllegalArgumentException { if (typeName == null) { throw new IllegalArgumentException(Messages.element_nullType); } becomeDetailed(); expand(); fragment(); setTypeAltered(true); setNameAltered(true); this.fType= typeName; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void addSuperInterface(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_addNullInterface); } if (this.fSuperInterfaces == null) { this.fSuperInterfaces= new String[1]; this.fSuperInterfaces[0]= name; } else { this.fSuperInterfaces= appendString(this.fSuperInterfaces, name); } setSuperInterfaces(this.fSuperInterfaces); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { switch (parent.getElementType()) { case IJavaElement.COMPILATION_UNIT: return ((ICompilationUnit)parent).getType(getName()); case IJavaElement.TYPE: return ((IType)parent).getType(getName()); // Note: creating local/anonymous type is not supported default: throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } super.setName(name); Enumeration children= getChildren(); while (children.hasMoreElements()) { IDOMNode child= (IDOMNode)children.nextElement(); if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setSuperInterfaces(String[] names) { becomeDetailed(); if (names == null) { throw new IllegalArgumentException(Messages.dom_nullInterfaces); } fragment(); this.fSuperInterfaces= names; if (names.length == 0) { this.fInterfaces= null; this.fSuperInterfaces= CharOperation.NO_STRINGS; setMask(MASK_TYPE_HAS_INTERFACES, false); } else { setMask(MASK_TYPE_HAS_INTERFACES, true); CharArrayBuffer buffer = new CharArrayBuffer(); for (int i = 0; i < names.length; i++) { if (i > 0) { buffer.append(", "); //$NON-NLS-1$ } buffer.append(names[i]); } this.fInterfaces = buffer.getContents(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { return ((IPackageFragment)parent).getCompilationUnit(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { int count = 1; IDOMNode previousNode = getPreviousNode(); while (previousNode != null) { if (previousNode instanceof DOMInitializer) { count++; } previousNode = previousNode.getPreviousNode(); } return ((IType) parent).getInitializer(count); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addException(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullExceptionType); } if (this.fExceptions == null) { this.fExceptions= new String[1]; this.fExceptions[0]= name; } else { this.fExceptions= appendString(this.fExceptions, name); } setExceptions(this.fExceptions); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addParameter(String type, String name) throws IllegalArgumentException { if (type == null) { throw new IllegalArgumentException(Messages.dom_nullTypeParameter); } if (name == null) { throw new IllegalArgumentException(Messages.dom_nullNameParameter); } if (this.fParameterNames == null) { this.fParameterNames= new String[1]; this.fParameterNames[0]= name; } else { this.fParameterNames= appendString(this.fParameterNames, name); } if (this.fParameterTypes == null) { this.fParameterTypes= new String[1]; this.fParameterTypes[0]= type; } else { this.fParameterTypes= appendString(this.fParameterTypes, type); } setParameters(this.fParameterTypes, this.fParameterNames); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { // translate parameter types to signatures String[] sigs= null; if (this.fParameterTypes != null) { sigs= new String[this.fParameterTypes.length]; int i; for (i= 0; i < this.fParameterTypes.length; i++) { sigs[i]= Signature.createTypeSignature(this.fParameterTypes[i].toCharArray(), false); } } String name= null; if (isConstructor()) { name= getConstructorName(); } else { name= getName(); } return ((IType)parent).getMethod(name, sigs); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setName(String name) { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setParameters(String[] types, String[] names) throws IllegalArgumentException { becomeDetailed(); if (types== null || names == null) { if (types == null && names == null) { this.fParameterTypes= null; this.fParameterNames= null; this.fParameterList= new char[] {'(',')'}; } else { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } } else if (names.length != types.length) { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } else if (names.length == 0) { setParameters(null, null); } else { this.fParameterNames= names; this.fParameterTypes= types; CharArrayBuffer parametersBuffer = new CharArrayBuffer(); parametersBuffer.append("("); //$NON-NLS-1$ char[] comma = new char[] {',', ' '}; for (int i = 0; i < names.length; i++) { if (i > 0) { parametersBuffer.append(comma); } parametersBuffer .append(types[i]) .append(' ') .append(names[i]); } parametersBuffer.append(')'); this.fParameterList= parametersBuffer.getContents(); } fragment(); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setReturnType(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullReturnType); } becomeDetailed(); fragment(); setReturnTypeAltered(true); this.fReturnType= name; }
// 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/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 IClassFile getClassFile(String classFileName) { if (!org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(classFileName)) { throw new IllegalArgumentException(Messages.bind(Messages.element_invalidClassFileName, classFileName)); } // don't hold on the .class file extension to save memory // also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary int length = classFileName.length() - 6; char[] nameWithoutExtension = new char[length]; classFileName.getChars(0, length, nameWithoutExtension, 0); return new ClassFile(this, new String(nameWithoutExtension)); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public ICompilationUnit getCompilationUnit(String cuName) { if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(cuName)) { throw new IllegalArgumentException(Messages.convention_unit_notJavaName); } return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY); }
// 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/Member.java
public IType getType(String typeName, int count) { if (isBinary()) { throw new IllegalArgumentException("Not a source member " + toStringWithAncestors()); //$NON-NLS-1$ } else { SourceType type = new SourceType(this, typeName); type.occurrenceCount = count; return type; } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static void logRepeatedMessage(String key, Exception e) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$ } if (fgRepeatedMessages.contains(key)) { return; } fgRepeatedMessages.add(key); log(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static void logRepeatedMessage(String key, int statusErrorID, String message) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$ } if (fgRepeatedMessages.contains(key)) { return; } fgRepeatedMessages.add(key); log(statusErrorID, message); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == Signature.C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } c = string[++index]; } appendTypeSignature(string, index, buffer, compact); for(int i = 0, dims = index - start; i < dims; i++) { buffer.append('[').append(']'); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } StringBuffer buffer = new StringBuffer(methodSignature.length + 10); // selector if (methodName != null) { buffer.append(methodName); } // parameters 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; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } 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 new IllegalArgumentException(); // a var args is an array type } } 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 new IllegalArgumentException(); } } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendTypeArgumentSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } 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); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendCaptureTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_CAPTURE) { throw new IllegalArgumentException(); } return appendTypeArgumentSignatureForAnchor(string, start + 1, buffer); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendArrayTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == Signature.C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } 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; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendClassTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; switch(c) { case Signature.C_SEMICOLON : // all done return p; case Signature.C_GENERIC_START : int e = scanGenericEnd(string, p + 1); // once we hit type arguments there are no more package prefixes p = e; break; case Signature.C_DOT : buffer.append('.'); break; case '/' : buffer.append('/'); break; case Signature.C_DOLLAR : // once we hit "$" there are no more package prefixes /** * Convert '$' in resolved type signatures into '.'. * NOTE: This assumes that the type signature is an inner type * signature. This is true in most cases, but someone can define a * non-inner type name containing a '$'. */ buffer.append('.'); break; default : buffer.append(c); } p++; } }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public ASTNode[] parseClassBodyDeclarations( char[] source, int offset, int length, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies; final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); parser.setMethodsFullRecovery(false); parser.setStatementsRecovery(enabledStatementRecovery); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); final CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length); ASTNode[] result = parser.parseClassBodyDeclarations(source, offset, length, compilationUnitDeclaration); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } return result; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public CompilationUnitDeclaration parseCompilationUnit(char[] source, Map settings, boolean recordParsingInformation) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies; CommentRecorderParser parser = new CommentRecorderParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())), false); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } if (compilationUnitDeclaration.ignoreMethodBodies) { compilationUnitDeclaration.ignoreFurtherInvestigation = true; // if initial diet parse did not work, no need to dig into method bodies. return compilationUnitDeclaration; } //fill the methods bodies in order for the code to be generated //real parse of the method.... parser.scanner.setSource(compilationResult); org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types; if (types != null) { for (int i = 0, length = types.length; i < length; i++) { types[i].parseMethods(parser, compilationUnitDeclaration); } } if (recordParsingInformation) { this.recordedParsingInformation.updateRecordedParsingInformation(compilationResult); } return compilationUnitDeclaration; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public Expression parseExpression(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); // in this case we don't want to ignore method bodies since we are parsing only an expression final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration unit = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length); Expression result = parser.parseExpression(source, offset, length, unit); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, unit.comments); } return result; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public ConstructorDeclaration parseStatements( char[] source, int offset, int length, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); // in this case we don't want to ignore method bodies since we are parsing only statements final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); parser.setMethodsFullRecovery(false); parser.setStatementsRecovery(enabledStatementRecovery); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length); ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult); constructorDeclaration.sourceEnd = -1; constructorDeclaration.declarationSourceEnd = offset + length - 1; constructorDeclaration.bodyStart = offset; constructorDeclaration.bodyEnd = offset + length - 1; parser.scanner.setSource(compilationResult); parser.scanner.resetTo(offset, offset + length); parser.parse(constructorDeclaration, compilationUnitDeclaration, true); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } return constructorDeclaration; }
// 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 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/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 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, 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 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/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, 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 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/core/JavaCore.java
public static IResource[] getGeneratedResources(IRegion region, boolean includesNonJavaResources) { if (region == null) throw new IllegalArgumentException("region cannot be null"); //$NON-NLS-1$ IJavaElement[] elements = region.getElements(); HashMap projectsStates = new HashMap(); ArrayList collector = new ArrayList(); for (int i = 0, max = elements.length; i < max; i++) { // collect all the java project IJavaElement element = elements[i]; IJavaProject javaProject = element.getJavaProject(); IProject project = javaProject.getProject(); State state = null; State currentState = (State) projectsStates.get(project); if (currentState != null) { state = currentState; } else { state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(project, null); if (state != null) { projectsStates.put(project, state); } } if (state == null) continue; if (element.getElementType() == IJavaElement.JAVA_PROJECT) { IPackageFragmentRoot[] roots = null; try { roots = javaProject.getPackageFragmentRoots(); } catch (JavaModelException e) { // ignore } if (roots == null) continue; IRegion region2 = JavaCore.newRegion(); for (int j = 0; j < roots.length; j++) { region2.add(roots[j]); } IResource[] res = getGeneratedResources(region2, includesNonJavaResources); for (int j = 0, max2 = res.length; j < max2; j++) { collector.add(res[j]); } continue; } IPath outputLocation = null; try { outputLocation = javaProject.getOutputLocation(); } catch (JavaModelException e) { // ignore } IJavaElement root = element; while (root != null && root.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) { root = root.getParent(); } if (root == null) continue; IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) root; int rootPathSegmentCounts = packageFragmentRoot.getPath().segmentCount(); try { IClasspathEntry entry = packageFragmentRoot.getRawClasspathEntry(); IPath entryOutputLocation = entry.getOutputLocation(); if (entryOutputLocation != null) { outputLocation = entryOutputLocation; } } catch (JavaModelException e) { e.printStackTrace(); } if (outputLocation == null) continue; IContainer container = (IContainer) project.getWorkspace().getRoot().findMember(outputLocation); switch(element.getElementType()) { case IJavaElement.COMPILATION_UNIT : // get the .class files generated when this element was built ICompilationUnit unit = (ICompilationUnit) element; getGeneratedResource(unit, container, state, rootPathSegmentCounts, collector); break; case IJavaElement.PACKAGE_FRAGMENT : // collect all the .class files generated when all the units in this package were built IPackageFragment fragment = (IPackageFragment) element; ICompilationUnit[] compilationUnits = null; try { compilationUnits = fragment.getCompilationUnits(); } catch (JavaModelException e) { // ignore } if (compilationUnits == null) continue; for (int j = 0, max2 = compilationUnits.length; j < max2; j++) { getGeneratedResource(compilationUnits[j], container, state, rootPathSegmentCounts, collector); } if (includesNonJavaResources) { // retrieve all non-java resources from the output location using the package fragment path Object[] nonJavaResources = null; try { nonJavaResources = fragment.getNonJavaResources(); } catch (JavaModelException e) { // ignore } if (nonJavaResources != null) { addNonJavaResources(nonJavaResources, container, rootPathSegmentCounts, collector); } } break; case IJavaElement.PACKAGE_FRAGMENT_ROOT : // collect all the .class files generated when all the units in this package were built IPackageFragmentRoot fragmentRoot = (IPackageFragmentRoot) element; if (fragmentRoot.isArchive()) continue; IJavaElement[] children = null; try { children = fragmentRoot.getChildren(); } catch (JavaModelException e) { // ignore } if (children == null) continue; for (int j = 0, max2 = children.length; j < max2; j++) { fragment = (IPackageFragment) children[j]; ICompilationUnit[] units = null; try { units = fragment.getCompilationUnits(); } catch (JavaModelException e) { // ignore } if (units == null) continue; for (int n = 0, max3 = units.length; n < max3; n++) { getGeneratedResource(units[n], container, state, rootPathSegmentCounts, collector); } if (includesNonJavaResources) { // retrieve all non-java resources from the output location using the package fragment path Object[] nonJavaResources = null; try { nonJavaResources = fragment.getNonJavaResources(); } catch (JavaModelException e) { // ignore } if (nonJavaResources != null) { addNonJavaResources(nonJavaResources, container, rootPathSegmentCounts, collector); } } } break; } } int size = collector.size(); if (size != 0) { IResource[] result = new IResource[size]; collector.toArray(result); return result; } return NO_GENERATED_RESOURCES; }
// 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/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/CorrectionEngine.java
private void computeCorrections(ICompilationUnit unit, int id, int start, int end, String[] arguments, ICorrectionRequestor requestor) { if(id == -1 || arguments == null || start == -1 || end == -1) return; if (requestor == null) { throw new IllegalArgumentException(Messages.correction_nullRequestor); } this.correctionRequestor = requestor; this.correctionStart = start; this.correctionEnd = end; this.compilationUnit = unit; String argument = null; try { switch (id) { // Type correction case IProblem.ImportNotFound : this.filter = IMPORT; argument = arguments[0]; break; case IProblem.UndefinedType : this.filter = CLASSES | INTERFACES; argument = arguments[0]; break; // Method correction case IProblem.UndefinedMethod : this.filter = METHOD; argument = arguments[1]; break; // Field and local variable correction case IProblem.UndefinedField : this.filter = FIELD; argument = arguments[0]; break; case IProblem.UndefinedName : case IProblem.UnresolvedVariable : this.filter = FIELD | LOCAL; argument = arguments[0]; break; } } catch (ArrayIndexOutOfBoundsException e) { return; } if(argument != null) { correct(argument.toCharArray()); } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } c = string[++index]; } int e = appendTypeSignature(string, index, fullyQualifyTypeNames, buffer); 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; }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendCaptureTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_CAPTURE) { throw new IllegalArgumentException(); } buffer.append(CAPTURE).append(' '); return appendTypeArgumentSignature(string, start + 1, fullyQualifyTypeNames, buffer); }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendClassTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != C_RESOLVED && c != C_UNRESOLVED) { throw new IllegalArgumentException(); } boolean resolved = (c == C_RESOLVED); boolean removePackageQualifiers = !fullyQualifyTypeNames; if (!resolved) { // keep everything in an unresolved name removePackageQualifiers = false; } int p = start + 1; int checkpoint = buffer.length(); int innerTypeStart = -1; boolean inAnonymousType = false; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; switch(c) { case C_SEMICOLON : // all done return p; case C_GENERIC_START : int e = appendTypeArgumentSignatures(string, p, fullyQualifyTypeNames, buffer); // once we hit type arguments there are no more package prefixes removePackageQualifiers = false; p = e; break; case C_DOT : if (removePackageQualifiers) { // erase package prefix buffer.setLength(checkpoint); } else { buffer.append('.'); } break; case '/' : if (removePackageQualifiers) { // erase package prefix buffer.setLength(checkpoint); } else { buffer.append('/'); } break; case C_DOLLAR : innerTypeStart = buffer.length(); inAnonymousType = false; if (resolved) { // once we hit "$" there are no more package prefixes removePackageQualifiers = false; /** * Convert '$' in resolved type signatures into '.'. * NOTE: This assumes that the type signature is an inner type * signature. This is true in most cases, but someone can define a * non-inner type name containing a '$'. */ buffer.append('.'); } break; default : if (innerTypeStart != -1 && !inAnonymousType && Character.isDigit(c)) { inAnonymousType = true; buffer.setLength(innerTypeStart); // remove '.' buffer.insert(checkpoint, "new "); //$NON-NLS-1$ buffer.append("(){}"); //$NON-NLS-1$ } if (!inAnonymousType) buffer.append(c); innerTypeStart = -1; } p++; } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendIntersectionTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_INTERSECTION) { throw new IllegalArgumentException(); } start = appendClassTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); if (start < string.length - 1) { start++; if (string[start] != C_COLON) { throw new IllegalArgumentException("should be a colon at this location"); //$NON-NLS-1$ } while (string[start] == C_COLON) { buffer.append(" | "); //$NON-NLS-1$ start = appendClassTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); if (start == string.length - 1) { return start; } else if (start > string.length - 1) { throw new IllegalArgumentException("Should be at the end"); //$NON-NLS-1$ } start++; } } return start; }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeArgumentSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch(c) { case C_STAR : buffer.append('?'); return start; case C_EXTENDS : buffer.append("? extends "); //$NON-NLS-1$ return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); case C_SUPER : buffer.append("? super "); //$NON-NLS-1$ return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); default : return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer); } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeArgumentSignatures(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char "<>" if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } buffer.append('<'); int p = start + 1; int count = 0; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_GENERIC_END) { buffer.append('>'); return p; } if (count != 0) { buffer.append(','); } int e = appendTypeArgumentSignature(string, p, fullyQualifyTypeNames, buffer); count++; p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; if (isVarArgs) { switch (c) { case C_ARRAY : return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, true); case C_RESOLVED : case C_UNRESOLVED : case C_TYPE_VARIABLE : case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : case C_STAR: case C_EXTENDS: case C_SUPER: case C_CAPTURE: case C_INTERSECTION : default: throw new IllegalArgumentException(); // a var args is an array type } } else { switch (c) { case C_ARRAY : return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_RESOLVED : case C_UNRESOLVED : return appendClassTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_TYPE_VARIABLE : int e = Util.scanTypeVariableSignature(string, start); buffer.append(string, start + 1, e - start - 1); return e; case C_BOOLEAN : buffer.append(BOOLEAN); return start; case C_BYTE : buffer.append(BYTE); return start; case C_CHAR : buffer.append(CHAR); return start; case C_DOUBLE : buffer.append(DOUBLE); return start; case C_FLOAT : buffer.append(FLOAT); return start; case C_INT : buffer.append(INT); return start; case C_LONG : buffer.append(LONG); return start; case C_SHORT : buffer.append(SHORT); return start; case C_VOID : buffer.append(VOID); return start; case C_CAPTURE : return appendCaptureTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_INTERSECTION : return appendIntersectionTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_STAR: case C_EXTENDS: case C_SUPER: return appendTypeArgumentSignature(string, start, fullyQualifyTypeNames, buffer); default : throw new IllegalArgumentException(); } } }
// in model/org/eclipse/jdt/core/Signature.java
private static int checkNextChar(char[] typeName, char expectedChar, int pos, int length, boolean isOptional) { pos = consumeWhitespace(typeName, pos, length); if (pos < length && typeName[pos] == expectedChar) return pos + 1; if (!isOptional) throw new IllegalArgumentException(new String(typeName)); return -1; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) { if (typeName == null) throw new IllegalArgumentException("null"); //$NON-NLS-1$ int length = typeName.length; if (length == 0) throw new IllegalArgumentException(new String(typeName)); StringBuffer buffer = new StringBuffer(5); int pos = encodeTypeSignature(typeName, 0, isResolved, length, buffer); pos = consumeWhitespace(typeName, pos, length); if (pos < length) throw new IllegalArgumentException(new String(typeName)); char[] result = new char[length = buffer.length()]; buffer.getChars(0, length, result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
private static int encodeQualifiedName(char[] typeName, int pos, int length, StringBuffer buffer) { int count = 0; char lastAppendedChar = 0; nameLoop: while (pos < length) { char currentChar = typeName[pos]; switch (currentChar) { case '<' : case '>' : case '[' : case ',' : break nameLoop; case '.' : buffer.append(C_DOT); lastAppendedChar = C_DOT; count++; break; default: if (currentChar == ' ' || ScannerHelper.isWhitespace(currentChar)) { if (lastAppendedChar == C_DOT) { // allow spaces after a dot pos = consumeWhitespace(typeName, pos, length) - 1; // will be incremented break; } // allow spaces before a dot int checkPos = checkNextChar(typeName, '.', pos, length, true); if (checkPos > 0) { buffer.append(C_DOT); // process dot immediately to avoid one iteration lastAppendedChar = C_DOT; count++; pos = checkPos; break; } break nameLoop; } buffer.append(currentChar); lastAppendedChar = currentChar; count++; break; } pos++; } if (count == 0) throw new IllegalArgumentException(new String(typeName)); return pos; }
// in model/org/eclipse/jdt/core/Signature.java
private static int encodeTypeSignature(char[] typeName, int start, boolean isResolved, int length, StringBuffer buffer) { int pos = start; pos = consumeWhitespace(typeName, pos, length); if (pos >= length) throw new IllegalArgumentException(new String(typeName)); int checkPos; char currentChar = typeName[pos]; switch (currentChar) { // primitive type? case 'b' : checkPos = checkName(BOOLEAN, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_BOOLEAN); return pos; } checkPos = checkName(BYTE, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_BYTE); return pos; } break; case 'd': checkPos = checkName(DOUBLE, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_DOUBLE); return pos; } break; case 'f': checkPos = checkName(FLOAT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_FLOAT); return pos; } break; case 'i': checkPos = checkName(INT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_INT); return pos; } break; case 'l': checkPos = checkName(LONG, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_LONG); return pos; } break; case 's': checkPos = checkName(SHORT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_SHORT); return pos; } break; case 'v': checkPos = checkName(VOID, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_VOID); return pos; } break; case 'c': checkPos = checkName(CHAR, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_CHAR); return pos; } else { checkPos = checkName(CAPTURE, typeName, pos, length); if (checkPos > 0) { pos = consumeWhitespace(typeName, checkPos, length); if (typeName[pos] != '?') { break; } } else { break; } } buffer.append(C_CAPTURE); //$FALL-THROUGH$ for wildcard part of capture typecheckPos case '?': // wildcard pos = consumeWhitespace(typeName, pos+1, length); checkPos = checkName(EXTENDS, typeName, pos, length); if (checkPos > 0) { buffer.append(C_EXTENDS); pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); return pos; } checkPos = checkName(SUPER, typeName, pos, length); if (checkPos > 0) { buffer.append(C_SUPER); pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); return pos; } buffer.append(C_STAR); return pos; } // non primitive type checkPos = checkArrayDimension(typeName, pos, length); int end; if (checkPos > 0) { end = encodeArrayDimension(typeName, checkPos, length, buffer); } else { end = -1; } buffer.append(isResolved ? C_RESOLVED : C_UNRESOLVED); while (true) { // loop on qualifiedName[<args>][.qualifiedName[<args>]* pos = encodeQualifiedName(typeName, pos, length, buffer); checkPos = checkNextChar(typeName, '<', pos, length, true); if (checkPos > 0) { buffer.append(C_GENERIC_START); // Stop gap fix for <>. if ((pos = checkNextChar(typeName, '>', checkPos, length, true)) > 0) { buffer.append(C_GENERIC_END); } else { pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); while ((checkPos = checkNextChar(typeName, ',', pos, length, true)) > 0) { pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); } pos = checkNextChar(typeName, '>', pos, length, false); buffer.append(C_GENERIC_END); } } checkPos = checkNextChar(typeName, '.', pos, length, true); if (checkPos > 0) { buffer.append(C_DOT); pos = checkPos; } else { break; } } buffer.append(C_NAME_END); if (end > 0) pos = end; // skip array dimension which were preprocessed return pos; }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { try { int count = 0; while (typeSignature[count] == C_ARRAY) { ++count; } return count; } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getIntersectionTypeBounds(char[] intersectionTypeSignature) throws IllegalArgumentException { if (getTypeSignatureKind(intersectionTypeSignature) != INTERSECTION_TYPE_SIGNATURE) { return CharOperation.NO_CHAR_CHAR; } ArrayList args = new ArrayList(); int i = 1; // skip the '|' int length = intersectionTypeSignature.length; for (;;) { int e = Util.scanClassTypeSignature(intersectionTypeSignature, i); if (e < 0) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } args.add(CharOperation.subarray(intersectionTypeSignature, i, e + 1)); if (e == length - 1) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } else if (intersectionTypeSignature[e + 1] != C_COLON) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } i = e + 2; // add one to skip C_COLON } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { try { int count = getParameterCount(methodSignature); char[][] result = new char[count][]; if (count == 0) { return result; } int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } int t = 0; for (;;) { if (methodSignature[i] == C_PARAM_END) { return result; } int e = Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } result[t] = CharOperation.subarray(methodSignature, i, e + 1); t++; i = e + 1; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // there could be thrown exceptions behind, thus scan one type exactly int last = Util.scanTypeSignature(methodSignature, paren+1); return CharOperation.subarray(methodSignature, paren + 1, last+1); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getThrownExceptionTypes(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int exceptionStart = CharOperation.indexOf(C_EXCEPTION_START, methodSignature); if (exceptionStart == -1) { int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // ignore return type exceptionStart = Util.scanTypeSignature(methodSignature, paren+1) + 1; int length = methodSignature.length; if (exceptionStart == length) return CharOperation.NO_CHAR_CHAR; throw new IllegalArgumentException(); } int length = methodSignature.length; int i = exceptionStart; ArrayList exceptionList = new ArrayList(1); while (i < length) { if (methodSignature[i] == C_EXCEPTION_START) { exceptionStart++; i++; } else { throw new IllegalArgumentException(); } i = Util.scanTypeSignature(methodSignature, i) + 1; exceptionList.add(CharOperation.subarray(methodSignature, exceptionStart,i)); exceptionStart = i; } char[][] result; exceptionList.toArray(result = new char[exceptionList.size()][]); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeArguments(char[] parameterizedTypeSignature) throws IllegalArgumentException { int length = parameterizedTypeSignature.length; if (length < 2 || parameterizedTypeSignature[length-2] != C_GENERIC_END) // cannot have type arguments otherwise signature would end by ">;" return CharOperation.NO_CHAR_CHAR; int count = 1; // start to count generic end/start peers int start = length - 2; while (start >= 0 && count > 0) { switch (parameterizedTypeSignature[--start]) { case C_GENERIC_START: count--; break; case C_GENERIC_END: count++; break; } } if (start < 0) // invalid number of generic start/end throw new IllegalArgumentException(); ArrayList args = new ArrayList(); int p = start + 1; while (true) { if (p >= parameterizedTypeSignature.length) { throw new IllegalArgumentException(); } char c = parameterizedTypeSignature[p]; if (c == C_GENERIC_END) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } int e = Util.scanTypeArgumentSignature(parameterizedTypeSignature, p); args.add(CharOperation.subarray(parameterizedTypeSignature, p, e+1)); p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeErasure(char[] parameterizedTypeSignature) throws IllegalArgumentException { int end = CharOperation.indexOf(C_GENERIC_START, parameterizedTypeSignature); if (end == -1) return parameterizedTypeSignature; int length = parameterizedTypeSignature.length; char[] result = new char[length]; int pos = 0; int start = 0; int deep= 0; for (int idx=end; idx<length; idx++) { switch (parameterizedTypeSignature[idx]) { case C_GENERIC_START: if (deep == 0) { int size = idx-start; System.arraycopy(parameterizedTypeSignature, start, result, pos, size); end = idx; pos += size; } deep++; break; case C_GENERIC_END: deep--; if (deep < 0) throw new IllegalArgumentException(); if (deep == 0) start = idx+1; break; } } if (deep > 0) throw new IllegalArgumentException(); int size = pos+length-start; char[] resized = new char[size]; System.arraycopy(result, 0, resized, 0, pos); System.arraycopy(parameterizedTypeSignature, start, resized, pos, length-start); return resized; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p1 < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } if (p1 == formalTypeParameterSignature.length - 1) { // no class or interface bounds return CharOperation.NO_CHAR_CHAR; } int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); char[] classBound; if (p2 < 0) { // no interface bounds classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); return new char[][] {classBound}; } if (p2 == p1 + 1) { // no class bound, but 1 or more interface bounds classBound = null; } else { classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); } char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); if (classBound == null) { return interfaceBounds; } int resultLength = interfaceBounds.length + 1; char[][] result = new char[resultLength][]; result[0] = classBound; System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { try { int length = methodOrTypeSignature.length; if (length == 0) return CharOperation.NO_CHAR_CHAR; if (methodOrTypeSignature[0] != C_GENERIC_START) return CharOperation.NO_CHAR_CHAR; ArrayList paramList = new ArrayList(1); int paramStart = 1, i = 1; // start after leading '<' while (i < length) { if (methodOrTypeSignature[i] == C_GENERIC_END) { int size = paramList.size(); if (size == 0) throw new IllegalArgumentException(); char[][] result; paramList.toArray(result = new char[size][]); return result; } i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); if (i < 0 || i >= length) throw new IllegalArgumentException(); // iterate over bounds while (methodOrTypeSignature[i] == ':') { i++; // skip colon switch (methodOrTypeSignature[i]) { case ':': // no class bound break; case C_GENERIC_END: break; case C_RESOLVED: try { i = Util.scanClassTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter } break; case C_ARRAY: try { i = Util.scanArrayTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter } break; case C_TYPE_VARIABLE: try { i = Util.scanTypeVariableSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter } break; // default: another type parameter is starting } } paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); paramStart = i; // next param start from here } } catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through } throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
public static int getTypeSignatureKind(char[] typeSignature) { // need a minimum 1 char if (typeSignature.length < 1) { throw new IllegalArgumentException(); } char c = typeSignature[0]; if (c == C_GENERIC_START) { int count = 1; for (int i = 1, length = typeSignature.length; i < length; i++) { switch (typeSignature[i]) { case C_GENERIC_START: count++; break; case C_GENERIC_END: count--; break; } if (count == 0) { if (i+1 < length) c = typeSignature[i+1]; break; } } } switch (c) { case C_ARRAY : return ARRAY_TYPE_SIGNATURE; case C_RESOLVED : case C_UNRESOLVED : return CLASS_TYPE_SIGNATURE; case C_TYPE_VARIABLE : return TYPE_VARIABLE_SIGNATURE; case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : return BASE_TYPE_SIGNATURE; case C_STAR : case C_SUPER : case C_EXTENDS : return WILDCARD_TYPE_SIGNATURE; case C_CAPTURE : return CAPTURE_TYPE_SIGNATURE; case C_INTERSECTION : return INTERSECTION_TYPE_SIGNATURE; default : throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeVariable(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } return CharOperation.subarray(formalTypeParameterSignature, 0, p); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] signature) throws IllegalArgumentException { int sigLength = signature.length; if (sigLength == 0) { throw new IllegalArgumentException(); } if (signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); } StringBuffer buffer = new StringBuffer(signature.length + 10); appendTypeSignature(signature, 0, true, buffer); char[] result = new char[buffer.length()]; buffer.getChars(0, buffer.length(), result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVargArgs) { int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); if (firstParen == -1) { throw new IllegalArgumentException(); } StringBuffer buffer = new StringBuffer(methodSignature.length + 10); // return type if (includeReturnType) { char[] rts = getReturnType(methodSignature); appendTypeSignature(rts, 0 , fullyQualifyTypeNames, buffer); buffer.append(' '); } // selector if (methodName != null) { buffer.append(methodName); } // parameters buffer.append('('); char[][] pts = getParameterTypes(methodSignature); // search for the last array in the signature int max = pts.length; int index = max - 1; loop: for (int i = index; i >= 0; i--) { if (pts[i][0] == Signature.C_ARRAY) { break loop; } index--; } for (int i = 0; i < max; i++) { if (i == index) { appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer, isVargArgs); } else { appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer); } if (parameterNames != null) { buffer.append(' '); buffer.append(parameterNames[i]); } 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; }
// in model/org/eclipse/jdt/core/util/CompilationUnitSorter.java
private static void checkASTLevel(int level) { switch (level) { case AST.JLS2 : case AST.JLS3 : case AST.JLS4 : break; default : throw new IllegalArgumentException(); } }
// 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/CompletionRequestor.java
public boolean isIgnored(int completionProposalKind) { if (completionProposalKind < CompletionProposal.FIRST_KIND || completionProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$ } return 0 != (this.ignoreSet & (1 << completionProposalKind)); }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public void setIgnored(int completionProposalKind, boolean ignore) { if (completionProposalKind < CompletionProposal.FIRST_KIND || completionProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$ } if (ignore) { this.ignoreSet |= (1 << completionProposalKind); } else { this.ignoreSet &= ~(1 << completionProposalKind); } }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public boolean isAllowingRequiredProposals(int proposalKind, int requiredProposalKind) { if (proposalKind < CompletionProposal.FIRST_KIND || proposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (requiredProposalKind < CompletionProposal.FIRST_KIND || requiredProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (this.requiredProposalAllowSet == null) return false; return 0 != (this.requiredProposalAllowSet[proposalKind] & (1 << requiredProposalKind)); }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public void setAllowsRequiredProposals(int proposalKind, int requiredProposalKind, boolean allow) { if (proposalKind < CompletionProposal.FIRST_KIND || proposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (requiredProposalKind < CompletionProposal.FIRST_KIND || requiredProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (this.requiredProposalAllowSet == null) { this.requiredProposalAllowSet = new int[CompletionProposal.LAST_KIND + 1]; } if (allow) { this.requiredProposalAllowSet[proposalKind] |= (1 << requiredProposalKind); } else { this.requiredProposalAllowSet[proposalKind] &= ~(1 << requiredProposalKind); } }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) { int length= string.length(); if (0 < 0 || length < 0 || 0 + length > string.length()) { throw new IllegalArgumentException("offset or length outside of string. offset: " + 0 + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return ToolFactory.createCodeFormatter(options).format(kind, string, 0, length, indentationLevel, lineSeparator); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException { Document doc= new Document(content); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { if (this.fOffset < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < this.fOffset + this.fLength)) { this.fPosition.offset= this.fOffset + this.fLength; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public String createIndentationString(final int indentationLevel) { if (indentationLevel < 0) { throw new IllegalArgumentException(); } int tabs = 0; int spaces = 0; switch(this.preferences.tab_char) { case DefaultCodeFormatterOptions.SPACE : spaces = indentationLevel * this.preferences.tab_size; break; case DefaultCodeFormatterOptions.TAB : tabs = indentationLevel; break; case DefaultCodeFormatterOptions.MIXED : int tabSize = this.preferences.tab_size; if (tabSize != 0) { int spaceEquivalents = indentationLevel * this.preferences.indentation_size; tabs = spaceEquivalents / tabSize; spaces = spaceEquivalents % tabSize; } break; default: return Util.EMPTY_STRING; } if (tabs == 0 && spaces == 0) { return Util.EMPTY_STRING; } StringBuffer buffer = new StringBuffer(tabs + spaces); for(int i = 0; i < tabs; i++) { buffer.append('\t'); } for(int i = 0; i < spaces; i++) { buffer.append(' '); } return buffer.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { if (offset < 0 || length < 0 || length > source.length()) { throw new IllegalArgumentException(); } switch(kind & K_MASK) { case K_JAVA_DOC : // https://bugs.eclipse.org/bugs/show_bug.cgi?id=102780 // use the integrated comment formatter to format comment return formatComment(kind & K_MASK, source, indentationLevel, lineSeparator, new IRegion[] {new Region(offset, length)}); // $FALL-THROUGH$ - fall through next case when old comment formatter is activated case K_MULTI_LINE_COMMENT : case K_SINGLE_LINE_COMMENT : return formatComment(kind & K_MASK, source, indentationLevel, lineSeparator, new IRegion[] {new Region(offset, length)}); } return format(kind, source, new IRegion[] {new Region(offset, length)}, indentationLevel, lineSeparator); }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public TextEdit format(int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) { if (!regionsSatisfiesPreconditions(regions, source.length())) { throw new IllegalArgumentException(); } this.codeSnippetParsingUtil = new CodeSnippetParsingUtil(); boolean includeComments = (kind & F_INCLUDE_COMMENTS) != 0; switch(kind & K_MASK) { case K_CLASS_BODY_DECLARATIONS : return formatClassBodyDeclarations(source, indentationLevel, lineSeparator, regions, includeComments); case K_COMPILATION_UNIT : return formatCompilationUnit(source, indentationLevel, lineSeparator, regions, includeComments); case K_EXPRESSION : return formatExpression(source, indentationLevel, lineSeparator, regions, includeComments); case K_STATEMENTS : return formatStatements(source, indentationLevel, lineSeparator, regions, includeComments); case K_UNKNOWN : return probeFormatting(source, indentationLevel, lineSeparator, regions, includeComments); case K_JAVA_DOC : case K_MULTI_LINE_COMMENT : case K_SINGLE_LINE_COMMENT : //https://bugs.eclipse.org/bugs/show_bug.cgi?id=204091 throw new IllegalArgumentException(); } return null; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int measureIndentUnits(CharSequence line, int tabWidth, int indentWidth) { if (indentWidth < 0 || tabWidth < 0 || line == null) { throw new IllegalArgumentException(); } if (indentWidth == 0) return 0; int visualLength= measureIndentInSpaces(line, tabWidth); return visualLength / indentWidth; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int measureIndentInSpaces(CharSequence line, int tabWidth) { if (tabWidth < 0 || line == null) { throw new IllegalArgumentException(); } int length= 0; int max= line.length(); for (int i= 0; i < max; i++) { char ch= line.charAt(i); if (ch == '\t') { length = calculateSpaceEquivalents(tabWidth, length); } else if (isIndentChar(ch)) { length++; } else { return length; } } return length; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String extractIndentString(String line, int tabWidth, int indentWidth) { if (tabWidth < 0 || indentWidth < 0 || line == null) { throw new IllegalArgumentException(); } int size = line.length(); int end = 0; int spaceEquivs = 0; int characters = 0; for (int i = 0; i < size; i++) { char c = line.charAt(i); if (c == '\t') { spaceEquivs = calculateSpaceEquivalents(tabWidth, spaceEquivs); characters++; } else if (isIndentChar(c)) { spaceEquivs++; characters++; } else { break; } if (spaceEquivs >= indentWidth) { end += characters; characters = 0; if(indentWidth == 0) { spaceEquivs = 0; } else { spaceEquivs = spaceEquivs % indentWidth; } } } if (end == 0) { return Util.EMPTY_STRING; } else if (end == size) { return line; } else { return line.substring(0, end); } }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String trimIndent(String line, int indentUnitsToRemove, int tabWidth, int indentWidth) { if (tabWidth < 0 || indentWidth < 0 || line == null) { throw new IllegalArgumentException(); } if (indentUnitsToRemove <= 0 || indentWidth == 0) { return line; } final int spaceEquivalentsToRemove= indentUnitsToRemove * indentWidth; int start= 0; int spaceEquivalents= 0; int size= line.length(); String prefix= null; for (int i= 0; i < size; i++) { char c= line.charAt(i); if (c == '\t') { spaceEquivalents = calculateSpaceEquivalents(tabWidth, spaceEquivalents); } else if (isIndentChar(c)) { spaceEquivalents++; } else { // Assert.isTrue(false, "Line does not have requested number of indents"); start= i; break; } if (spaceEquivalents == spaceEquivalentsToRemove) { start= i + 1; break; } if (spaceEquivalents > spaceEquivalentsToRemove) { // can happen if tabSize > indentSize, e.g tabsize==8, indent==4, indentsToRemove==1, line prefixed with one tab // this implements the third option start= i + 1; // remove the tab // and add the missing spaces char[] missing= new char[spaceEquivalents - spaceEquivalentsToRemove]; Arrays.fill(missing, ' '); prefix= new String(missing); break; } } String trimmed; if (start == size) trimmed= Util.EMPTY_STRING; else trimmed= line.substring(start); if (prefix == null) return trimmed; return prefix + trimmed; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String changeIndent(String code, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString, String lineDelim) { if (tabWidth < 0 || indentWidth < 0 || code == null || indentUnitsToRemove < 0 || newIndentString == null || lineDelim == null) { throw new IllegalArgumentException(); } try { ILineTracker tracker= new DefaultLineTracker(); tracker.set(code); int nLines= tracker.getNumberOfLines(); if (nLines == 1) { return code; } StringBuffer buf= new StringBuffer(); for (int i= 0; i < nLines; i++) { IRegion region= tracker.getLineInformation(i); int start= region.getOffset(); int end= start + region.getLength(); String line= code.substring(start, end); if (i == 0) { // no indent for first line (contained in the formatted string) buf.append(line); } else { // no new line after last line buf.append(lineDelim); buf.append(newIndentString); if(indentWidth != 0) { buf.append(trimIndent(line, indentUnitsToRemove, tabWidth, indentWidth)); } else { buf.append(line); } } } return buf.toString(); } catch (BadLocationException e) { // can not happen return code; } }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static ReplaceEdit[] getChangeIndentEdits(String source, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString) { if (tabWidth < 0 || indentWidth < 0 || source == null || indentUnitsToRemove < 0 || newIndentString == null) { throw new IllegalArgumentException(); } ArrayList result= new ArrayList(); try { ILineTracker tracker= new DefaultLineTracker(); tracker.set(source); int nLines= tracker.getNumberOfLines(); if (nLines == 1) return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]); for (int i= 1; i < nLines; i++) { IRegion region= tracker.getLineInformation(i); int offset= region.getOffset(); String line= source.substring(offset, offset + region.getLength()); int length= indexOfIndent(line, indentUnitsToRemove, tabWidth, indentWidth); if (length >= 0) { result.add(new ReplaceEdit(offset, length, newIndentString)); } else { length= measureIndentUnits(line, tabWidth, indentWidth); result.add(new ReplaceEdit(offset, length, "")); //$NON-NLS-1$ } } } catch (BadLocationException cannotHappen) { // can not happen } return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int getTabWidth(Map options) { if (options == null) { throw new IllegalArgumentException(); } return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int getIndentWidth(Map options) { if (options == null) { throw new IllegalArgumentException(); } int tabWidth=getTabWidth(options); boolean isMixedMode= DefaultCodeFormatterConstants.MIXED.equals(options.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)); if (isMixedMode) { return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, tabWidth); } return tabWidth; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setTokenRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { throw new IllegalArgumentException(); } this.tokenStart = startIndex; this.tokenEnd = endIndex; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setReplaceRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { throw new IllegalArgumentException(); } this.replaceStart = startIndex; this.replaceEnd = endIndex; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setRelevance(int rating) { if (rating <= 0) { throw new IllegalArgumentException(); } this.relevance = rating; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
private int getParametersCount(char[] methodSignature) { int i = CharOperation.indexOf('(', methodSignature); i++; char currentCharacter = methodSignature[i]; if (currentCharacter == ')') { return 0; } int result = 0; while (true) { currentCharacter = methodSignature[i]; if (currentCharacter == ')') { return result; } switch (currentCharacter) { case '[': // array type int scanType = scanType(methodSignature, i + 1); result++; i = scanType + 1; break; case 'L': scanType = CharOperation.indexOf(';', methodSignature, i + 1); result++; i = scanType + 1; break; case 'Z': case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': result++; i++; break; default: throw new IllegalArgumentException("Invalid starting type character : " + currentCharacter); //$NON-NLS-1$ } } }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
private int scanType(char[] methodSignature, int index) { switch (methodSignature[index]) { case '[': // array type return scanType(methodSignature, index + 1); case 'L': return CharOperation.indexOf(';', methodSignature, index + 1); case 'Z': case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': return index; default: throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/StackMapFrame.java
public void addStackItem(VerificationTypeInfo info) { if (info == null) { throw new IllegalArgumentException("info cannot be null"); //$NON-NLS-1$ } if (this.stackItems == null) { this.stackItems = new VerificationTypeInfo[1]; this.stackItems[0] = info; this.numberOfStackItems = 1; } else { final int length = this.stackItems.length; if (this.numberOfStackItems == length) { System.arraycopy(this.stackItems, 0, this.stackItems = new VerificationTypeInfo[length + 1], 0, length); } this.stackItems[this.numberOfStackItems++] = info; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int getParameterCount(char[] methodSignature) { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_ARRAY : return scanArrayTypeSignature(string, start); case C_RESOLVED : case C_UNRESOLVED : return scanClassTypeSignature(string, start); case C_TYPE_VARIABLE : return scanTypeVariableSignature(string, start); case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : return scanBaseTypeSignature(string, start); case C_CAPTURE : return scanCaptureTypeSignature(string, start); case C_EXTENDS: case C_SUPER: case C_STAR: return scanTypeBoundSignature(string, start); default : throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanBaseTypeSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ return start; } else { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanArrayTypeSignature(char[] string, int start) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_ARRAY) { throw new IllegalArgumentException(); } c = string[++start]; while(c == C_ARRAY) { // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } c = string[++start]; } return scanTypeSignature(string, start); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanCaptureTypeSignature(char[] string, int start) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_CAPTURE) { throw new IllegalArgumentException(); } return scanTypeBoundSignature(string, start + 1); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeVariableSignature(char[] string, int start) { // need a minimum 3 chars "Tx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "T" char c = string[start]; if (c != C_TYPE_VARIABLE) { throw new IllegalArgumentException(); } int id = scanIdentifier(string, start + 1); c = string[id + 1]; if (c == C_SEMICOLON) { return id + 1; } else { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanIdentifier(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } int p = start; while (true) { char c = string[p]; if (c == '<' || c == '>' || c == ':' || c == ';' || c == '.' || c == '/') { return p - 1; } p++; if (p == string.length) { return p - 1; } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanClassTypeSignature(char[] string, int start) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != C_RESOLVED && c != C_UNRESOLVED) { return -1; } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_SEMICOLON) { // all done return p; } else if (c == C_GENERIC_START) { int e = scanTypeArgumentSignatures(string, p); p = e; } else if (c == C_DOT || c == '/') { int id = scanIdentifier(string, p + 1); p = id; } p++; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeBoundSignature(char[] string, int start) { // need a minimum 1 char for wildcard if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_STAR : return start; case C_SUPER : case C_EXTENDS : // need a minimum 3 chars "+[I" if (start >= string.length - 2) { throw new IllegalArgumentException(); } break; default : // must start in "+/-" throw new IllegalArgumentException(); } c = string[++start]; switch (c) { case C_CAPTURE : return scanCaptureTypeSignature(string, start); case C_SUPER : case C_EXTENDS : return scanTypeBoundSignature(string, start); case C_RESOLVED : case C_UNRESOLVED : return scanClassTypeSignature(string, start); case C_TYPE_VARIABLE : return scanTypeVariableSignature(string, start); case C_ARRAY : return scanArrayTypeSignature(string, start); case C_STAR: return start; default: throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeArgumentSignatures(char[] string, int start) { // need a minimum 2 char "<>" if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_GENERIC_END) { return p; } int e = scanTypeArgumentSignature(string, p); p = e + 1; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeArgumentSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_STAR : return start; case C_EXTENDS : case C_SUPER : return scanTypeBoundSignature(string, start); default : return scanTypeSignature(string, start); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSetOfCharArray.java
public void asArray(Object[] copy) { if (this.elementSize != copy.length) throw new IllegalArgumentException(); int index = this.elementSize; for (int i = 0, l = this.values.length; i < l && index > 0; i++) if (this.values[i] != null) copy[--index] = this.values[i]; }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSet.java
public void asArray(Object[] copy) { if (this.elementSize != copy.length) throw new IllegalArgumentException(); int index = this.elementSize; for (int i = 0, l = this.values.length; i < l && index > 0; i++) if (this.values[i] != null) copy[--index] = this.values[i]; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public final void markAsTracked(ASTNode node, TextEditGroup editGroup) { if (getTrackedNodeData(node) != null) { throw new IllegalArgumentException("Node is already marked as tracked"); //$NON-NLS-1$ } setTrackedNodeData(node, editGroup); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public final CopySourceInfo createRangeCopy(ASTNode parent, StructuralPropertyDescriptor childProperty, ASTNode first, ASTNode last, boolean isMove, ASTNode internalPlaceholder, ASTNode replacingNode, TextEditGroup editGroup) { CopySourceInfo copyInfo= createCopySourceInfo(null, internalPlaceholder, isMove); internalPlaceholder.setProperty(INTERNAL_PLACEHOLDER_PROPERTY, internalPlaceholder); NodeRangeInfo copyRangeInfo= new NodeRangeInfo(parent, childProperty, first, last, copyInfo, replacingNode, editGroup); ListRewriteEvent listEvent= getListEvent(parent, childProperty, true); int indexFirst= listEvent.getIndex(first, ListRewriteEvent.OLD); if (indexFirst == -1) { throw new IllegalArgumentException("Start node is not a original child of the given list"); //$NON-NLS-1$ } int indexLast= listEvent.getIndex(last, ListRewriteEvent.OLD); if (indexLast == -1) { throw new IllegalArgumentException("End node is not a original child of the given list"); //$NON-NLS-1$ } if (indexFirst > indexLast) { throw new IllegalArgumentException("Start node must be before end node"); //$NON-NLS-1$ } if (this.nodeRangeInfos == null) { this.nodeRangeInfos= new HashMap(); } PropertyLocation loc= new PropertyLocation(parent, childProperty); List innerList= (List) this.nodeRangeInfos.get(loc); if (innerList == null) { innerList= new ArrayList(2); this.nodeRangeInfos.put(loc, innerList); } else { assertNoOverlap(listEvent, indexFirst, indexLast, innerList); } innerList.add(copyRangeInfo); return copyInfo; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void assertNoOverlap(ListRewriteEvent listEvent, int indexFirst, int indexLast, List innerList) { for (Iterator iter= innerList.iterator(); iter.hasNext();) { NodeRangeInfo curr= (NodeRangeInfo) iter.next(); int currStart= listEvent.getIndex(curr.getStartNode(), ListRewriteEvent.BOTH); int currEnd= listEvent.getIndex(curr.getEndNode(), ListRewriteEvent.BOTH); if (currStart < indexFirst && currEnd < indexLast && currEnd >= indexFirst || currStart > indexFirst && currStart <= currEnd && currEnd > indexLast) { throw new IllegalArgumentException("Range overlapps with an existing copy or move range"); //$NON-NLS-1$ } } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateIsListProperty(StructuralPropertyDescriptor property) { if (!property.isChildListProperty()) { String message= property.getId() + " is not a list property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateHasChildProperty(ASTNode parent, StructuralPropertyDescriptor property) { if (!parent.structuralPropertiesForType().contains(property)) { String message= Signature.getSimpleName(parent.getClass().getName()) + " has no property " + property.getId(); //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateIsNodeProperty(StructuralPropertyDescriptor property) { if (property.isChildListProperty()) { String message= property.getId() + " is not a node property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ListRewriteEvent.java
public RewriteEvent replaceEntry(ASTNode entry, ASTNode newEntry) { if (entry == null) { throw new IllegalArgumentException(); } List entries= getEntries(); int nEntries= entries.size(); for (int i= 0; i < nEntries; i++) { NodeRewriteEvent curr= (NodeRewriteEvent) entries.get(i); if (curr.getOriginalValue() == entry || curr.getNewValue() == entry) { curr.setNewValue(newEntry); if (curr.getNewValue() == null && curr.getOriginalValue() == null) { // removed an inserted node entries.remove(i); return null; } return curr; } } return null; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { Document doc= new Document(string); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { int start= this.fOffset; int end= start + this.fLength; if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) { this.fPosition.offset= end; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setOperator(Assignment.Operator assignmentOperator) { if (assignmentOperator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.assignmentOperator = assignmentOperator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setLeftHandSide(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an Assignment may occur inside a Expression - must check cycles ASTNode oldChild = this.leftHandSide; preReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY); this.leftHandSide = expression; postReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setRightHandSide(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an Assignment may occur inside a Expression - must check cycles ASTNode oldChild = this.rightHandSide; preReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY); this.rightHandSide = expression; postReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setName(SimpleName variableName) { if (variableName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.variableName; preReplaceChild(oldChild, variableName, NAME_PROPERTY); this.variableName = variableName; postReplaceChild(oldChild, variableName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
public void setName(SimpleName methodName) { if (methodName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, methodName, NAME_PROPERTY); this.methodName = methodName; postReplaceChild(oldChild, methodName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
void internalSetReturnType(Type type) { supportedOnlyIn2(); if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.returnType; preReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY); this.returnType = type; postReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedName.java
public void setQualifier(Name qualifier) { if (qualifier == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.qualifier; preReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY); this.qualifier = qualifier; postReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedName.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SimpleType.java
public void setName(Name typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, NAME_PROPERTY); this.typeName = typeName; postReplaceChild(oldChild, typeName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void remove(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } RewriteEvent event= getEvent().removeEntry(node); if (editGroup != null) { getRewriteStore().setEventEditGroup(event, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } RewriteEvent event= getEvent().replaceEntry(node, replacement); if (editGroup != null) { getRewriteStore().setEventEditGroup(event, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertAfter(ASTNode node, ASTNode previousElement, TextEditGroup editGroup) { if (node == null || previousElement == null) { throw new IllegalArgumentException(); } int index= getEvent().getIndex(previousElement, ListRewriteEvent.BOTH); if (index == -1) { throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$ } internalInsertAt(node, index + 1, true, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertBefore(ASTNode node, ASTNode nextElement, TextEditGroup editGroup) { if (node == null || nextElement == null) { throw new IllegalArgumentException(); } int index= getEvent().getIndex(nextElement, ListRewriteEvent.BOTH); if (index == -1) { throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$ } internalInsertAt(node, index, false, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertFirst(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, 0, false, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertLast(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, -1, true, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertAt(ASTNode node, int index, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, index, isInsertBoundToPreviousByDefault(node), editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
private ASTNode createTargetNode(ASTNode first, ASTNode last, boolean isMove, ASTNode replacingNode, TextEditGroup editGroup) { if (first == null || last == null) { throw new IllegalArgumentException(); } NodeInfoStore nodeStore= this.rewriter.getNodeStore(); ASTNode placeholder= nodeStore.newPlaceholderNode(first.getNodeType()); // revisit: could use list type if (placeholder == null) { throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + first.getClass().getName()); //$NON-NLS-1$ } Block internalPlaceHolder= nodeStore.createCollapsePlaceholder(); CopySourceInfo info= getRewriteStore().createRangeCopy(this.parent, this.childProperty, first, last, isMove, internalPlaceHolder, replacingNode, editGroup); nodeStore.markAsCopyTarget(placeholder, info); return placeholder; }
// 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/ImportRewrite.java
public static ImportRewrite create(CompilationUnit astRoot, boolean restoreExistingImports) { if (astRoot == null) { throw new IllegalArgumentException("AST must not be null"); //$NON-NLS-1$ } ITypeRoot typeRoot = astRoot.getTypeRoot(); if (!(typeRoot instanceof ICompilationUnit)) { throw new IllegalArgumentException("AST must have been constructed from a Java element"); //$NON-NLS-1$ } List existingImport= null; if (restoreExistingImports) { existingImport= new ArrayList(); List imports= astRoot.imports(); for (int i= 0; i < imports.size(); i++) { ImportDeclaration curr= (ImportDeclaration) imports.get(i); StringBuffer buf= new StringBuffer(); buf.append(curr.isStatic() ? STATIC_PREFIX : NORMAL_PREFIX).append(curr.getName().getFullyQualifiedName()); if (curr.isOnDemand()) { if (buf.length() > 1) buf.append('.'); buf.append('*'); } existingImport.add(buf.toString()); } } return new ImportRewrite((ICompilationUnit) typeRoot, astRoot, existingImport); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setImportOrder(String[] order) { if (order == null) throw new IllegalArgumentException("Order must not be null"); //$NON-NLS-1$ this.importOrder= order; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setOnDemandImportThreshold(int threshold) { if (threshold <= 0) throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$ this.importOnDemandThreshold= threshold; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setStaticOnDemandImportThreshold(int threshold) { if (threshold <= 0) throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$ this.staticImportOnDemandThreshold= threshold; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public Type addImportFromSignature(String typeSig, AST ast, ImportRewriteContext context) { if (typeSig == null || typeSig.length() == 0) { throw new IllegalArgumentException("Invalid type signature: empty or null"); //$NON-NLS-1$ } int sigKind= Signature.getTypeSignatureKind(typeSig); switch (sigKind) { case Signature.BASE_TYPE_SIGNATURE: return ast.newPrimitiveType(PrimitiveType.toCode(Signature.toString(typeSig))); case Signature.ARRAY_TYPE_SIGNATURE: Type elementType= addImportFromSignature(Signature.getElementType(typeSig), ast, context); return ast.newArrayType(elementType, Signature.getArrayCount(typeSig)); case Signature.CLASS_TYPE_SIGNATURE: String erasureSig= Signature.getTypeErasure(typeSig); String erasureName= Signature.toString(erasureSig); if (erasureSig.charAt(0) == Signature.C_RESOLVED) { erasureName= internalAddImport(erasureName, context); } Type baseType= ast.newSimpleType(ast.newName(erasureName)); String[] typeArguments= Signature.getTypeArguments(typeSig); if (typeArguments.length > 0) { ParameterizedType type= ast.newParameterizedType(baseType); List argNodes= type.typeArguments(); for (int i= 0; i < typeArguments.length; i++) { String curr= typeArguments[i]; if (containsNestedCapture(curr)) { // see bug 103044 argNodes.add(ast.newWildcardType()); } else { argNodes.add(addImportFromSignature(curr, ast, context)); } } return type; } return baseType; case Signature.TYPE_VARIABLE_SIGNATURE: return ast.newSimpleType(ast.newSimpleName(Signature.toString(typeSig))); case Signature.WILDCARD_TYPE_SIGNATURE: WildcardType wildcardType= ast.newWildcardType(); char ch= typeSig.charAt(0); if (ch != Signature.C_STAR) { Type bound= addImportFromSignature(typeSig.substring(1), ast, context); wildcardType.setBound(bound, ch == Signature.C_EXTENDS); } return wildcardType; case Signature.CAPTURE_TYPE_SIGNATURE: return addImportFromSignature(typeSig.substring(1), ast, context); default: throw new IllegalArgumentException("Unknown type signature kind: " + typeSig); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public String addStaticImport(IBinding binding, ImportRewriteContext context) { if (Modifier.isStatic(binding.getModifiers())) { if (binding instanceof IVariableBinding) { IVariableBinding variableBinding= (IVariableBinding) binding; if (variableBinding.isField()) { ITypeBinding declaringType= variableBinding.getDeclaringClass(); return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), true, context); } } else if (binding instanceof IMethodBinding) { ITypeBinding declaringType= ((IMethodBinding) binding).getDeclaringClass(); return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), false, context); } } throw new IllegalArgumentException("Binding must be a static field or method."); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException { if (document == null) { throw new IllegalArgumentException(); } ASTNode rootNode= getRootNode(); if (rootNode == null) { return new MultiTextEdit(); // no changes } char[] content= document.get().toCharArray(); LineInformation lineInfo= LineInformation.create(document); String lineDelim= TextUtilities.getDefaultLineDelimiter(document); ASTNode astRoot= rootNode.getRoot(); List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null; Map currentOptions = options == null ? JavaCore.getOptions() : options; return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData()); }
// 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/rewrite/ASTRewrite.java
public final void remove(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } StructuralPropertyDescriptor property; ASTNode parent; if (RewriteEventStore.isNewNode(node)) { // remove a new node, bug 164862 PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW); if (location != null) { property= location.getProperty(); parent= location.getParent(); } else { throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ } } else { property= node.getLocationInParent(); parent= node.getParent(); } if (property.isChildListProperty()) { getListRewrite(parent, (ChildListPropertyDescriptor) property).remove(node, editGroup); } else { set(parent, property, null, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } StructuralPropertyDescriptor property; ASTNode parent; if (RewriteEventStore.isNewNode(node)) { // replace a new node, bug 164862 PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW); if (location != null) { property= location.getProperty(); parent= location.getParent(); } else { throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ } } else { property= node.getLocationInParent(); parent= node.getParent(); } if (property.isChildListProperty()) { getListRewrite(parent, (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup); } else { set(parent, property, replacement, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void set(ASTNode node, StructuralPropertyDescriptor property, Object value, TextEditGroup editGroup) { if (node == null || property == null) { throw new IllegalArgumentException(); } validateIsCorrectAST(node); validatePropertyType(property, value); validateIsPropertyOfNode(property, node); NodeRewriteEvent nodeEvent= this.eventStore.getNodeEvent(node, property, true); nodeEvent.setNewValue(value); if (editGroup != null) { this.eventStore.setEventEditGroup(nodeEvent, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public Object get(ASTNode node, StructuralPropertyDescriptor property) { if (node == null || property == null) { throw new IllegalArgumentException(); } if (property.isChildListProperty()) { throw new IllegalArgumentException("Use the list rewriter to access nodes in a list"); //$NON-NLS-1$ } return this.eventStore.getNewValue(node, property); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor property) { if (node == null || property == null) { throw new IllegalArgumentException(); } validateIsCorrectAST(node); validateIsListProperty(property); validateIsPropertyOfNode(property, node); return new ListRewrite(this, node, property); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final Object getProperty(String propertyName) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // rewrite has no properties at all return null; } if (this.property1 instanceof String) { // rewrite has only a single property if (propertyName.equals(this.property1)) { return this.property2; } else { return null; } } // otherwise rewrite has table of properties Map m = (Map) this.property1; return m.get(propertyName); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ITrackedNodePosition track(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } TextEditGroup group= this.eventStore.getTrackedNodeData(node); if (group == null) { group= new TextEditGroup("internal"); //$NON-NLS-1$ this.eventStore.setTrackedNodeData(node, group); } return new TrackedNodePosition(group, node); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsExistingNode(ASTNode node) { if (node.getStartPosition() == -1) { throw new IllegalArgumentException("Node is not an existing node"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsCorrectAST(ASTNode node) { if (node.getAST() != getAST()) { throw new IllegalArgumentException("Node is not inside the AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsListProperty(StructuralPropertyDescriptor property) { if (!property.isChildListProperty()) { String message= property.getId() + " is not a list property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsPropertyOfNode(StructuralPropertyDescriptor property, ASTNode node) { if (!property.getNodeClass().isInstance(node)) { String message= property.getId() + " is not a property of type " + node.getClass().getName(); //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validatePropertyType(StructuralPropertyDescriptor prop, Object node) { if (prop.isChildListProperty()) { String message= "Can not modify a list property, use a list rewriter"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ASTNode createStringPlaceholder(String code, int nodeType) { if (code == null) { throw new IllegalArgumentException(); } ASTNode placeholder= getNodeStore().newPlaceholderNode(nodeType); if (placeholder == null) { throw new IllegalArgumentException("String placeholder is not supported for type" + nodeType); //$NON-NLS-1$ } getNodeStore().markAsStringPlaceholder(placeholder, code); return placeholder; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ASTNode createGroupNode(ASTNode[] targetNodes) { if (targetNodes == null || targetNodes.length == 0) { throw new IllegalArgumentException(); } Block res= getNodeStore().createCollapsePlaceholder(); ListRewrite listRewrite= getListRewrite(res, Block.STATEMENTS_PROPERTY); for (int i= 0; i < targetNodes.length; i++) { listRewrite.insertLast(targetNodes[i], null); } return res; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private ASTNode createTargetNode(ASTNode node, boolean isMove) { if (node == null) { throw new IllegalArgumentException(); } validateIsExistingNode(node); validateIsCorrectAST(node); CopySourceInfo info= getRewriteEventStore().markAsCopySource(node.getParent(), node.getLocationInParent(), node, isMove); ASTNode placeholder= getNodeStore().newPlaceholderNode(node.getNodeType()); if (placeholder == null) { throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + node.getClass().getName()); //$NON-NLS-1$ } getNodeStore().markAsCopyTarget(placeholder, info); return placeholder; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void setProperty(String propertyName, Object data) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // rewrite has no properties at all if (data == null) { // rewrite already knows this return; } // rewrite gets its fist property this.property1 = propertyName; this.property2 = data; return; } if (this.property1 instanceof String) { // rewrite has only a single property if (propertyName.equals(this.property1)) { // we're in luck if (data == null) { // just delete last property this.property1 = null; this.property2 = null; } else { this.property2 = data; } return; } if (data == null) { // we already know this return; } // rewrite already has one property - getting its second // convert to more flexible representation Map m = new HashMap(3); m.put(this.property1, this.property2); m.put(propertyName, data); this.property1 = m; this.property2 = null; return; } // rewrite has two or more properties Map m = (Map) this.property1; if (data == null) { m.remove(propertyName); // check for just one property left if (m.size() == 1) { // convert to more efficient representation Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]); this.property1 = entries[0].getKey(); this.property2 = entries[0].getValue(); } return; } else { m.put(propertyName, data); // still has two or more properties return; } }
// in dom/org/eclipse/jdt/core/dom/Statement.java
public void setLeadingComment(String comment) { if (comment != null) { char[] source = comment.toCharArray(); Scanner scanner = this.ast.scanner; scanner.resetTo(0, source.length); scanner.setSource(source); try { int token; boolean onlyOneComment = false; while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : case TerminalTokens.TokenNameCOMMENT_LINE : if (onlyOneComment) { throw new IllegalArgumentException(); } onlyOneComment = true; break; default: onlyOneComment = false; } } if (!onlyOneComment) { throw new IllegalArgumentException(); } } catch (InvalidInputException e) { throw new IllegalArgumentException(); } } // we do not consider the obsolete comment as a structureal property // but we protect them nevertheless checkModifiable(); this.optionalLeadingComment = comment; }
// in dom/org/eclipse/jdt/core/dom/FieldAccess.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/FieldAccess.java
public void setName(SimpleName fieldName) { if (fieldName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.fieldName; preReplaceChild(oldChild, fieldName, NAME_PROPERTY); this.fieldName = fieldName; postReplaceChild(oldChild, fieldName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ParenthesizedExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeDeclarationStatement.java
public void setDeclaration(AbstractTypeDeclaration decl) { if (decl == null) { throw new IllegalArgumentException(); } // a TypeDeclarationStatement may occur inside an // TypeDeclaration - must check cycles ASTNode oldChild = this.typeDecl; ChildPropertyDescriptor typeDeclProperty = typeDeclProperty(); preReplaceChild(oldChild, decl, typeDeclProperty); this.typeDecl= decl; postReplaceChild(oldChild, decl, typeDeclProperty); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static Class nodeClassForType(int nodeType) { switch (nodeType) { case ANNOTATION_TYPE_DECLARATION : return AnnotationTypeDeclaration.class; case ANNOTATION_TYPE_MEMBER_DECLARATION : return AnnotationTypeMemberDeclaration.class; case ANONYMOUS_CLASS_DECLARATION : return AnonymousClassDeclaration.class; case ARRAY_ACCESS : return ArrayAccess.class; case ARRAY_CREATION : return ArrayCreation.class; case ARRAY_INITIALIZER : return ArrayInitializer.class; case ARRAY_TYPE : return ArrayType.class; case ASSERT_STATEMENT : return AssertStatement.class; case ASSIGNMENT : return Assignment.class; case BLOCK : return Block.class; case BLOCK_COMMENT : return BlockComment.class; case BOOLEAN_LITERAL : return BooleanLiteral.class; case BREAK_STATEMENT : return BreakStatement.class; case CAST_EXPRESSION : return CastExpression.class; case CATCH_CLAUSE : return CatchClause.class; case CHARACTER_LITERAL : return CharacterLiteral.class; case CLASS_INSTANCE_CREATION : return ClassInstanceCreation.class; case COMPILATION_UNIT : return CompilationUnit.class; case CONDITIONAL_EXPRESSION : return ConditionalExpression.class; case CONSTRUCTOR_INVOCATION : return ConstructorInvocation.class; case CONTINUE_STATEMENT : return ContinueStatement.class; case UNION_TYPE : return UnionType.class; case DO_STATEMENT : return DoStatement.class; case EMPTY_STATEMENT : return EmptyStatement.class; case ENHANCED_FOR_STATEMENT : return EnhancedForStatement.class; case ENUM_CONSTANT_DECLARATION : return EnumConstantDeclaration.class; case ENUM_DECLARATION : return EnumDeclaration.class; case EXPRESSION_STATEMENT : return ExpressionStatement.class; case FIELD_ACCESS : return FieldAccess.class; case FIELD_DECLARATION : return FieldDeclaration.class; case FOR_STATEMENT : return ForStatement.class; case IF_STATEMENT : return IfStatement.class; case IMPORT_DECLARATION : return ImportDeclaration.class; case INFIX_EXPRESSION : return InfixExpression.class; case INITIALIZER : return Initializer.class; case INSTANCEOF_EXPRESSION : return InstanceofExpression.class; case JAVADOC : return Javadoc.class; case LABELED_STATEMENT : return LabeledStatement.class; case LINE_COMMENT : return LineComment.class; case MARKER_ANNOTATION : return MarkerAnnotation.class; case MEMBER_REF : return MemberRef.class; case MEMBER_VALUE_PAIR : return MemberValuePair.class; case METHOD_DECLARATION : return MethodDeclaration.class; case METHOD_INVOCATION : return MethodInvocation.class; case METHOD_REF : return MethodRef.class; case METHOD_REF_PARAMETER : return MethodRefParameter.class; case MODIFIER : return Modifier.class; case NORMAL_ANNOTATION : return NormalAnnotation.class; case NULL_LITERAL : return NullLiteral.class; case NUMBER_LITERAL : return NumberLiteral.class; case PACKAGE_DECLARATION : return PackageDeclaration.class; case PARAMETERIZED_TYPE : return ParameterizedType.class; case PARENTHESIZED_EXPRESSION : return ParenthesizedExpression.class; case POSTFIX_EXPRESSION : return PostfixExpression.class; case PREFIX_EXPRESSION : return PrefixExpression.class; case PRIMITIVE_TYPE : return PrimitiveType.class; case QUALIFIED_NAME : return QualifiedName.class; case QUALIFIED_TYPE : return QualifiedType.class; case RETURN_STATEMENT : return ReturnStatement.class; case SIMPLE_NAME : return SimpleName.class; case SIMPLE_TYPE : return SimpleType.class; case SINGLE_MEMBER_ANNOTATION : return SingleMemberAnnotation.class; case SINGLE_VARIABLE_DECLARATION : return SingleVariableDeclaration.class; case STRING_LITERAL : return StringLiteral.class; case SUPER_CONSTRUCTOR_INVOCATION : return SuperConstructorInvocation.class; case SUPER_FIELD_ACCESS : return SuperFieldAccess.class; case SUPER_METHOD_INVOCATION : return SuperMethodInvocation.class; case SWITCH_CASE: return SwitchCase.class; case SWITCH_STATEMENT : return SwitchStatement.class; case SYNCHRONIZED_STATEMENT : return SynchronizedStatement.class; case TAG_ELEMENT : return TagElement.class; case TEXT_ELEMENT : return TextElement.class; case THIS_EXPRESSION : return ThisExpression.class; case THROW_STATEMENT : return ThrowStatement.class; case TRY_STATEMENT : return TryStatement.class; case TYPE_DECLARATION : return TypeDeclaration.class; case TYPE_DECLARATION_STATEMENT : return TypeDeclarationStatement.class; case TYPE_LITERAL : return TypeLiteral.class; case TYPE_PARAMETER : return TypeParameter.class; case VARIABLE_DECLARATION_EXPRESSION : return VariableDeclarationExpression.class; case VARIABLE_DECLARATION_FRAGMENT : return VariableDeclarationFragment.class; case VARIABLE_DECLARATION_STATEMENT : return VariableDeclarationStatement.class; case WHILE_STATEMENT : return WhileStatement.class; case WILDCARD_TYPE : return WildcardType.class; } throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public Object set(int index, Object element) { if (element == null) { throw new IllegalArgumentException(); } if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // delink old child from parent, and link new child to parent ASTNode newChild = (ASTNode) element; ASTNode oldChild = (ASTNode) this.store.get(index); if (oldChild == newChild) { return oldChild; } if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType); ASTNode.this.ast.preReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor); Object result = this.store.set(index, newChild); // n.b. setParent will call ast.modifying() oldChild.setParent(null, null); newChild.setParent(ASTNode.this, this.propertyDescriptor); ASTNode.this.ast.postReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor); return result; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public void add(int index, Object element) { if (element == null) { throw new IllegalArgumentException(); } if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // link new child to parent ASTNode newChild = (ASTNode) element; ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType); ASTNode.this.ast.preAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor); this.store.add(index, element); updateCursors(index, +1); // n.b. setParent will call ast.modifying() newChild.setParent(ASTNode.this, this.propertyDescriptor); ASTNode.this.ast.postAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public Object remove(int index) { if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // delink old child from parent ASTNode oldChild = (ASTNode) this.store.get(index); if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } ASTNode.this.ast.preRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor); // n.b. setParent will call ast.modifying() oldChild.setParent(null, null); Object result = this.store.remove(index); updateCursors(index, -1); ASTNode.this.ast.postRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor); return result; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final Object getStructuralProperty(StructuralPropertyDescriptor property) { if (property instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor p = (SimplePropertyDescriptor) property; if (p.getValueType() == int.class) { int result = internalGetSetIntProperty(p, true, 0); return new Integer(result); } else if (p.getValueType() == boolean.class) { boolean result = internalGetSetBooleanProperty(p, true, false); return Boolean.valueOf(result); } else { return internalGetSetObjectProperty(p, true, null); } } if (property instanceof ChildPropertyDescriptor) { return internalGetSetChildProperty((ChildPropertyDescriptor) property, true, null); } if (property instanceof ChildListPropertyDescriptor) { return internalGetChildListProperty((ChildListPropertyDescriptor) property); } throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setStructuralProperty(StructuralPropertyDescriptor property, Object value) { if (property instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor p = (SimplePropertyDescriptor) property; if (p.getValueType() == int.class) { int arg = ((Integer) value).intValue(); internalGetSetIntProperty(p, false, arg); return; } else if (p.getValueType() == boolean.class) { boolean arg = ((Boolean) value).booleanValue(); internalGetSetBooleanProperty(p, false, arg); return; } else { if (value == null && p.isMandatory()) { throw new IllegalArgumentException(); } internalGetSetObjectProperty(p, false, value); return; } } if (property instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor p = (ChildPropertyDescriptor) property; ASTNode child = (ASTNode) value; if (child == null && p.isMandatory()) { throw new IllegalArgumentException(); } internalGetSetChildProperty(p, false, child); return; } if (property instanceof ChildListPropertyDescriptor) { throw new IllegalArgumentException("Cannot set the list of child list property"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void checkNewChild(ASTNode node, ASTNode newChild, boolean cycleCheck, Class nodeType) { if (newChild.ast != node.ast) { // new child is from a different AST throw new IllegalArgumentException(); } if (newChild.getParent() != null) { // new child currently has a different parent throw new IllegalArgumentException(); } if (cycleCheck && newChild == node.getRoot()) { // inserting new child would create a cycle throw new IllegalArgumentException(); } Class childClass = newChild.getClass(); if (nodeType != null && !nodeType.isAssignableFrom(childClass)) { // new child is not of the right type throw new ClassCastException(); } if ((newChild.typeAndFlags & PROTECT) != 0) { // new child node is protected => cannot be parented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void preReplaceChild(ASTNode oldChild, ASTNode newChild, ChildPropertyDescriptor property) { if ((this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } if (newChild != null) { checkNewChild(this, newChild, property.cycleRisk, null); } // delink old child from parent if (oldChild != null) { if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child node is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } if (newChild != null) { this.ast.preReplaceChildEvent(this, oldChild, newChild, property); } else { this.ast.preRemoveChildEvent(this, oldChild, property); } oldChild.setParent(null, null); } else { if(newChild != null) { this.ast.preAddChildEvent(this, newChild, property); } } // link new child to parent if (newChild != null) { newChild.setParent(this, property); // cannot notify postAddChildEvent until parent is linked to child too } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void preValueChange(SimplePropertyDescriptor property) { if ((this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot change valure of properties throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } this.ast.preValueChangeEvent(this, property); this.ast.modifying(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void checkModifiable() { if ((this.typeAndFlags & PROTECT) != 0) { throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } this.ast.modifying(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final Object getProperty(String propertyName) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // node has no properties at all return null; } if (this.property1 instanceof String) { // node has only a single property if (propertyName.equals(this.property1)) { return this.property2; } else { return null; } } // otherwise node has table of properties Map m = (Map) this.property1; return m.get(propertyName); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setProperty(String propertyName, Object data) { if (propertyName == null) { throw new IllegalArgumentException(); } // N.B. DO NOT CALL ast.modifying(); if (this.property1 == null) { // node has no properties at all if (data == null) { // we already know this return; } // node gets its fist property this.property1 = propertyName; this.property2 = data; return; } if (this.property1 instanceof String) { // node has only a single property if (propertyName.equals(this.property1)) { // we're in luck if (data == null) { // just deleted last property this.property1 = null; this.property2 = null; } else { this.property2 = data; } return; } if (data == null) { // we already know this return; } // node already has one property - getting its second // convert to more flexible representation Map m = new HashMap(3); m.put(this.property1, this.property2); m.put(propertyName, data); this.property1 = m; this.property2 = null; return; } // node has two or more properties Map m = (Map) this.property1; if (data == null) { m.remove(propertyName); // check for just one property left if (m.size() == 1) { // convert to more efficient representation Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]); this.property1 = entries[0].getKey(); this.property2 = entries[0].getValue(); } return; } else { m.put(propertyName, data); // still has two or more properties return; } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static ASTNode copySubtree(AST target, ASTNode node) { if (node == null) { return null; } if (target == null) { throw new IllegalArgumentException(); } if (target.apiLevel() != node.getAST().apiLevel()) { throw new UnsupportedOperationException(); } ASTNode newNode = node.clone(target); return newNode; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void accept(ASTVisitor visitor) { if (visitor == null) { throw new IllegalArgumentException(); } // begin with the generic pre-visit if (visitor.preVisit2(this)) { // dynamic dispatch to internal method for type-specific visit/endVisit accept0(visitor); } // end with the generic post-visit visitor.postVisit(this); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setSourceRange(int startPosition, int length) { if (startPosition >= 0 && length < 0) { throw new IllegalArgumentException(); } if (startPosition < 0 && length != 0) { throw new IllegalArgumentException(); } // source positions are not considered a structural property // but we protect them nevertheless checkModifiable(); this.startPosition = startPosition; this.length = length; }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
public void setIdentifier(String identifier) { // update internalSetIdentifier if this is changed if (identifier == null) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; long sourceLevel = scanner.sourceLevel; long complianceLevel = scanner.complianceLevel; try { scanner.sourceLevel = ClassFileConstants.JDK1_3; scanner.complianceLevel = ClassFileConstants.JDK1_5; char[] source = identifier.toCharArray(); scanner.setSource(source); final int length = source.length; scanner.resetTo(0, length - 1); try { int tokenType = scanner.scanIdentifier(); if (tokenType != TerminalTokens.TokenNameIdentifier) { throw new IllegalArgumentException(); } if (scanner.currentPosition != length) { // this is the case when there is only one identifier see 87849 throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } } finally { this.ast.scanner.sourceLevel = sourceLevel; this.ast.scanner.complianceLevel = complianceLevel; } preValueChange(IDENTIFIER_PROPERTY); this.identifier = identifier; postValueChange(IDENTIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static IBinding[] resolve( final IJavaElement[] elements, int apiLevel, Map compilerOptions, IJavaProject javaProject, WorkingCopyOwner owner, int flags, IProgressMonitor monitor) { final int length = elements.length; final HashMap sourceElementPositions = new HashMap(); // a map from ICompilationUnit to int[] (positions in elements) int cuNumber = 0; final HashtableOfObjectToInt binaryElementPositions = new HashtableOfObjectToInt(); // a map from String (binding key) to int (position in elements) for (int i = 0; i < length; i++) { IJavaElement element = elements[i]; if (!(element instanceof SourceRefElement)) throw new IllegalStateException(element + " is not part of a compilation unit or class file"); //$NON-NLS-1$ Object cu = element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { // source member IntArrayList intList = (IntArrayList) sourceElementPositions.get(cu); if (intList == null) { sourceElementPositions.put(cu, intList = new IntArrayList()); cuNumber++; } intList.add(i); } else { // binary member try { String key = ((BinaryMember) element).getKey(true/*open to get resolved info*/); binaryElementPositions.put(key, i); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } } } ICompilationUnit[] cus = new ICompilationUnit[cuNumber]; sourceElementPositions.keySet().toArray(cus); int bindingKeyNumber = binaryElementPositions.size(); String[] bindingKeys = new String[bindingKeyNumber]; binaryElementPositions.keysToArray(bindingKeys); class Requestor extends ASTRequestor { IBinding[] bindings = new IBinding[length]; public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } } public void acceptBinding(String bindingKey, IBinding binding) { int index = binaryElementPositions.get(bindingKey); this.bindings[index] = binding; } } Requestor requestor = new Requestor(); resolve(cus, bindingKeys, requestor, apiLevel, compilerOptions, javaProject, owner, flags, monitor); return requestor.bindings; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
public void setComment(String docComment) { supportedOnlyIn2(); if (docComment == null) { throw new IllegalArgumentException(); } char[] source = docComment.toCharArray(); Scanner scanner = this.ast.scanner; scanner.resetTo(0, source.length); scanner.setSource(source); try { int token; boolean onlyOneComment = false; while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (onlyOneComment) { throw new IllegalArgumentException(); } onlyOneComment = true; break; default: onlyOneComment = false; } } if (!onlyOneComment) { throw new IllegalArgumentException(); } } catch (InvalidInputException e) { throw new IllegalArgumentException(); } preValueChange(COMMENT_PROPERTY); this.comment = docComment; postValueChange(COMMENT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ThrowStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CastExpression.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CastExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
public void setEscapedValue(String value) { // check setInternalEscapedValue(String) if this method is changed if (value == null) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = value.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameCharacterLiteral: break; default: throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } preValueChange(ESCAPED_VALUE_PROPERTY); this.escapedValue = value; postValueChange(ESCAPED_VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
public char charValue() { Scanner scanner = this.ast.scanner; char[] source = this.escapedValue.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); int firstChar = scanner.getNextChar(); int secondChar = scanner.getNextChar(); if (firstChar == -1 || firstChar != '\'') { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } char value = (char) secondChar; int nextChar = scanner.getNextChar(); if (secondChar == '\\') { if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } switch(nextChar) { case 'b' : value = '\b'; break; case 't' : value = '\t'; break; case 'n' : value = '\n'; break; case 'f' : value = '\f'; break; case 'r' : value = '\r'; break; case '\"': value = '\"'; break; case '\'': value = '\''; break; case '\\': value = '\\'; break; default : //octal (well-formed: ended by a ' ) try { if (ScannerHelper.isDigit((char) nextChar)) { int number = ScannerHelper.getNumericValue((char) nextChar); nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } if (nextChar != '\'') { if (!ScannerHelper.isDigit((char) nextChar)) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } number = (number * 8) + ScannerHelper.getNumericValue((char) nextChar); nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } if (nextChar != '\'') { if (!ScannerHelper.isDigit((char) nextChar)) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } number = (number * 8) + ScannerHelper.getNumericValue((char) nextChar); } } return (char) number; } else { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } if (nextChar == -1 || nextChar != '\'') { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } return value; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
public ITypeBinding createArrayType(int dimension) { int realDimensions = dimension; realDimensions += getDimensions(); if (realDimensions < 1 || realDimensions > 255) { throw new IllegalArgumentException(); } return this.resolver.resolveArrayType(this, dimension); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int getExtendedLength(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { // fall back: use best info available return node.getLength(); } else { return this.commentMapper.getExtendedLength(node); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int getExtendedStartPosition(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { // fall back: use best info available return node.getStartPosition(); } else { return this.commentMapper.getExtendedStartPosition(node); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int firstLeadingCommentIndex(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { return -1; } return this.commentMapper.firstLeadingCommentIndex(node); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int lastTrailingCommentIndex(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { return -1; } return this.commentMapper.lastTrailingCommentIndex(node); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setCommentTable(Comment[] commentTable) { // double check table to ensure that all comments have // source positions and are in strictly increasing order if (commentTable == null) { this.optionalCommentList = null; this.optionalCommentTable = null; } else { int nextAvailablePosition = 0; for (int i = 0; i < commentTable.length; i++) { Comment comment = commentTable[i]; if (comment == null) { throw new IllegalArgumentException(); } int start = comment.getStartPosition(); int length = comment.getLength(); if (start < 0 || length < 0 || start < nextAvailablePosition) { throw new IllegalArgumentException(); } nextAvailablePosition = comment.getStartPosition() + comment.getLength(); } this.optionalCommentTable = commentTable; List commentList = Arrays.asList(commentTable); // protect the list from further modification this.optionalCommentList = Collections.unmodifiableList(commentList); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setProblems(IProblem[] problems) { if (problems == null) { throw new IllegalArgumentException(); } this.problems = problems; }
// in dom/org/eclipse/jdt/core/dom/Annotation.java
public void setTypeName(Name typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ChildPropertyDescriptor p = internalTypeNameProperty(); ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, p); this.typeName = typeName; postReplaceChild(oldChild, typeName, p); }
// in dom/org/eclipse/jdt/core/dom/ArrayAccess.java
public void setArray(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an ArrayAccess may occur inside an Expression // must check cycles ASTNode oldChild = this.arrayExpression; preReplaceChild(oldChild, expression, ARRAY_PROPERTY); this.arrayExpression = expression; postReplaceChild(oldChild, expression, ARRAY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayAccess.java
public void setIndex(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an ArrayAccess may occur inside an Expression // must check cycles ASTNode oldChild = this.indexExpression; preReplaceChild(oldChild, expression, INDEX_PROPERTY); this.indexExpression = expression; postReplaceChild(oldChild, expression, INDEX_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SynchronizedStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SynchronizedStatement.java
public void setBody(Block block) { if (block == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, block, BODY_PROPERTY); this.body = block; postReplaceChild(oldChild, block, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayType.java
public void setComponentType(Type componentType) { if (componentType == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.componentType; preReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY); this.componentType = componentType; postReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
ITypeBinding resolveArrayType(ITypeBinding typeBinding, int dimensions) { if (typeBinding instanceof RecoveredTypeBinding) throw new IllegalArgumentException("Cannot be called on a recovered type binding"); //$NON-NLS-1$ ITypeBinding leafComponentType = typeBinding; int actualDimensions = dimensions; if (typeBinding.isArray()) { leafComponentType = typeBinding.getElementType(); actualDimensions += typeBinding.getDimensions(); } org.eclipse.jdt.internal.compiler.lookup.TypeBinding leafTypeBinding = null; if (leafComponentType.isPrimitive()) { String name = leafComponentType.getBinaryName(); switch(name.charAt(0)) { case 'I' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.INT; break; case 'B' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.BYTE; break; case 'Z' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.BOOLEAN; break; case 'C' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.CHAR; break; case 'J' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.LONG; break; case 'S' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.SHORT; break; case 'D' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.DOUBLE; break; case 'F' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.FLOAT; break; case 'V' : throw new IllegalArgumentException(); } } else { if (!(leafComponentType instanceof TypeBinding)) return null; leafTypeBinding = ((TypeBinding) leafComponentType).binding; } return this.getTypeBinding(lookupEnvironment().createArrayType(leafTypeBinding, actualDimensions)); }
// in dom/org/eclipse/jdt/core/dom/SwitchStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedType.java
public void setQualifier(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.qualifier; preReplaceChild(oldChild, type, QUALIFIER_PROPERTY); this.qualifier = type; postReplaceChild(oldChild, type, QUALIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedType.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayCreation.java
public void setType(ArrayType type) { if (type == null) { throw new IllegalArgumentException(); } // an ArrayCreation cannot occur inside a ArrayType - cycles not possible ASTNode oldChild = this.arrayType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.arrayType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ClassInstanceCreation.java
void internalSetName(Name name) { supportedOnlyIn2(); if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.typeName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ClassInstanceCreation.java
public void setType(Type type) { unsupportedIn2(); if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AssertStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an AssertStatement may occur inside an Expression - must check cycles ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit(char[] source) { if (source == null) { throw new IllegalArgumentException(); } ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(source); ASTNode result = c.createAST(null); return (CompilationUnit) result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( char[] source, String unitName, IJavaProject project) { if (source == null) { throw new IllegalArgumentException(); } ASTParser astParser = ASTParser.newParser(AST.JLS2); astParser.setSource(source); astParser.setUnitName(unitName); astParser.setProject(project); astParser.setResolveBindings(project != null); ASTNode result = astParser.createAST(null); return (CompilationUnit) result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( IClassFile classFile, boolean resolveBindings) { if (classFile == null) { throw new IllegalArgumentException(); } try { ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(classFile); c.setResolveBindings(resolveBindings); ASTNode result = c.createAST(null); return (CompilationUnit) result; } catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( ICompilationUnit unit, boolean resolveBindings) { try { ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(unit); c.setResolveBindings(resolveBindings); ASTNode result = c.createAST(null); return (CompilationUnit) result; } catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
public ASTNode createInstance(Class nodeClass) { if (nodeClass == null) { throw new IllegalArgumentException(); } try { // invoke constructor with signature Foo(AST) Constructor c = nodeClass.getDeclaredConstructor(AST_CLASS); Object result = c.newInstance(this.THIS_AST); return (ASTNode) result; } catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
Name internalNewName(String[] identifiers) { int count = identifiers.length; if (count == 0) { throw new IllegalArgumentException(); } final SimpleName simpleName = new SimpleName(this); simpleName.internalSetIdentifier(identifiers[0]); Name result = simpleName; for (int i = 1; i < count; i++) { SimpleName name = new SimpleName(this); name.internalSetIdentifier(identifiers[i]); result = newQualifiedName(result, name); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public ArrayType newArrayType(Type elementType, int dimensions) { if (elementType == null) { throw new IllegalArgumentException(); } if (dimensions < 1 || dimensions > 1000) { // we would blow our stacks anyway with a 1000-D array throw new IllegalArgumentException(); } ArrayType result = new ArrayType(this); result.setComponentType(elementType); for (int i = 2; i <= dimensions; i++) { result = newArrayType(result); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public FieldDeclaration newFieldDeclaration(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } FieldDeclaration result = new FieldDeclaration(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public Name newName(String qualifiedName) { StringTokenizer t = new StringTokenizer(qualifiedName, ".", true); //$NON-NLS-1$ Name result = null; // balance is # of name tokens - # of period tokens seen so far // initially 0; finally 1; should never drop < 0 or > 1 int balance = 0; while(t.hasMoreTokens()) { String s = t.nextToken(); if (s.indexOf('.') >= 0) { // this is a delimiter if (s.length() > 1) { // too many dots in a row throw new IllegalArgumentException(); } balance--; if (balance < 0) { throw new IllegalArgumentException(); } } else { // this is an identifier segment balance++; SimpleName name = newSimpleName(s); if (result == null) { result = name; } else { result = newQualifiedName(result, name); } } } if (balance != 1) { throw new IllegalArgumentException(); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public Name newName(String[] identifiers) { // update internalSetName(String[] if changed int count = identifiers.length; if (count == 0) { throw new IllegalArgumentException(); } Name result = newSimpleName(identifiers[0]); for (int i = 1; i < count; i++) { SimpleName name = newSimpleName(identifiers[i]); result = newQualifiedName(result, name); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public NumberLiteral newNumberLiteral(String literal) { if (literal == null) { throw new IllegalArgumentException(); } NumberLiteral result = new NumberLiteral(this); result.setToken(literal); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public SimpleName newSimpleName(String identifier) { if (identifier == null) { throw new IllegalArgumentException(); } SimpleName result = new SimpleName(this); result.setIdentifier(identifier); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public VariableDeclarationExpression newVariableDeclarationExpression(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } VariableDeclarationExpression result = new VariableDeclarationExpression(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public VariableDeclarationStatement newVariableDeclarationStatement(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } VariableDeclarationStatement result = new VariableDeclarationStatement(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void recordModifications(CompilationUnit root) { if(this.modificationCount != this.originalModificationCount) { throw new IllegalArgumentException("AST is already modified"); //$NON-NLS-1$ } else if(this.rewriter != null) { throw new IllegalArgumentException("AST modifications are already recorded"); //$NON-NLS-1$ } else if((root.getFlags() & ASTNode.PROTECT) != 0) { throw new IllegalArgumentException("Root node is unmodifiable"); //$NON-NLS-1$ } else if(root.getAST() != this) { throw new IllegalArgumentException("Root node is not owned by this ast"); //$NON-NLS-1$ } this.rewriter = new InternalASTRewrite(root); setEventHandler(this.rewriter); }
// in dom/org/eclipse/jdt/core/dom/AST.java
TextEdit rewrite(IDocument document, Map options) { if (document == null) { throw new IllegalArgumentException(); } if (this.rewriter == null) { throw new IllegalStateException("Modifications record is not enabled"); //$NON-NLS-1$ } return this.rewriter.rewriteAST(document, options); }
// in dom/org/eclipse/jdt/core/dom/AST.java
void setBindingResolver(BindingResolver resolver) { if (resolver == null) { throw new IllegalArgumentException(); } this.resolver = resolver; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void setEventHandler(NodeEventHandler eventHandler) { if (this.eventHandler == null) { throw new IllegalArgumentException(); } this.eventHandler = eventHandler; }
// in dom/org/eclipse/jdt/core/dom/AnnotationTypeMemberDeclaration.java
public void setName(SimpleName memberName) { if (memberName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberName; preReplaceChild(oldChild, memberName, NAME_PROPERTY); this.memberName = memberName; postReplaceChild(oldChild, memberName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AnnotationTypeMemberDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.memberType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TryStatement.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
public void setToken(String token) { // update internalSetToken(String) if this is changed if (token == null || token.length() == 0) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = token.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); scanner.tokenizeComments = false; scanner.tokenizeWhiteSpace = false; try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameDoubleLiteral: case TerminalTokens.TokenNameIntegerLiteral: case TerminalTokens.TokenNameFloatingPointLiteral: case TerminalTokens.TokenNameLongLiteral: break; case TerminalTokens.TokenNameMINUS : tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameDoubleLiteral: case TerminalTokens.TokenNameIntegerLiteral: case TerminalTokens.TokenNameFloatingPointLiteral: case TerminalTokens.TokenNameLongLiteral: break; default: throw new IllegalArgumentException("Invalid number literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$ } break; default: throw new IllegalArgumentException("Invalid number literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } finally { scanner.tokenizeComments = true; scanner.tokenizeWhiteSpace = true; } preValueChange(TOKEN_PROPERTY); this.tokenValue = token; postValueChange(TOKEN_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AbstractTypeDeclaration.java
public void setName(SimpleName typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ChildPropertyDescriptor p = internalNameProperty(); ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, p); this.typeName = typeName; postReplaceChild(oldChild, typeName, p); }
// in dom/org/eclipse/jdt/core/dom/PrefixExpression.java
public void setOperator(PrefixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PrefixExpression.java
public void setOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.operand; preReplaceChild(oldChild, expression, OPERAND_PROPERTY); this.operand = expression; postReplaceChild(oldChild, expression, OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberRef.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.memberName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InstanceofExpression.java
public void setLeftOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.leftOperand; preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); this.leftOperand = expression; postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InstanceofExpression.java
public void setRightOperand(Type referenceType) { if (referenceType == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.rightOperand; preReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY); this.rightOperand = referenceType; postReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleMemberAnnotation.java
public void setValue(Expression value) { if (value == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.value; preReplaceChild(oldChild, value, VALUE_PROPERTY); this.value = value; postReplaceChild(oldChild, value, VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/IfStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/IfStatement.java
public void setThenStatement(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.thenStatement; preReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY); this.thenStatement = statement; postReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/LabeledStatement.java
public void setLabel(SimpleName label) { if (label == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.labelName; preReplaceChild(oldChild, label, LABEL_PROPERTY); this.labelName = label; postReplaceChild(oldChild, label, LABEL_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/LabeledStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ExpressionStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodRef.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeLiteral.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SuperFieldAccess.java
public void setName(SimpleName fieldName) { if (fieldName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.fieldName; preReplaceChild(oldChild, fieldName, NAME_PROPERTY); this.fieldName = fieldName; postReplaceChild(oldChild, fieldName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setEnvironment(String[] classpathEntries, String[] sourcepathEntries, String[] encodings, boolean includeRunningVMBootclasspath) { this.classpaths = classpathEntries; this.sourcepaths = sourcepathEntries; this.sourcepathsEncodings = encodings; if (encodings != null) { if (sourcepathEntries == null || sourcepathEntries.length != encodings.length) { throw new IllegalArgumentException(); } } if (includeRunningVMBootclasspath) { this.bits |= CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH; } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setKind(int kind) { if ((kind != K_COMPILATION_UNIT) && (kind != K_CLASS_BODY_DECLARATIONS) && (kind != K_EXPRESSION) && (kind != K_STATEMENTS)) { throw new IllegalArgumentException(); } this.astKind = kind; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setSourceRange(int offset, int length) { if (offset < 0 || length < -1) { throw new IllegalArgumentException(); } this.sourceOffset = offset; this.sourceLength = length; }
// in dom/org/eclipse/jdt/core/dom/PackageDeclaration.java
public void setName(Name name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.packageName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.packageName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CatchClause.java
public void setException(SingleVariableDeclaration exception) { if (exception == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.exceptionDecl; preReplaceChild(oldChild, exception, EXCEPTION_PROPERTY); this.exceptionDecl= exception; postReplaceChild(oldChild, exception, EXCEPTION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CatchClause.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ForStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DoStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DoStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PrimitiveType.java
public void setPrimitiveTypeCode(PrimitiveType.Code typeCode) { if (typeCode == null) { throw new IllegalArgumentException(); } preValueChange(PRIMITIVE_TYPE_CODE_PROPERTY); this.typeCode = typeCode; postValueChange(PRIMITIVE_TYPE_CODE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodInvocation.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setOperator(InfixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setLeftOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.leftOperand; preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); this.leftOperand = expression; postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setRightOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.rightOperand; preReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY); this.rightOperand = expression; postReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberValuePair.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberValuePair.java
public void setValue(Expression value) { if (value == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.value; preReplaceChild(oldChild, value, VALUE_PROPERTY); this.value = value; postReplaceChild(oldChild, value, VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ParameterizedType.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/WhileStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/WhileStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TextElement.java
public void setText(String text) { if (text == null) { throw new IllegalArgumentException(); } if (text.indexOf("*/") > 0) { //$NON-NLS-1$ throw new IllegalArgumentException(); } preValueChange(TEXT_PROPERTY); this.text = text; postValueChange(TEXT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/FieldDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.conditionExpression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.conditionExpression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setThenExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.thenExpression; preReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY); this.thenExpression = expression; postReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setElseExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.elseExpression; preReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY); this.elseExpression = expression; postReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationFragment.java
public void setName(SimpleName variableName) { if (variableName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.variableName; preReplaceChild(oldChild, variableName, NAME_PROPERTY); this.variableName = variableName; postReplaceChild(oldChild, variableName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationFragment.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SuperMethodInvocation.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationStatement.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public void setEscapedValue(String token) { // update internalSetEscapedValue(String) if this is changed if (token == null) { throw new IllegalArgumentException("Token cannot be null"); //$NON-NLS-1$ } Scanner scanner = this.ast.scanner; char[] source = token.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameStringLiteral: break; default: throw new IllegalArgumentException("Invalid string literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$ } } catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ } preValueChange(ESCAPED_VALUE_PROPERTY); this.escapedValue = token; postValueChange(ESCAPED_VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public String getLiteralValue() { String s = getEscapedValue(); int len = s.length(); if (len < 2 || s.charAt(0) != '\"' || s.charAt(len-1) != '\"' ) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = s.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameStringLiteral: return scanner.getCurrentStringLiteral(); default: throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public void setLiteralValue(String value) { if (value == null) { throw new IllegalArgumentException(); } int len = value.length(); StringBuffer b = new StringBuffer(len + 2); b.append("\""); // opening delimiter //$NON-NLS-1$ for (int i = 0; i < len; i++) { char c = value.charAt(i); switch(c) { case '\b' : b.append("\\b"); //$NON-NLS-1$ break; case '\t' : b.append("\\t"); //$NON-NLS-1$ break; case '\n' : b.append("\\n"); //$NON-NLS-1$ break; case '\f' : b.append("\\f"); //$NON-NLS-1$ break; case '\r' : b.append("\\r"); //$NON-NLS-1$ break; case '\"': b.append("\\\""); //$NON-NLS-1$ break; case '\\': b.append("\\\\"); //$NON-NLS-1$ break; case '\0' : b.append("\\0"); //$NON-NLS-1$ break; case '\1' : b.append("\\1"); //$NON-NLS-1$ break; case '\2' : b.append("\\2"); //$NON-NLS-1$ break; case '\3' : b.append("\\3"); //$NON-NLS-1$ break; case '\4' : b.append("\\4"); //$NON-NLS-1$ break; case '\5' : b.append("\\5"); //$NON-NLS-1$ break; case '\6' : b.append("\\6"); //$NON-NLS-1$ break; case '\7' : b.append("\\7"); //$NON-NLS-1$ break; default: b.append(c); } } b.append("\""); // closing delimiter //$NON-NLS-1$ setEscapedValue(b.toString()); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setParameter(SingleVariableDeclaration parameter) { if (parameter == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.parameter; preReplaceChild(oldChild, parameter, PARAMETER_PROPERTY); this.parameter = parameter; postReplaceChild(oldChild, parameter, PARAMETER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeParameter.java
public void setName(SimpleName typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeVariableName; preReplaceChild(oldChild, typeName, NAME_PROPERTY); this.typeVariableName = typeName; postReplaceChild(oldChild, typeName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PostfixExpression.java
public void setOperator(PostfixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PostfixExpression.java
public void setOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.operand; preReplaceChild(oldChild, expression, OPERAND_PROPERTY); this.operand = expression; postReplaceChild(oldChild, expression, OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Modifier.java
public void setKeyword(ModifierKeyword modifierKeyord) { if (modifierKeyord == null) { throw new IllegalArgumentException(); } preValueChange(KEYWORD_PROPERTY); this.modifierKeyword = modifierKeyord; postValueChange(KEYWORD_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnumConstantDeclaration.java
public void setName(SimpleName constantName) { if (constantName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.constantName; preReplaceChild(oldChild, constantName, NAME_PROPERTY); this.constantName = constantName; postReplaceChild(oldChild, constantName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationExpression.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodRefParameter.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Initializer.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ImportDeclaration.java
public void setName(Name name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.importName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.importName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
30
              
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
52
              
// in model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java
public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException { if(newLoadFactor <= 1.0 && newLoadFactor > 0.0) this.loadFactor = newLoadFactor; else throw new IllegalArgumentException(Messages.cache_invalidLoadFactor); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getImport(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getPackageDeclaration(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { return ((IType)parent).getField(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { if (isVariableDeclarator()) { expand(); } super.insertSibling(sibling); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); setTypeAltered(true); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setType(String typeName) throws IllegalArgumentException { if (typeName == null) { throw new IllegalArgumentException(Messages.element_nullType); } becomeDetailed(); expand(); fragment(); setTypeAltered(true); setNameAltered(true); this.fType= typeName; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void addSuperInterface(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_addNullInterface); } if (this.fSuperInterfaces == null) { this.fSuperInterfaces= new String[1]; this.fSuperInterfaces[0]= name; } else { this.fSuperInterfaces= appendString(this.fSuperInterfaces, name); } setSuperInterfaces(this.fSuperInterfaces); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { switch (parent.getElementType()) { case IJavaElement.COMPILATION_UNIT: return ((ICompilationUnit)parent).getType(getName()); case IJavaElement.TYPE: return ((IType)parent).getType(getName()); // Note: creating local/anonymous type is not supported default: throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } super.setName(name); Enumeration children= getChildren(); while (children.hasMoreElements()) { IDOMNode child= (IDOMNode)children.nextElement(); if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { return ((IPackageFragment)parent).getCompilationUnit(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException { basicAddChild(child); // if the node is a constructor, it must also be fragmented to update the constructor's name if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } else { fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { int count = 1; IDOMNode previousNode = getPreviousNode(); while (previousNode != null) { if (previousNode instanceof DOMInitializer) { count++; } previousNode = previousNode.getPreviousNode(); } return ((IType) parent).getInitializer(count); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addException(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullExceptionType); } if (this.fExceptions == null) { this.fExceptions= new String[1]; this.fExceptions[0]= name; } else { this.fExceptions= appendString(this.fExceptions, name); } setExceptions(this.fExceptions); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addParameter(String type, String name) throws IllegalArgumentException { if (type == null) { throw new IllegalArgumentException(Messages.dom_nullTypeParameter); } if (name == null) { throw new IllegalArgumentException(Messages.dom_nullNameParameter); } if (this.fParameterNames == null) { this.fParameterNames= new String[1]; this.fParameterNames[0]= name; } else { this.fParameterNames= appendString(this.fParameterNames, name); } if (this.fParameterTypes == null) { this.fParameterTypes= new String[1]; this.fParameterTypes[0]= type; } else { this.fParameterTypes= appendString(this.fParameterTypes, type); } setParameters(this.fParameterTypes, this.fParameterNames); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { // translate parameter types to signatures String[] sigs= null; if (this.fParameterTypes != null) { sigs= new String[this.fParameterTypes.length]; int i; for (i= 0; i < this.fParameterTypes.length; i++) { sigs[i]= Signature.createTypeSignature(this.fParameterTypes[i].toCharArray(), false); } } String name= null; if (isConstructor()) { name= getConstructorName(); } else { name= getName(); } return ((IType)parent).getMethod(name, sigs); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setParameters(String[] types, String[] names) throws IllegalArgumentException { becomeDetailed(); if (types== null || names == null) { if (types == null && names == null) { this.fParameterTypes= null; this.fParameterNames= null; this.fParameterList= new char[] {'(',')'}; } else { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } } else if (names.length != types.length) { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } else if (names.length == 0) { setParameters(null, null); } else { this.fParameterNames= names; this.fParameterTypes= types; CharArrayBuffer parametersBuffer = new CharArrayBuffer(); parametersBuffer.append("("); //$NON-NLS-1$ char[] comma = new char[] {',', ' '}; for (int i = 0; i < names.length; i++) { if (i > 0) { parametersBuffer.append(comma); } parametersBuffer .append(types[i]) .append(' ') .append(names[i]); } parametersBuffer.append(')'); this.fParameterList= parametersBuffer.getContents(); } fragment(); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setReturnType(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullReturnType); } becomeDetailed(); fragment(); setReturnTypeAltered(true); this.fReturnType= name; }
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected void setRelativePosition(IJavaElement sibling, int policy) throws IllegalArgumentException { if (sibling == null) { this.anchorElement = null; this.insertionPolicy = INSERT_LAST; } else { this.anchorElement = sibling; this.insertionPolicy = policy; } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { try { int count = 0; while (typeSignature[count] == C_ARRAY) { ++count; } return count; } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(String typeSignature) throws IllegalArgumentException { return getArrayCount(typeSignature.toCharArray()); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException { int count = getArrayCount(typeSignature); if (count == 0) return typeSignature; int length = typeSignature.length; char[] result = new char[length-count]; System.arraycopy(typeSignature, count, result, 0, length-count); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String getElementType(String typeSignature) throws IllegalArgumentException { char[] signature = typeSignature.toCharArray(); char[] elementType = getElementType(signature); return signature == elementType ? typeSignature : new String(elementType); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getIntersectionTypeBounds(char[] intersectionTypeSignature) throws IllegalArgumentException { if (getTypeSignatureKind(intersectionTypeSignature) != INTERSECTION_TYPE_SIGNATURE) { return CharOperation.NO_CHAR_CHAR; } ArrayList args = new ArrayList(); int i = 1; // skip the '|' int length = intersectionTypeSignature.length; for (;;) { int e = Util.scanClassTypeSignature(intersectionTypeSignature, i); if (e < 0) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } args.add(CharOperation.subarray(intersectionTypeSignature, i, e + 1)); if (e == length - 1) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } else if (intersectionTypeSignature[e + 1] != C_COLON) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } i = e + 2; // add one to skip C_COLON } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getIntersectionTypeBounds(String intersectionTypeSignature) throws IllegalArgumentException { char[][] args = getIntersectionTypeBounds(intersectionTypeSignature.toCharArray()); return CharOperation.toStrings(args); }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(String methodSignature) throws IllegalArgumentException { return getParameterCount(methodSignature.toCharArray()); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { try { int count = getParameterCount(methodSignature); char[][] result = new char[count][]; if (count == 0) { return result; } int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } int t = 0; for (;;) { if (methodSignature[i] == C_PARAM_END) { return result; } int e = Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } result[t] = CharOperation.subarray(methodSignature, i, e + 1); t++; i = e + 1; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException { char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray()); return CharOperation.toStrings(parameterTypes); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // there could be thrown exceptions behind, thus scan one type exactly int last = Util.scanTypeSignature(methodSignature, paren+1); return CharOperation.subarray(methodSignature, paren + 1, last+1); }
// in model/org/eclipse/jdt/core/Signature.java
public static String getReturnType(String methodSignature) throws IllegalArgumentException { return new String(getReturnType(methodSignature.toCharArray())); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getThrownExceptionTypes(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int exceptionStart = CharOperation.indexOf(C_EXCEPTION_START, methodSignature); if (exceptionStart == -1) { int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // ignore return type exceptionStart = Util.scanTypeSignature(methodSignature, paren+1) + 1; int length = methodSignature.length; if (exceptionStart == length) return CharOperation.NO_CHAR_CHAR; throw new IllegalArgumentException(); } int length = methodSignature.length; int i = exceptionStart; ArrayList exceptionList = new ArrayList(1); while (i < length) { if (methodSignature[i] == C_EXCEPTION_START) { exceptionStart++; i++; } else { throw new IllegalArgumentException(); } i = Util.scanTypeSignature(methodSignature, i) + 1; exceptionList.add(CharOperation.subarray(methodSignature, exceptionStart,i)); exceptionStart = i; } char[][] result; exceptionList.toArray(result = new char[exceptionList.size()][]); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getThrownExceptionTypes(String methodSignature) throws IllegalArgumentException { char[][] parameterTypes = getThrownExceptionTypes(methodSignature.toCharArray()); return CharOperation.toStrings(parameterTypes); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeArguments(char[] parameterizedTypeSignature) throws IllegalArgumentException { int length = parameterizedTypeSignature.length; if (length < 2 || parameterizedTypeSignature[length-2] != C_GENERIC_END) // cannot have type arguments otherwise signature would end by ">;" return CharOperation.NO_CHAR_CHAR; int count = 1; // start to count generic end/start peers int start = length - 2; while (start >= 0 && count > 0) { switch (parameterizedTypeSignature[--start]) { case C_GENERIC_START: count--; break; case C_GENERIC_END: count++; break; } } if (start < 0) // invalid number of generic start/end throw new IllegalArgumentException(); ArrayList args = new ArrayList(); int p = start + 1; while (true) { if (p >= parameterizedTypeSignature.length) { throw new IllegalArgumentException(); } char c = parameterizedTypeSignature[p]; if (c == C_GENERIC_END) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } int e = Util.scanTypeArgumentSignature(parameterizedTypeSignature, p); args.add(CharOperation.subarray(parameterizedTypeSignature, p, e+1)); p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeArguments(String parameterizedTypeSignature) throws IllegalArgumentException { char[][] args = getTypeArguments(parameterizedTypeSignature.toCharArray()); return CharOperation.toStrings(args); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeErasure(char[] parameterizedTypeSignature) throws IllegalArgumentException { int end = CharOperation.indexOf(C_GENERIC_START, parameterizedTypeSignature); if (end == -1) return parameterizedTypeSignature; int length = parameterizedTypeSignature.length; char[] result = new char[length]; int pos = 0; int start = 0; int deep= 0; for (int idx=end; idx<length; idx++) { switch (parameterizedTypeSignature[idx]) { case C_GENERIC_START: if (deep == 0) { int size = idx-start; System.arraycopy(parameterizedTypeSignature, start, result, pos, size); end = idx; pos += size; } deep++; break; case C_GENERIC_END: deep--; if (deep < 0) throw new IllegalArgumentException(); if (deep == 0) start = idx+1; break; } } if (deep > 0) throw new IllegalArgumentException(); int size = pos+length-start; char[] resized = new char[size]; System.arraycopy(result, 0, resized, 0, pos); System.arraycopy(parameterizedTypeSignature, start, resized, pos, length-start); return resized; }
// in model/org/eclipse/jdt/core/Signature.java
public static String getTypeErasure(String parameterizedTypeSignature) throws IllegalArgumentException { char[] signature = parameterizedTypeSignature.toCharArray(); char[] erasure = getTypeErasure(signature); return signature == erasure ? parameterizedTypeSignature : new String(erasure); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p1 < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } if (p1 == formalTypeParameterSignature.length - 1) { // no class or interface bounds return CharOperation.NO_CHAR_CHAR; } int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); char[] classBound; if (p2 < 0) { // no interface bounds classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); return new char[][] {classBound}; } if (p2 == p1 + 1) { // no class bound, but 1 or more interface bounds classBound = null; } else { classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); } char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); if (classBound == null) { return interfaceBounds; } int resultLength = interfaceBounds.length + 1; char[][] result = new char[resultLength][]; result[0] = classBound; System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeParameterBounds(String formalTypeParameterSignature) throws IllegalArgumentException { char[][] bounds = getTypeParameterBounds(formalTypeParameterSignature.toCharArray()); return CharOperation.toStrings(bounds); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { try { int length = methodOrTypeSignature.length; if (length == 0) return CharOperation.NO_CHAR_CHAR; if (methodOrTypeSignature[0] != C_GENERIC_START) return CharOperation.NO_CHAR_CHAR; ArrayList paramList = new ArrayList(1); int paramStart = 1, i = 1; // start after leading '<' while (i < length) { if (methodOrTypeSignature[i] == C_GENERIC_END) { int size = paramList.size(); if (size == 0) throw new IllegalArgumentException(); char[][] result; paramList.toArray(result = new char[size][]); return result; } i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); if (i < 0 || i >= length) throw new IllegalArgumentException(); // iterate over bounds while (methodOrTypeSignature[i] == ':') { i++; // skip colon switch (methodOrTypeSignature[i]) { case ':': // no class bound break; case C_GENERIC_END: break; case C_RESOLVED: try { i = Util.scanClassTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter } break; case C_ARRAY: try { i = Util.scanArrayTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter } break; case C_TYPE_VARIABLE: try { i = Util.scanTypeVariableSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter } break; // default: another type parameter is starting } } paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); paramStart = i; // next param start from here } } catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through } throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeParameters(String methodOrTypeSignature) throws IllegalArgumentException { char[][] params = getTypeParameters(methodOrTypeSignature.toCharArray()); return CharOperation.toStrings(params); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeVariable(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } return CharOperation.subarray(formalTypeParameterSignature, 0, p); }
// in model/org/eclipse/jdt/core/Signature.java
public static String getTypeVariable(String formalTypeParameterSignature) throws IllegalArgumentException { return new String(getTypeVariable(formalTypeParameterSignature.toCharArray())); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] signature) throws IllegalArgumentException { int sigLength = signature.length; if (sigLength == 0) { throw new IllegalArgumentException(); } if (signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); } StringBuffer buffer = new StringBuffer(signature.length + 10); appendTypeSignature(signature, 0, true, buffer); char[] result = new char[buffer.length()]; buffer.getChars(0, buffer.length(), result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String toString(String signature) throws IllegalArgumentException { return new String(toCharArray(signature.toCharArray())); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException { Document doc= new Document(content); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { if (this.fOffset < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < this.fOffset + this.fLength)) { this.fPosition.offset= this.fOffset + this.fLength; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { Document doc= new Document(string); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { int start= this.fOffset; int end= start + this.fLength; if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) { this.fPosition.offset= end; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException { if (document == null) { throw new IllegalArgumentException(); } ASTNode rootNode= getRootNode(); if (rootNode == null) { return new MultiTextEdit(); // no changes } char[] content= document.get().toCharArray(); LineInformation lineInfo= LineInformation.create(document); String lineDelim= TextUtilities.getDefaultLineDelimiter(document); ASTNode astRoot= rootNode.getRoot(); List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null; Map currentOptions = options == null ? JavaCore.getOptions() : options; return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData()); }
// 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()); }
(Domain) InvalidInputException 149
              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { if (this.tagSourceStart>this.cursorLocation) { return super.parseArguments(receiver); } // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && getCurrentTokenType() == TerminalTokens.TokenNameRPAREN) { this.lineStarted = true; return createMethodReference(receiver, null); } Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } if (this.index >= this.scanner.eofPosition) { int argumentStart = ((ASTNode)typeRef).sourceStart; Object argument = createArgumentReference(this.scanner.getCurrentIdentifierSource(), 0, false, typeRef, null, (((long)argumentStart)<<32)+this.tokenPreviousPosition-1); return syntaxRecoverArgumentType(receiver, arguments, argument); } if (this.index >= this.cursorLocation) { if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token == null || singleTypeReference.token.length == 0) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens == null || qualifiedTypeReference.tokens.length < qualifiedTypeReference.sourcePositions.length) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); return syntaxRecoverArgumentType(receiver, arguments, argument); } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
public static boolean isDigit(char c) throws InvalidInputException { if(c < ScannerHelper.MAX_OBVIOUS) { return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0; } if (Character.isDigit(c)) { throw new InvalidInputException(Scanner.INVALID_DIGIT); } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { TypeReference argTypeRef = (TypeReference) typeRef; if (dim > 0) { long pos = (((long) argTypeRef.sourceStart) << 32) + argTypeRef.sourceEnd; if (typeRef instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef; argTypeRef = new JavadocArraySingleTypeReference(singleRef.token, dim, pos); } else { JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) typeRef; argTypeRef = new JavadocArrayQualifiedTypeReference(qualifRef, dim); } } int argEnd = argTypeRef.sourceEnd; if (dim > 0) { argEnd = (int) dimPositions[dim-1]; if (isVarargs) { argTypeRef.bits |= ASTNode.IsVarArgs; // set isVarArgs } } if (argNamePos >= 0) argEnd = (int) argNamePos; return new JavadocArgumentExpression(name, argTypeRef.sourceStart, argEnd, argTypeRef); } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } // Create field JavadocFieldReference field = new JavadocFieldReference(this.identifierStack[0], this.identifierPositionStack[0]); field.receiver = typeRef; field.tagSourceStart = this.tagSourceStart; field.tagSourceEnd = this.tagSourceEnd; field.tagValue = this.tagValue; return field; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; // Decide whether we have a constructor or not boolean isConstructor = false; int length = this.identifierLengthStack[0]; // may be > 1 for member class constructor reference if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } isConstructor = CharOperation.equals(this.identifierStack[length-1], name); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } else { if (typeRef instanceof JavadocSingleTypeReference) { char[] name = ((JavadocSingleTypeReference)typeRef).token; isConstructor = CharOperation.equals(this.identifierStack[length-1], name); } else if (typeRef instanceof JavadocQualifiedTypeReference) { char[][] tokens = ((JavadocQualifiedTypeReference)typeRef).tokens; int last = tokens.length-1; isConstructor = CharOperation.equals(this.identifierStack[length-1], tokens[last]); if (isConstructor) { boolean valid = true; if (valid) { for (int i=0; i<length-1 && valid; i++) { valid = CharOperation.equals(this.identifierStack[i], tokens[i]); } } if (!valid) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidMemberTypeQualification((int)(this.identifierPositionStack[0]>>>32), (int)this.identifierPositionStack[length-1], -1); } return null; } } } else { throw new InvalidInputException(); } } // Create node if (arguments == null) { if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1]); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } else { JavadocArgumentExpression[] expressions = new JavadocArgumentExpression[arguments.size()]; arguments.toArray(expressions); if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.arguments = expressions; allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1], expressions); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); int start = this.scanner.getCurrentTokenStartPosition(); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && this.currentTokenType == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } this.lineStarted = true; return createMethodReference(receiver, null); } break nextArg; } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { break nextArg; } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseQualifiedName(boolean reset) throws InvalidInputException { // Reset identifier stack if requested if (reset) { this.identifierPtr = -1; this.identifierLengthPtr = -1; } // Scan tokens int primitiveToken = -1; int parserKind = this.kind & PARSER_KIND; nextToken : for (int iToken = 0; ; iToken++) { int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameIdentifier : if (((iToken & 1) != 0)) { // identifiers must be odd tokens break nextToken; } pushIdentifier(iToken == 0, false); consumeToken(); break; case TerminalTokens.TokenNameDOT : if ((iToken & 1) == 0) { // dots must be even tokens throw new InvalidInputException(); } consumeToken(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: if (iToken == 0) { pushIdentifier(true, true); primitiveToken = token; consumeToken(); break nextToken; } // Fall through default case to verify that we do not leave on a dot //$FALL-THROUGH$ default : if (iToken == 0) { if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return null; } if ((iToken & 1) == 0) { // cannot leave on a dot switch (parserKind) { case COMPLETION_PARSER: if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return syntaxRecoverQualifiedName(primitiveToken); case DOM_PARSER: if (this.currentTokenType != -1) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } // $FALL-THROUGH$ - fall through default case to raise exception default: throw new InvalidInputException(); } } break nextToken; } } // Reset position: we want to rescan last token if (parserKind != COMPLETION_PARSER && this.currentTokenType != -1) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return createTypeReference(primitiveToken); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { MethodRefParameter argument = this.ast.newMethodRefParameter(); ASTNode node = (ASTNode) typeRef; int argStart = node.getStartPosition(); int argEnd = node.getStartPosition()+node.getLength()-1; if (dim > 0) argEnd = (int) dimPositions[dim-1]; if (argNamePos >= 0) argEnd = (int) argNamePos; if (name.length != 0) { final SimpleName argName = new SimpleName(this.ast); argName.internalSetIdentifier(new String(name)); argument.setName(argName); int argNameStart = (int) (argNamePos >>> 32); argName.setSourceRange(argNameStart, argEnd-argNameStart+1); } Type argType = null; if (node.getNodeType() == ASTNode.PRIMITIVE_TYPE) { argType = (PrimitiveType) node; // if (dim > 0) { // argType = this.ast.newArrayType(argType, dim); // argType.setSourceRange(argStart, ((int) dimPositions[dim-1])-argStart+1); // } } else { Name argTypeName = (Name) node; argType = this.ast.newSimpleType(argTypeName); argType.setSourceRange(argStart, node.getLength()); } if (dim > 0 && !isVarargs) { for (int i=0; i<dim; i++) { argType = this.ast.newArrayType(argType); argType.setSourceRange(argStart, ((int) dimPositions[i])-argStart+1); } } argument.setType(argType); argument.setSourceRange(argStart, argEnd - argStart + 1); return argument; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { MemberRef fieldRef = this.ast.newMemberRef(); SimpleName fieldName = new SimpleName(this.ast); fieldName.internalSetIdentifier(new String(this.identifierStack[0])); fieldRef.setName(fieldName); int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; fieldName.setSourceRange(start, end - start + 1); if (receiver == null) { start = this.memberStart; fieldRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; fieldRef.setQualifier(typeRef); start = typeRef.getStartPosition(); end = fieldName.getStartPosition()+fieldName.getLength()-1; fieldRef.setSourceRange(start, end-start+1); } return fieldRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Create method ref MethodRef methodRef = this.ast.newMethodRef(); SimpleName methodName = new SimpleName(this.ast); int length = this.identifierLengthStack[0] - 1; // may be > 0 for member class constructor reference methodName.internalSetIdentifier(new String(this.identifierStack[length])); methodRef.setName(methodName); int start = (int) (this.identifierPositionStack[length] >>> 32); int end = (int) this.identifierPositionStack[length]; methodName.setSourceRange(start, end - start + 1); // Set qualifier if (receiver == null) { start = this.memberStart; methodRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; methodRef.setQualifier(typeRef); start = typeRef.getStartPosition(); } // Add arguments if (arguments != null) { Iterator parameters = arguments.listIterator(); while (parameters.hasNext()) { MethodRefParameter param = (MethodRefParameter) parameters.next(); methodRef.parameters().add(param); } } methodRef.setSourceRange(start, this.scanner.getCurrentTokenEndPosition()-start+1); return methodRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
15
              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
67
              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException { char[] src = this.source; // only look for newer task: tags if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { return; } int foundTaskIndex = this.foundTaskCount; char previous = src[commentStart+1]; // should be '*' or '/' for ( int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) { char[] tag = null; char[] priority = null; // check for tag occurrence only if not ambiguous with javadoc tag if (previous != '@') { nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) { tag = this.taskTags[itag]; int tagLength = tag.length; if (tagLength == 0) continue nextTag; // ensure tag is not leaded with letter if tag starts with a letter if (ScannerHelper.isJavaIdentifierStart(this.complianceLevel, tag[0])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, previous)) { continue nextTag; } } for (int t = 0; t < tagLength; t++) { char sc, tc; int x = i+t; if (x >= this.eofPosition || x >= commentEnd) continue nextTag; // case sensitive check if ((sc = src[i + t]) != (tc = tag[t])) { // case insensitive check if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { continue nextTag; } } } // ensure tag is not followed with letter if tag finishes with a letter if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i+tagLength-1])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i + tagLength])) continue nextTag; } if (this.foundTaskTags == null) { this.foundTaskTags = new char[5][]; this.foundTaskMessages = new char[5][]; this.foundTaskPriorities = new char[5][]; this.foundTaskPositions = new int[5][]; } else if (this.foundTaskCount == this.foundTaskTags.length) { System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount); } priority = this.taskPriorities != null && itag < this.taskPriorities.length ? this.taskPriorities[itag] : null; this.foundTaskTags[this.foundTaskCount] = tag; this.foundTaskPriorities[this.foundTaskCount] = priority; this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 }; this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; this.foundTaskCount++; i += tagLength - 1; // will be incremented when looping break nextTag; } } previous = src[i]; } boolean containsEmptyTask = false; for (int i = foundTaskIndex; i < this.foundTaskCount; i++) { // retrieve message start and end positions int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length; int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 : commentEnd - 1; // at most beginning of next task if (max_value < msgStart) { max_value = msgStart; // would only occur if tag is before EOF. } int end = -1; char c; for (int j = msgStart; j < max_value; j++) { if ((c = src[j]) == '\n' || c == '\r') { end = j - 1; break; } } if (end == -1) { for (int j = max_value; j > msgStart; j--) { if ((c = src[j]) == '*') { end = j - 1; break; } } if (end == -1) end = max_value; } if (msgStart == end) { // if the description is empty, we might want to see if two tags are not sharing the same message // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797 containsEmptyTask = true; continue; } // trim the message // we don't trim the beginning of the message to be able to show it after the task tag while (CharOperation.isWhitespace(src[end]) && msgStart <= end) end--; // update the end position of the task this.foundTaskPositions[i][1] = end; // get the message source final int messageLength = end - msgStart + 1; char[] message = new char[messageLength]; System.arraycopy(src, msgStart, message, 0, messageLength); this.foundTaskMessages[i] = message; } if (containsEmptyTask) { for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) { if (this.foundTaskMessages[i].length == 0) { loop: for (int j = i + 1; j < max; j++) { if (this.foundTaskMessages[j].length != 0) { this.foundTaskMessages[i] = this.foundTaskMessages[j]; this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1]; break loop; } } } } } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix) throws InvalidInputException { consumeDigits(radix, false); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final int consumeDigits0(int radix, int usingUnderscore, int invalidPosition, boolean expectingDigitFirst) throws InvalidInputException { int kind = 0; if (getNextChar('_')) { if (expectingDigitFirst) { return invalidPosition; } kind = usingUnderscore; while (getNextChar('_')) {/*empty */} } if (getNextCharAsDigit(radix)) { // continue to read digits or underscore while (getNextCharAsDigit(radix)) {/*empty */} int kind2 = consumeDigits0(radix, usingUnderscore, invalidPosition, false); if (kind2 == 0) { return kind; } return kind2; } if (kind == usingUnderscore) return invalidPosition; return kind; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final boolean getNextCharAsDigit() throws InvalidInputException { //BOOLEAN //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //Both previous lines are true if the currentCharacter is a digit //On false, no side effect has occured. //ALL getNextChar.... ARE OPTIMIZED COPIES if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront return false; int temp = this.currentPosition; try { if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; this.withoutUnicodePtr--; return false; } return true; } else { if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; return false; } if (this.withoutUnicodePtr != 0) unicodeStore(); return true; } } catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; } catch(InvalidInputException e) { this.currentPosition = temp; return false; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException { //BOOLEAN //handle the case of unicode. Jump over the next whiteSpace //making startPosition pointing on the next available char //On false, the currentCharacter is filled up with a potential //correct char this.wasAcr = false; getNextUnicodeChar(); return CharOperation.isWhitespace(this.currentCharacter); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object ref, long[] dimPositions, long argNamePos) throws InvalidInputException { FormatJavadocReference typeRef = (FormatJavadocReference) ref; if (dim > 0) { typeRef.sourceEnd = (int) dimPositions[dim-1]; } if (argNamePos >= 0) typeRef.sourceEnd = (int) argNamePos; return ref; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int start = receiver == null ? this.memberStart : ((FormatJavadocReference)receiver).sourceStart; int lineStart = this.scanner.getLineNumber(start); return new FormatJavadocReference(start, (int) this.identifierPositionStack[0], lineStart); }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int start = receiver == null ? this.memberStart : ((FormatJavadocReference) receiver).sourceStart; int lineStart = this.scanner.getLineNumber(start); return new FormatJavadocReference(start, this.scanner.getCurrentTokenEndPosition(), lineStart); }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseHtmlTag(int previousPosition, int endTextPosition) throws InvalidInputException { if (!this.parseHtmlTags) return false; boolean closing = false; boolean valid = false; boolean incremented = false; int start = this.scanner.currentPosition; int currentPosition = start; int htmlPtr = this.htmlTagsPtr; char firstChar = peekChar(); boolean hasWhitespaces = firstChar == ' ' || ScannerHelper.isWhitespace(firstChar); try { int token = readTokenAndConsume(); char[] htmlTag; int htmlIndex; switch (token) { case TerminalTokens.TokenNameIdentifier: // HTML tag opening htmlTag = this.scanner.getCurrentIdentifierSource(); htmlIndex = getHtmlTagIndex(htmlTag); if (htmlIndex == JAVADOC_TAGS_ID_MASK) return false; if (htmlPtr >= 0) { int lastHtmlTagIndex = getHtmlTagIndex(this.htmlTags[htmlPtr]); if ((lastHtmlTagIndex & JAVADOC_TAGS_ID_MASK) == JAVADOC_IMMUTABLE_TAGS_ID) { // Do not accept tags inside immutable tags except the <pre> tag if ((htmlIndex & JAVADOC_TAGS_ID_MASK) == JAVADOC_CODE_TAGS_ID) { FormatJavadocBlock previousBlock = (FormatJavadocBlock) this.astStack[this.astPtr]; FormatJavadocNode parentNode = previousBlock; FormatJavadocNode lastNode = parentNode; while (lastNode.getLastNode() != null) { parentNode = lastNode; lastNode = lastNode.getLastNode(); } if (lastNode.isText()) { FormatJavadocText text = (FormatJavadocText) lastNode; if (text.separatorsPtr == -1) { break; } } } return false; } } if ((htmlIndex & JAVADOC_TAGS_ID_MASK) > JAVADOC_SINGLE_TAGS_ID) { if (this.htmlTagsPtr == -1 || !CharOperation.equals(this.htmlTags[this.htmlTagsPtr], htmlTag, false)) { if (++this.htmlTagsPtr == 0) { // lazy initialization this.htmlTags = new char[AST_STACK_INCREMENT][]; } else { // resize if needed if (this.htmlTagsPtr == this.htmlTags.length) { System.arraycopy(this.htmlTags, 0, (this.htmlTags = new char[this.htmlTags.length + AST_STACK_INCREMENT][]), 0, this.htmlTagsPtr); } } this.htmlTags[this.htmlTagsPtr] = htmlTag; incremented = true; } } // Accept xhtml syntax currentPosition = this.scanner.currentPosition; if (readToken() == TerminalTokens.TokenNameDIVIDE) { consumeToken(); } break; case TerminalTokens.TokenNameDIVIDE: // HTML tag closing if (this.htmlTagsPtr == -1) return false; htmlTag = this.htmlTags[this.htmlTagsPtr]; if ((token = readTokenAndConsume()) != TerminalTokens.TokenNameIdentifier) { // not a closing html tag return false; } char[] identifier = this.scanner.getCurrentIdentifierSource(); htmlIndex = getHtmlTagIndex(identifier); if (htmlIndex == JAVADOC_TAGS_ID_MASK) return false; int ptr = this.htmlTagsPtr; while (!CharOperation.equals(htmlTag, identifier, false)) { if (this.htmlTagsPtr <= 0) { // consider the closing tag as invalid this.htmlTagsPtr = ptr; return false; } this.htmlTagsPtr--; htmlTag = this.htmlTags[this.htmlTagsPtr]; } // set closing flag htmlIndex |= JAVADOC_CLOSED_TAG; closing = true; currentPosition = this.scanner.currentPosition; break; default: return false; } // Looking for tag closing switch (readTokenAndConsume()) { case TerminalTokens.TokenNameLESS: case TerminalTokens.TokenNameLESS_EQUAL: // consider that the closing '>' is missing return false; case TerminalTokens.TokenNameGREATER: // simple tag without attributes break; case TerminalTokens.TokenNameGREATER_EQUAL: case TerminalTokens.TokenNameRIGHT_SHIFT: case TerminalTokens.TokenNameRIGHT_SHIFT_EQUAL: // simple tag without attributes, but the closing '>' is followed by an '=' or '>' break; default: this.index = currentPosition; loop: while (true) { // currentPosition = this.index; switch (readChar()) { case '<': if (hasWhitespaces) { // not 100% sure this is a tag definition => give up return false; } // opening tag => consider the current one as closed this.index = currentPosition; this.scanner.startPosition = currentPosition; this.scanner.currentPosition = currentPosition; this.scanner.currentCharacter = '<'; break loop; case '>': // simple tag without attributes this.scanner.startPosition = this.index; this.scanner.currentPosition = this.index; this.scanner.currentCharacter = peekChar(); break loop; default: break; } if (this.index >= this.javadocTextEnd) { // the end of the comment is reached => consider current tag as closed this.index = currentPosition; this.scanner.startPosition = currentPosition; this.scanner.currentPosition = currentPosition; break; } } } // Push texts if (this.lineStarted && this.textStart != -1 && this.textStart < endTextPosition) { pushText(this.textStart, endTextPosition, -1, htmlPtr); } pushText(previousPosition, this.index, htmlIndex, this.htmlTagsPtr); this.textStart = -1; valid = true; } finally { if (valid) { if (closing) { this.htmlTagsPtr--; } } else if (!this.abort) { if (incremented) { this.htmlTagsPtr--; if (this.htmlTagsPtr == -1) this.htmlTags = null; } this.scanner.resetTo(start, this.scanner.eofPosition-1); this.index = start; } } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseParam() throws InvalidInputException { boolean valid = super.parseParam(); if (!valid) { this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); this.index = this.tagSourceEnd+1; char ch = peekChar(); // Try to push an identifier in the stack, otherwise restart from the end tag position if (ch == ' ' || ScannerHelper.isWhitespace(ch)) { int token = this.scanner.getNextToken(); if (token == TerminalTokens.TokenNameIdentifier) { ch = peekChar(); if (ch == ' ' || ScannerHelper.isWhitespace(ch)) { pushIdentifier(true, false); pushParamName(false); this.index = this.scanner.currentPosition; valid = true; } } this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); } this.tagValue = TAG_OTHERS_VALUE; // tag is invalid, do not keep the parsed tag value } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseReference() throws InvalidInputException { boolean valid = super.parseReference(); if (!valid) { this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); this.index = this.tagSourceEnd+1; this.tagValue = TAG_OTHERS_VALUE; // tag is invalid, do not keep the parsed tag value } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Do not parse javadoc tag inside <pre>...</pre> tags if (this.htmlTagsPtr >= 0) { int ptr = this.htmlTagsPtr; while (ptr >= 0) { if (getHtmlTagIndex(this.htmlTags[ptr--]) == JAVADOC_CODE_TAGS_ID) { if (this.textStart == -1) this.textStart = this.inlineTagStarted ? this.inlineTagStart : previousPosition; this.inlineTagStarted = false; return true; } } } // Read tag name int ptr = this.astPtr; this.tagSourceStart = previousPosition; this.scanner.startPosition = this.index; this.scanner.currentCharacter = readChar(); switch (this.scanner.currentCharacter) { case ' ': case '*': case '}': // tag name is empty this.tagSourceEnd = previousPosition; if (this.textStart == -1) this.textStart = previousPosition; return true; default: if (ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { // tag name is empty this.tagSourceEnd = previousPosition; if (this.textStart == -1) this.textStart = previousPosition; return true; } break; } int currentPosition = this.index; char currentChar = this.scanner.currentCharacter; while (currentChar != ' ' && currentChar != '*' && currentChar != '}' && !ScannerHelper.isWhitespace(currentChar)) { currentPosition = this.index; currentChar = readChar(); } this.tagSourceEnd = currentPosition - 1; this.scanner.currentCharacter = currentChar; this.scanner.currentPosition = currentPosition; char[] tagName = this.scanner.getCurrentIdentifierSource(); int length = tagName.length; this.index = this.tagSourceEnd+1; // Decide which parse to perform depending on tag name this.tagValue = TAG_OTHERS_VALUE; boolean valid = false; switch (tagName[0]) { case 'a': if (length == TAG_AUTHOR_LENGTH && CharOperation.equals(TAG_AUTHOR, tagName)) { this.tagValue = TAG_AUTHOR_VALUE; } break; case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName)) { this.tagValue = TAG_CATEGORY_VALUE; valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } else if (length == TAG_CODE_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_CODE, tagName)) { this.tagValue = TAG_CODE_VALUE; } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) { this.deprecated = true; valid = true; this.tagValue = TAG_DEPRECATED_VALUE; } else if (length == TAG_DOC_ROOT_LENGTH && CharOperation.equals(TAG_DOC_ROOT, tagName)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=227730 // identify @docRoot tag as a base tag that does not expect any argument valid = true; this.tagValue = TAG_DOC_ROOT_VALUE; } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) { this.tagValue = TAG_EXCEPTION_VALUE; valid = parseThrows(); } break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName)) { if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } valid = true; this.tagValue = TAG_INHERITDOC_VALUE; } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) { this.tagValue = TAG_LINK_VALUE; if (this.inlineTagStarted || (this.kind & COMPLETION_PARSER) != 0) { valid = parseReference(); } else { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @link outside inline comment valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName)) { this.tagValue = TAG_LINKPLAIN_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_LITERAL_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_LITERAL, tagName)) { this.tagValue = TAG_LITERAL_VALUE; } break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) { this.tagValue = TAG_PARAM_VALUE; valid = parseParam(); } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) { if (this.inlineTagStarted) { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @see inside inline comment valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } else { this.tagValue = TAG_SEE_VALUE; valid = parseReference(); } } else if (length == TAG_SERIAL_LENGTH && CharOperation.equals(TAG_SERIAL, tagName)) { this.tagValue = TAG_SERIAL_VALUE; } else if (length == TAG_SERIAL_DATA_LENGTH && CharOperation.equals(TAG_SERIAL_DATA, tagName)) { this.tagValue = TAG_SERIAL_DATA_VALUE; } else if (length == TAG_SERIAL_FIELD_LENGTH && CharOperation.equals(TAG_SERIAL_FIELD, tagName)) { this.tagValue = TAG_SERIAL_FIELD_VALUE; } else if (length == TAG_SINCE_LENGTH && CharOperation.equals(TAG_SINCE, tagName)) { this.tagValue = TAG_SINCE_VALUE; } break; case 'v': if (length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName)) { this.tagValue = TAG_VALUE_VALUE; if (this.sourceLevel >= ClassFileConstants.JDK1_5) { if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_VERSION_LENGTH && CharOperation.equals(TAG_VERSION, tagName)) { this.tagValue = TAG_VERSION_VALUE; } else { createTag(); } break; case 'r': if (length == TAG_RETURN_LENGTH && CharOperation.equals(TAG_RETURN, tagName)) { this.tagValue = TAG_RETURN_VALUE; valid = parseReturn(); } break; case 't': if (length == TAG_THROWS_LENGTH && CharOperation.equals(TAG_THROWS, tagName)) { this.tagValue = TAG_THROWS_VALUE; valid = parseThrows(); } break; default: createTag(); break; } consumeToken(); this.textStart = -1; // the javadoc parser may not create tag for some valid tags: force tag creation for such tag. if (valid) { switch (this.tagValue) { case TAG_INHERITDOC_VALUE: case TAG_DEPRECATED_VALUE: createTag(); break; } } else if (this.invalidTagName) { this.textStart = previousPosition; } else if (this.astPtr == ptr) { createTag(); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { // Create argument as we may need it after char[] argName = name==null ? CharOperation.NO_CHAR : name; Expression expression = (Expression) super.createArgumentReference(argName, dim, isVarargs, typeRef, dimPositions, argNamePos); // See if completion location is in argument int refStart = ((TypeReference)typeRef).sourceStart; int refEnd = ((TypeReference)typeRef).sourceEnd; boolean inCompletion = (refStart <= this.cursorLocation && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)); // or it's a completion on empty token if (this.completionNode == null && inCompletion) { JavadocArgumentExpression javadocArgument = (JavadocArgumentExpression) expression; TypeReference expressionType = javadocArgument.argument.type; if (expressionType instanceof JavadocSingleTypeReference) { this.completionNode = new CompletionOnJavadocSingleTypeReference((JavadocSingleTypeReference) expressionType); } else if (expressionType instanceof JavadocQualifiedTypeReference) { this.completionNode = new CompletionOnJavadocQualifiedTypeReference((JavadocQualifiedTypeReference) expressionType); } if (CompletionEngine.DEBUG) { System.out.println(" completion argument="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return expression; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int refStart = (int) (this.identifierPositionStack[0] >>> 32); int refEnd = (int) this.identifierPositionStack[0]; boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor if (inCompletion) { JavadocFieldReference fieldRef = (JavadocFieldReference) super.createFieldReference(receiver); char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } this.completionNode = new CompletionOnJavadocFieldReference(fieldRef, this.memberStart, name); if (CompletionEngine.DEBUG) { System.out.println(" completion field="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return super.createFieldReference(receiver); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference int refStart = (int) (this.identifierPositionStack[memberPtr] >>> 32); int refEnd = (int) this.identifierPositionStack[memberPtr]; boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor if (inCompletion) { ASTNode node = (ASTNode) super.createMethodReference(receiver, arguments); if (node instanceof JavadocMessageSend) { JavadocMessageSend messageSend = (JavadocMessageSend) node; int nameStart = (int) (messageSend.nameSourcePosition >>> 32); int nameEnd = (int) messageSend.nameSourcePosition; if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) { this.completionNode = new CompletionOnJavadocFieldReference(messageSend, this.memberStart); } else { this.completionNode = new CompletionOnJavadocMessageSend(messageSend, this.memberStart); } } else if (node instanceof JavadocAllocationExpression) { this.completionNode = new CompletionOnJavadocAllocationExpression((JavadocAllocationExpression)node, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return super.createMethodReference(receiver, arguments); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { if (this.tagSourceStart>this.cursorLocation) { return super.parseArguments(receiver); } // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && getCurrentTokenType() == TerminalTokens.TokenNameRPAREN) { this.lineStarted = true; return createMethodReference(receiver, null); } Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } if (this.index >= this.scanner.eofPosition) { int argumentStart = ((ASTNode)typeRef).sourceStart; Object argument = createArgumentReference(this.scanner.getCurrentIdentifierSource(), 0, false, typeRef, null, (((long)argumentStart)<<32)+this.tokenPreviousPosition-1); return syntaxRecoverArgumentType(receiver, arguments, argument); } if (this.index >= this.cursorLocation) { if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token == null || singleTypeReference.token.length == 0) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens == null || qualifiedTypeReference.tokens.length < qualifiedTypeReference.sourcePositions.length) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); return syntaxRecoverArgumentType(receiver, arguments, argument); } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseParam() throws InvalidInputException { int startPosition = this.index; int endPosition = this.index; long namePosition = (((long)startPosition)<<32) + endPosition; this.identifierPtr = -1; boolean valid = super.parseParam(); if (this.identifierPtr > 2) return valid; // See if expression is concerned by completion char[] name = null; CompletionScanner completionScanner = (CompletionScanner) this.scanner; boolean isTypeParam = false; if (this.identifierPtr >= 0) { char[] identifier = null; switch (this.identifierPtr) { case 2: if (!valid && completionScanner.completionIdentifier != null && completionScanner.completionIdentifier.length == 0) { valid = pushParamName(true); } // $FALL-THROUGH$ - fall through next case to verify and get identifiers stack contents case 1: isTypeParam = this.identifierStack[0][0] == '<'; identifier = this.identifierStack[1]; namePosition = this.identifierPositionStack[1]; break; case 0: identifier = this.identifierStack[0]; namePosition = this.identifierPositionStack[0]; isTypeParam = identifier.length > 0 && identifier[0] == '<'; break; } if (identifier != null && identifier.length > 0 && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, identifier[0])) { name = identifier; } startPosition = (int)(this.identifierPositionStack[0]>>32); endPosition = (int)this.identifierPositionStack[this.identifierPtr]; } boolean inCompletion = (startPosition <= (this.cursorLocation+1) && this.cursorLocation <= endPosition) // completion cursor is between first and last stacked identifiers || ((startPosition == (endPosition+1) && endPosition == this.cursorLocation)); // or it's a completion on empty token if (inCompletion) { if (this.completionNode == null) { if (isTypeParam) { this.completionNode = new CompletionOnJavadocTypeParamReference(name, namePosition, startPosition, endPosition); } else { this.completionNode = new CompletionOnJavadocParamNameReference(name, namePosition, startPosition, endPosition); } if (CompletionEngine.DEBUG) { System.out.println(" completion param="+this.completionNode); //$NON-NLS-1$ } } else if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { CompletionOnJavadocParamNameReference paramNameRef = (CompletionOnJavadocParamNameReference)this.completionNode; int nameStart = (int) (namePosition>>32); paramNameRef.sourceStart = nameStart; int nameEnd = (int) namePosition; if (nameStart<this.cursorLocation && this.cursorLocation<nameEnd) { paramNameRef.sourceEnd = this.cursorLocation + 1; } else { paramNameRef.sourceEnd = nameEnd; } paramNameRef.tagSourceStart = startPosition; paramNameRef.tagSourceEnd = endPosition; } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { CompletionOnJavadocTypeParamReference typeParamRef = (CompletionOnJavadocTypeParamReference)this.completionNode; int nameStart = (int) (namePosition>>32); typeParamRef.sourceStart = nameStart; int nameEnd = (int) namePosition; if (nameStart<this.cursorLocation && this.cursorLocation<nameEnd) { typeParamRef.sourceEnd = this.cursorLocation + 1; } else { typeParamRef.sourceEnd = nameEnd; } typeParamRef.tagSourceStart = startPosition; typeParamRef.tagSourceEnd = endPosition; } } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseReference() throws InvalidInputException { boolean completed = this.completionNode != null; boolean valid = super.parseReference(); if (!completed && this.completionNode != null) { this.completionNode.addCompletionFlags(CompletionOnJavadoc.FORMAL_REFERENCE); } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { int startPosition = this.inlineTagStarted ? this.inlineTagStart : previousPosition; boolean newLine = !this.lineStarted; boolean valid = super.parseTag(previousPosition); boolean inCompletion = (this.tagSourceStart <= (this.cursorLocation+1) && this.cursorLocation <= this.tagSourceEnd) // completion cursor is between first and last stacked identifiers || ((this.tagSourceStart == (this.tagSourceEnd+1) && this.tagSourceEnd == this.cursorLocation)); // or it's a completion on empty token if (inCompletion) { int end = this.tagSourceEnd; if (this.inlineTagStarted && this.scanner.currentCharacter == '}') { end = this.scanner.currentPosition; } long position = (((long)startPosition)<<32) + end; int length = this.cursorLocation+1-this.tagSourceStart; char[] tag = new char[length]; System.arraycopy(this.source, this.tagSourceStart, tag, 0, length); char[][][] tags = possibleTags(tag, newLine); if (tags != null) { this.completionNode = new CompletionOnJavadocTag(tag, position, startPosition, end, tags, this.allPossibleTags); } } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected int readToken() throws InvalidInputException { int token = super.readToken(); if (token == TerminalTokens.TokenNameIdentifier && this.scanner.currentPosition == this.scanner.startPosition) { // Scanner is looping on empty token => read it... this.scanner.getCurrentIdentifierSource(); } return token; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException { if (this.cursorLocation == ((int)this.identifierPositionStack[this.identifierPtr])) { // special case of completion just before the dot. return createTypeReference(primitiveToken); } int idLength = this.identifierLengthStack[this.identifierLengthPtr]; char[][] tokens = new char[idLength][]; int startPtr = this.identifierPtr-idLength+1; System.arraycopy(this.identifierStack, startPtr, tokens, 0, idLength); long[] positions = new long[idLength+1]; System.arraycopy(this.identifierPositionStack, startPtr, positions, 0, idLength); positions[idLength] = (((long)this.tokenPreviousPosition)<<32) + this.tokenPreviousPosition; this.completionNode = new CompletionOnJavadocQualifiedTypeReference(tokens, CharOperation.NO_CHAR, positions, this.tagSourceStart, this.tagSourceEnd); if (CompletionEngine.DEBUG) { System.out.println(" completion partial qualified type="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverArgumentType(Object receiver, List arguments, Object argument) throws InvalidInputException { if (this.completionNode != null && !this.pushText) { this.completionNode.addCompletionFlags(CompletionOnJavadoc.BASE_TYPES); if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { char[] token = ((CompletionOnJavadocSingleTypeReference)this.completionNode).token; if (token != null && token.length > 0) { return this.completionNode; } } else { return this.completionNode; } } // Filter empty token if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token != null && singleTypeReference.token.length > 0) { arguments.add(argument); } } else if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens != null && qualifiedTypeReference.tokens.length == qualifiedTypeReference.sourcePositions.length) { arguments.add(argument); } } else { arguments.add(argument); } Object methodRef = super.createMethodReference(receiver, arguments); if (methodRef instanceof JavadocMessageSend) { JavadocMessageSend msgSend = (JavadocMessageSend) methodRef; if (this.index > this.cursorLocation) { msgSend.sourceEnd = this.tokenPreviousPosition-1; } int nameStart = (int) (msgSend.nameSourcePosition >>> 32); int nameEnd = (int) msgSend.nameSourcePosition; if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) { this.completionNode = new CompletionOnJavadocFieldReference(msgSend, this.memberStart); } else { this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart); } } else if (methodRef instanceof JavadocAllocationExpression) { JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef; if (this.index > this.cursorLocation) { allocExp.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverEmptyArgumentType(Object methodRef) throws InvalidInputException { if (methodRef instanceof JavadocMessageSend) { JavadocMessageSend msgSend = (JavadocMessageSend) methodRef; if (this.index > this.cursorLocation) { msgSend.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart); } else if (methodRef instanceof JavadocAllocationExpression) { JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef; if (this.index > this.cursorLocation) { allocExp.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public final void getNextUnicodeChar() throws InvalidInputException { int temp = this.currentPosition; // the \ is already read super.getNextUnicodeChar(); if(this.cursorLocation > temp) { this.unicodeCharSize += (this.currentPosition - temp); } if (temp < this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { int token = super.scanNumber(dotPrefix); // consider completion just before a number to be ok, will insert before it if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER); } return token; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { // Create argument as we may need it after Expression expression = (Expression) super.createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); // See if selection is in argument int start = ((TypeReference)typeRef).sourceStart; int end = ((TypeReference)typeRef).sourceEnd; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = expression; this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected argument="+this.selectedNode); //$NON-NLS-1$ } } return expression; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = (ASTNode) super.createFieldReference(receiver); this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected field="+this.selectedNode); //$NON-NLS-1$ } } return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference int start = (int) (this.identifierPositionStack[memberPtr] >>> 32); int end = (int) this.identifierPositionStack[memberPtr]; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = (ASTNode) super.createMethodReference(receiver, arguments); this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected method="+this.selectedNode); //$NON-NLS-1$ } } return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
public static boolean isDigit(char c) throws InvalidInputException { if(c < ScannerHelper.MAX_OBVIOUS) { return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0; } if (Character.isDigit(c)) { throw new InvalidInputException(Scanner.INVALID_DIGIT); } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { TypeReference argTypeRef = (TypeReference) typeRef; if (dim > 0) { long pos = (((long) argTypeRef.sourceStart) << 32) + argTypeRef.sourceEnd; if (typeRef instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef; argTypeRef = new JavadocArraySingleTypeReference(singleRef.token, dim, pos); } else { JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) typeRef; argTypeRef = new JavadocArrayQualifiedTypeReference(qualifRef, dim); } } int argEnd = argTypeRef.sourceEnd; if (dim > 0) { argEnd = (int) dimPositions[dim-1]; if (isVarargs) { argTypeRef.bits |= ASTNode.IsVarArgs; // set isVarArgs } } if (argNamePos >= 0) argEnd = (int) argNamePos; return new JavadocArgumentExpression(name, argTypeRef.sourceStart, argEnd, argTypeRef); } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } // Create field JavadocFieldReference field = new JavadocFieldReference(this.identifierStack[0], this.identifierPositionStack[0]); field.receiver = typeRef; field.tagSourceStart = this.tagSourceStart; field.tagSourceEnd = this.tagSourceEnd; field.tagValue = this.tagValue; return field; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; // Decide whether we have a constructor or not boolean isConstructor = false; int length = this.identifierLengthStack[0]; // may be > 1 for member class constructor reference if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } isConstructor = CharOperation.equals(this.identifierStack[length-1], name); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } else { if (typeRef instanceof JavadocSingleTypeReference) { char[] name = ((JavadocSingleTypeReference)typeRef).token; isConstructor = CharOperation.equals(this.identifierStack[length-1], name); } else if (typeRef instanceof JavadocQualifiedTypeReference) { char[][] tokens = ((JavadocQualifiedTypeReference)typeRef).tokens; int last = tokens.length-1; isConstructor = CharOperation.equals(this.identifierStack[length-1], tokens[last]); if (isConstructor) { boolean valid = true; if (valid) { for (int i=0; i<length-1 && valid; i++) { valid = CharOperation.equals(this.identifierStack[i], tokens[i]); } } if (!valid) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidMemberTypeQualification((int)(this.identifierPositionStack[0]>>>32), (int)this.identifierPositionStack[length-1], -1); } return null; } } } else { throw new InvalidInputException(); } } // Create node if (arguments == null) { if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1]); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } else { JavadocArgumentExpression[] expressions = new JavadocArgumentExpression[arguments.size()]; arguments.toArray(expressions); if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.arguments = expressions; allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1], expressions); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Complain when tag is missing a description // Note that if the parse of an inline tag has already started, consider it // as the expected description, hence do not report any warning switch (this.tagWaitingForDescription) { case TAG_PARAM_VALUE: case TAG_THROWS_VALUE: if (!this.inlineTagStarted) { int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[this.identifierPtr]; this.sourceParser.problemReporter().javadocMissingTagDescriptionAfterReference(start, end, this.sourceParser.modifiers); } break; case NO_TAG_VALUE: break; default: if (!this.inlineTagStarted) { this.sourceParser.problemReporter().javadocMissingTagDescription(TAG_NAMES[this.tagWaitingForDescription], this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers); } break; } this.tagWaitingForDescription = NO_TAG_VALUE; // Verify first character this.tagSourceStart = this.index; this.tagSourceEnd = previousPosition; this.scanner.startPosition = this.index; int currentPosition = this.index; char firstChar = readChar(); switch (firstChar) { case ' ': case '*': case '}': case '#': // the first character is not valid, hence report invalid empty tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(previousPosition, currentPosition); if (this.textStart == -1) this.textStart = currentPosition; this.scanner.currentCharacter = firstChar; return false; default: if (ScannerHelper.isWhitespace(firstChar)) { // the first character is not valid, hence report invalid empty tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(previousPosition, currentPosition); if (this.textStart == -1) this.textStart = currentPosition; this.scanner.currentCharacter = firstChar; return false; } break; } // Read tag name char[] tagName = new char[32]; int length = 0; char currentChar = firstChar; int tagNameLength = tagName.length; boolean validTag = true; tagLoop: while (true) { if (length == tagNameLength) { System.arraycopy(tagName, 0, tagName = new char[tagNameLength+32], 0, tagNameLength); tagNameLength = tagName.length; } tagName[length++] = currentChar; currentPosition = this.index; currentChar = readChar(); switch (currentChar) { case ' ': case '*': case '}': // these characters mark the end of the tag reading break tagLoop; case '#': // invalid tag character, mark the tag as invalid but continue until the end of the tag validTag = false; break; default: if (ScannerHelper.isWhitespace(currentChar)) { // whitespace characters mark the end of the tag reading break tagLoop; } break; } } // Init positions this.tagSourceEnd = currentPosition - 1; this.scanner.currentCharacter = currentChar; this.scanner.currentPosition = currentPosition; this.index = this.tagSourceEnd+1; // Return if the tag is not valid if (!validTag) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(this.tagSourceStart, this.tagSourceEnd); if (this.textStart == -1) this.textStart = this.index; this.scanner.currentCharacter = currentChar; return false; } // Decide which parse to perform depending on tag name this.tagValue = TAG_OTHERS_VALUE; boolean valid = false; switch (firstChar) { case 'a': if (length == TAG_AUTHOR_LENGTH && CharOperation.equals(TAG_AUTHOR, tagName, 0, length)) { this.tagValue = TAG_AUTHOR_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName, 0, length)) { this.tagValue = TAG_CATEGORY_VALUE; if (!this.inlineTagStarted) { valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } } else if (length == TAG_CODE_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_CODE, tagName, 0, length)) { this.tagValue = TAG_CODE_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName, 0, length)) { this.deprecated = true; valid = true; this.tagValue = TAG_DEPRECATED_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_DOC_ROOT_LENGTH && CharOperation.equals(TAG_DOC_ROOT, tagName, 0, length)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=227730 // identify @docRoot tag as a base tag that does not expect any argument valid = true; this.tagValue = TAG_DOC_ROOT_VALUE; } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName, 0, length)) { this.tagValue = TAG_EXCEPTION_VALUE; if (!this.inlineTagStarted) { valid = parseThrows(); } } break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName, 0, length)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=247037, @inheritDoc usage is illegal // outside of few block tags and the main description. switch (this.lastBlockTagValue) { case TAG_RETURN_VALUE: case TAG_THROWS_VALUE: case TAG_EXCEPTION_VALUE: case TAG_PARAM_VALUE: case NO_TAG_VALUE: // Still in main description valid = true; if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } if (this.inlineTagStarted) { // parse a 'valid' inheritDoc tag parseInheritDocTag(); } break; default: valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } this.tagValue = TAG_INHERITDOC_VALUE; } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName, 0, length)) { this.tagValue = TAG_LINK_VALUE; if (this.inlineTagStarted || (this.kind & COMPLETION_PARSER) != 0) { valid= parseReference(); } } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName, 0, length)) { this.tagValue = TAG_LINKPLAIN_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } } else if (length == TAG_LITERAL_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_LITERAL, tagName, 0, length)) { this.tagValue = TAG_LITERAL_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName, 0, length)) { this.tagValue = TAG_PARAM_VALUE; if (!this.inlineTagStarted) { valid = parseParam(); } } break; case 'r': if (length == TAG_RETURN_LENGTH && CharOperation.equals(TAG_RETURN, tagName, 0, length)) { this.tagValue = TAG_RETURN_VALUE; if (!this.inlineTagStarted) { valid = parseReturn(); } } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName, 0, length)) { this.tagValue = TAG_SEE_VALUE; if (!this.inlineTagStarted) { valid = parseReference(); } } else if (length == TAG_SERIAL_LENGTH && CharOperation.equals(TAG_SERIAL, tagName, 0, length)) { this.tagValue = TAG_SERIAL_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SERIAL_DATA_LENGTH && CharOperation.equals(TAG_SERIAL_DATA, tagName, 0, length)) { this.tagValue = TAG_SERIAL_DATA_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SERIAL_FIELD_LENGTH && CharOperation.equals(TAG_SERIAL_FIELD, tagName, 0, length)) { this.tagValue = TAG_SERIAL_FIELD_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SINCE_LENGTH && CharOperation.equals(TAG_SINCE, tagName, 0, length)) { this.tagValue = TAG_SINCE_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 't': if (length == TAG_THROWS_LENGTH && CharOperation.equals(TAG_THROWS, tagName, 0, length)) { this.tagValue = TAG_THROWS_VALUE; if (!this.inlineTagStarted) { valid = parseThrows(); } } break; case 'v': if (length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName, 0, length)) { this.tagValue = TAG_VALUE_VALUE; if (this.sourceLevel >= ClassFileConstants.JDK1_5) { if (this.inlineTagStarted) { valid = parseReference(); } } else { if (this.validValuePositions == -1) { if (this.invalidValuePositions != -1) { if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag((int) (this.invalidValuePositions>>>32), (int) this.invalidValuePositions); } if (valid) { this.validValuePositions = (((long) this.tagSourceStart) << 32) + this.tagSourceEnd; this.invalidValuePositions = -1; } else { this.invalidValuePositions = (((long) this.tagSourceStart) << 32) + this.tagSourceEnd; } } else { if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_VERSION_LENGTH && CharOperation.equals(TAG_VERSION, tagName, 0, length)) { this.tagValue = TAG_VERSION_VALUE; this.tagWaitingForDescription = this.tagValue; } else { createTag(); } break; default: createTag(); break; } this.textStart = this.index; if (this.tagValue != TAG_OTHERS_VALUE) { if (!this.inlineTagStarted) { this.lastBlockTagValue = this.tagValue; } // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=267833 // Report a problem if a block tag is being used in the context of an inline tag and vice versa. if ((this.inlineTagStarted && JAVADOC_TAG_TYPE[this.tagValue] == TAG_TYPE_BLOCK) || (!this.inlineTagStarted && JAVADOC_TAG_TYPE[this.tagValue] == TAG_TYPE_INLINE)) { valid = false; this.tagValue = TAG_OTHERS_VALUE; this.tagWaitingForDescription = NO_TAG_VALUE; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } return valid; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected boolean parseParam() throws InvalidInputException { boolean valid = super.parseParam(); this.tagWaitingForDescription = valid && this.reportProblems ? TAG_PARAM_VALUE : NO_TAG_VALUE; return valid; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException { char[] src = this.source; // only look for newer task: tags if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { return; } int foundTaskIndex = this.foundTaskCount; char previous = src[commentStart+1]; // should be '*' or '/' for ( int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) { char[] tag = null; char[] priority = null; // check for tag occurrence only if not ambiguous with javadoc tag if (previous != '@') { nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) { tag = this.taskTags[itag]; int tagLength = tag.length; if (tagLength == 0) continue nextTag; // ensure tag is not leaded with letter if tag starts with a letter if (ScannerHelper.isJavaIdentifierStart(this.complianceLevel, tag[0])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, previous)) { continue nextTag; } } for (int t = 0; t < tagLength; t++) { char sc, tc; int x = i+t; if (x >= this.eofPosition || x >= commentEnd) continue nextTag; // case sensitive check if ((sc = src[i + t]) != (tc = tag[t])) { // case insensitive check if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { continue nextTag; } } } // ensure tag is not followed with letter if tag finishes with a letter if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i+tagLength-1])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i + tagLength])) continue nextTag; } if (this.foundTaskTags == null) { this.foundTaskTags = new char[5][]; this.foundTaskMessages = new char[5][]; this.foundTaskPriorities = new char[5][]; this.foundTaskPositions = new int[5][]; } else if (this.foundTaskCount == this.foundTaskTags.length) { System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount); } priority = this.taskPriorities != null && itag < this.taskPriorities.length ? this.taskPriorities[itag] : null; this.foundTaskTags[this.foundTaskCount] = tag; this.foundTaskPriorities[this.foundTaskCount] = priority; this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 }; this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; this.foundTaskCount++; i += tagLength - 1; // will be incremented when looping break nextTag; } } previous = src[i]; } boolean containsEmptyTask = false; for (int i = foundTaskIndex; i < this.foundTaskCount; i++) { // retrieve message start and end positions int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length; int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 : commentEnd - 1; // at most beginning of next task if (max_value < msgStart) { max_value = msgStart; // would only occur if tag is before EOF. } int end = -1; char c; for (int j = msgStart; j < max_value; j++) { if ((c = src[j]) == '\n' || c == '\r') { end = j - 1; break; } } if (end == -1) { for (int j = max_value; j > msgStart; j--) { if ((c = src[j]) == '*') { end = j - 1; break; } } if (end == -1) end = max_value; } if (msgStart == end) { // if the description is empty, we might want to see if two tags are not sharing the same message // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797 containsEmptyTask = true; continue; } // trim the message // we don't trim the beginning of the message to be able to show it after the task tag while (CharOperation.isWhitespace(src[end]) && msgStart <= end) end--; // update the end position of the task this.foundTaskPositions[i][1] = end; // get the message source final int messageLength = end - msgStart + 1; char[] message = new char[messageLength]; System.arraycopy(src, msgStart, message, 0, messageLength); this.foundTaskMessages[i] = message; } if (containsEmptyTask) { for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) { if (this.foundTaskMessages[i].length == 0) { loop: for (int j = i + 1; j < max; j++) { if (this.foundTaskMessages[j].length != 0) { this.foundTaskMessages[i] = this.foundTaskMessages[j]; this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1]; break loop; } } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix) throws InvalidInputException { consumeDigits(radix, false); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final int consumeDigits0(int radix, int usingUnderscore, int invalidPosition, boolean expectingDigitFirst) throws InvalidInputException { int kind = 0; if (getNextChar('_')) { if (expectingDigitFirst) { return invalidPosition; } kind = usingUnderscore; while (getNextChar('_')) {/*empty */} } if (getNextCharAsDigit(radix)) { // continue to read digits or underscore while (getNextCharAsDigit(radix)) {/*empty */} int kind2 = consumeDigits0(radix, usingUnderscore, invalidPosition, false); if (kind2 == 0) { return kind; } return kind2; } if (kind == usingUnderscore) return invalidPosition; return kind; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final boolean getNextCharAsDigit() throws InvalidInputException { //BOOLEAN //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //Both previous lines are true if the currentCharacter is a digit //On false, no side effect has occured. //ALL getNextChar.... ARE OPTIMIZED COPIES if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront return false; int temp = this.currentPosition; try { if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; this.withoutUnicodePtr--; return false; } return true; } else { if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; return false; } if (this.withoutUnicodePtr != 0) unicodeStore(); return true; } } catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; } catch(InvalidInputException e) { this.currentPosition = temp; return false; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException { //BOOLEAN //handle the case of unicode. Jump over the next whiteSpace //making startPosition pointing on the next available char //On false, the currentCharacter is filled up with a potential //correct char this.wasAcr = false; getNextUnicodeChar(); return CharOperation.isWhitespace(this.currentCharacter); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/RecoveryScanner.java
public int getNextToken() throws InvalidInputException { if(this.pendingTokensPtr > -1) { int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } this.fakeTokenSource = null; this.precededByRemoved = false; if(this.data.insertedTokens != null) { for (int i = 0; i <= this.data.insertedTokensPtr; i++) { if(this.data.insertedTokensPosition[i] == this.currentPosition - 1 && i > this.skipNextInsertedTokens) { this.data.insertedTokenUsed[i] = true; this.pendingTokens = this.data.insertedTokens[i]; this.pendingTokensPtr = this.data.insertedTokens[i].length - 1; this.isInserted = true; this.startPosition = this.currentPosition; this.skipNextInsertedTokens = i; int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } } this.skipNextInsertedTokens = -1; } int previousLocation = this.currentPosition; int currentToken = super.getNextToken(); if(this.data.replacedTokens != null) { for (int i = 0; i <= this.data.replacedTokensPtr; i++) { if(this.data.replacedTokensStart[i] >= previousLocation && this.data.replacedTokensStart[i] <= this.startPosition && this.data.replacedTokensEnd[i] >= this.currentPosition - 1) { this.data.replacedTokenUsed[i] = true; this.pendingTokens = this.data.replacedTokens[i]; this.pendingTokensPtr = this.data.replacedTokens[i].length - 1; this.fakeTokenSource = FAKE_IDENTIFIER; this.isInserted = false; this.currentPosition = this.data.replacedTokensEnd[i] + 1; int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } } } if(this.data.removedTokensStart != null) { for (int i = 0; i <= this.data.removedTokensPtr; i++) { if(this.data.removedTokensStart[i] >= previousLocation && this.data.removedTokensStart[i] <= this.startPosition && this.data.removedTokensEnd[i] >= this.currentPosition - 1) { this.data.removedTokenUsed[i] = true; this.currentPosition = this.data.removedTokensEnd[i] + 1; this.precededByRemoved = false; return getNextToken(); } } } return currentToken; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); int start = this.scanner.getCurrentTokenStartPosition(); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && this.currentTokenType == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } this.lineStarted = true; return createMethodReference(receiver, null); } break nextArg; } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { break nextArg; } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseHtmlTag(int previousPosition, int endTextPosition) throws InvalidInputException { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseHref() throws InvalidInputException { boolean skipComments = this.scanner.skipComments; this.scanner.skipComments = true; try { int start = this.scanner.getCurrentTokenStartPosition(); char currentChar = readChar(); if (currentChar == 'a' || currentChar == 'A') { this.scanner.currentPosition = this.index; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); try { if (CharOperation.equals(this.scanner.getCurrentIdentifierSource(), HREF_TAG, false) && readToken() == TerminalTokens.TokenNameEQUAL) { consumeToken(); if (readToken() == TerminalTokens.TokenNameStringLiteral) { consumeToken(); while (this.index < this.javadocEnd) { // main loop to search for the </a> pattern // Skip all characters after string literal until closing '>' (see bug 68726) while (readToken() != TerminalTokens.TokenNameGREATER) { if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' || (this.inlineTagStarted && this.scanner.currentCharacter == '}')) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } return false; } this.currentTokenType = -1; // consume token without updating line end } consumeToken(); // update line end as new lines are allowed in URL description while (readToken() != TerminalTokens.TokenNameLESS) { if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' || (this.inlineTagStarted && this.scanner.currentCharacter == '}')) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } return false; } consumeToken(); } consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); currentChar = readChar(); // search for the </a> pattern and store last char read if (currentChar == '/') { currentChar = readChar(); if (currentChar == 'a' || currentChar =='A') { currentChar = readChar(); if (currentChar == '>') { return true; // valid href } } } // search for invalid char in tags if (currentChar == '\r' || currentChar == '\n' || currentChar == '\t' || currentChar == ' ') { break; } } } } } catch (InvalidInputException ex) { // Do nothing as we want to keep positions for error message } } } // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } } finally { this.scanner.skipComments = skipComments; } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseMember(Object receiver) throws InvalidInputException { // Init this.identifierPtr = -1; this.identifierLengthPtr = -1; int start = this.scanner.getCurrentTokenStartPosition(); this.memberStart = start; // Get member identifier if (readToken() == TerminalTokens.TokenNameIdentifier) { if (this.scanner.currentCharacter == '.') { // member name may be qualified (inner class constructor reference) parseQualifiedName(true); } else { consumeToken(); pushIdentifier(true, false); } // Look for next token to know whether it's a field or method reference int previousPosition = this.index; if (readToken() == TerminalTokens.TokenNameLPAREN) { consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); try { return parseArguments(receiver); } catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); } return null; } // Reset position: we want to rescan last token this.index = previousPosition; this.scanner.currentPosition = previousPosition; this.currentTokenType = -1; // Verify character(s) after identifier (expecting space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } return createFieldReference(receiver); } int end = getTokenEndPosition() - 1; end = start > end ? start : end; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(start, end); // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseParam() throws InvalidInputException { // Store current state int start = this.tagSourceStart; int end = this.tagSourceEnd; boolean tokenWhiteSpace = this.scanner.tokenizeWhiteSpace; this.scanner.tokenizeWhiteSpace = true; try { // Verify that there are whitespaces after tag boolean isCompletionParser = (this.kind & COMPLETION_PARSER) != 0; if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(start, this.scanner.getCurrentTokenEndPosition()); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; } // Get first non whitespace token this.identifierPtr = -1; this.identifierLengthPtr = -1; boolean hasMultiLines = this.scanner.currentPosition > (this.lineEnd+1); boolean isTypeParam = false; boolean valid = true, empty = true; boolean mayBeGeneric = this.sourceLevel >= ClassFileConstants.JDK1_5; int token = -1; nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameIdentifier : if (valid) { // store param name id pushIdentifier(true, false); start = this.scanner.getCurrentTokenStartPosition(); end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); break nextToken; } // $FALL-THROUGH$ - fall through next case to report error case TerminalTokens.TokenNameLESS: if (valid && mayBeGeneric) { // store '<' in identifiers stack as we need to add it to tag element (bug 79809) pushIdentifier(true, true); start = this.scanner.getCurrentTokenStartPosition(); end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); isTypeParam = true; break nextToken; } // $FALL-THROUGH$ - fall through next case to report error default: if (token == TerminalTokens.TokenNameLEFT_SHIFT) isTypeParam = true; if (valid && !hasMultiLines) start = this.scanner.getCurrentTokenStartPosition(); valid = false; if (!hasMultiLines) { empty = false; end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); break; } end = this.lineEnd; // $FALL-THROUGH$ - when several lines, fall through next case to report problem immediately case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.currentPosition > (this.lineEnd+1)) hasMultiLines = true; if (valid) break; // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) if (empty) this.sourceParser.problemReporter().javadocMissingParamName(start, end, this.sourceParser.modifiers); else if (mayBeGeneric && isTypeParam) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); else this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; } } // Scan more tokens for type parameter declaration if (isTypeParam && mayBeGeneric) { // Get type parameter name nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameWHITESPACE: if (valid && this.scanner.currentPosition <= (this.lineEnd+1)) { break; } // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; case TerminalTokens.TokenNameIdentifier : end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); if (valid) { // store param name id pushIdentifier(false, false); break nextToken; } break; default: end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); valid = false; break; } } // Get last character of type parameter declaration boolean spaces = false; nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.currentPosition > (this.lineEnd+1)) { // do not accept type parameter declaration on several lines hasMultiLines = true; valid = false; } spaces = true; if (valid) break; // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; case TerminalTokens.TokenNameGREATER: end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); if (valid) { // store '>' in identifiers stack as we need to add it to tag element (bug 79809) pushIdentifier(false, true); break nextToken; } break; default: if (!spaces) end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); valid = false; break; } } } // Verify that tag name is well followed by white spaces if (valid) { this.currentTokenType = -1; int restart = this.scanner.currentPosition; try { token = readTokenAndConsume(); } catch (InvalidInputException e) { valid = false; } if (token == TerminalTokens.TokenNameWHITESPACE) { this.scanner.resetTo(restart, this.javadocEnd); this.index = restart; return pushParamName(isTypeParam); } } // Report problem this.currentTokenType = -1; if (isCompletionParser) return false; if (this.reportProblems) { // we only need end if we report problems end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); try { while ((token=readToken()) != TerminalTokens.TokenNameWHITESPACE && token != TerminalTokens.TokenNameEOF) { this.currentTokenType = -1; end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); } } catch (InvalidInputException e) { end = this.lineEnd; } if (mayBeGeneric && isTypeParam) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); else this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end); } this.scanner.currentPosition = start; this.index = start; this.currentTokenType = -1; return false; } finally { // we have to make sure that this is reset to the previous value even if an exception occurs this.scanner.tokenizeWhiteSpace = tokenWhiteSpace; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseQualifiedName(boolean reset) throws InvalidInputException { // Reset identifier stack if requested if (reset) { this.identifierPtr = -1; this.identifierLengthPtr = -1; } // Scan tokens int primitiveToken = -1; int parserKind = this.kind & PARSER_KIND; nextToken : for (int iToken = 0; ; iToken++) { int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameIdentifier : if (((iToken & 1) != 0)) { // identifiers must be odd tokens break nextToken; } pushIdentifier(iToken == 0, false); consumeToken(); break; case TerminalTokens.TokenNameDOT : if ((iToken & 1) == 0) { // dots must be even tokens throw new InvalidInputException(); } consumeToken(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: if (iToken == 0) { pushIdentifier(true, true); primitiveToken = token; consumeToken(); break nextToken; } // Fall through default case to verify that we do not leave on a dot //$FALL-THROUGH$ default : if (iToken == 0) { if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return null; } if ((iToken & 1) == 0) { // cannot leave on a dot switch (parserKind) { case COMPLETION_PARSER: if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return syntaxRecoverQualifiedName(primitiveToken); case DOM_PARSER: if (this.currentTokenType != -1) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } // $FALL-THROUGH$ - fall through default case to raise exception default: throw new InvalidInputException(); } } break nextToken; } } // Reset position: we want to rescan last token if (parserKind != COMPLETION_PARSER && this.currentTokenType != -1) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return createTypeReference(primitiveToken); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseReference() throws InvalidInputException { int currentPosition = this.scanner.currentPosition; try { Object typeRef = null; Object reference = null; int previousPosition = -1; int typeRefStartPosition = -1; // Get reference tokens nextToken : while (this.index < this.scanner.eofPosition) { previousPosition = this.index; int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameStringLiteral : // @see "string" // If typeRef != null we may raise a warning here to let user know there's an unused reference... // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) if (typeRef != null) break nextToken; consumeToken(); int start = this.scanner.getCurrentTokenStartPosition(); if (this.tagValue == TAG_VALUE_VALUE) { // String reference are not allowed for @value tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getTokenEndPosition(), this.sourceParser.modifiers); return false; } // verify end line if (verifyEndLine(previousPosition)) { return createFakeReference(start); } if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd); return false; case TerminalTokens.TokenNameLESS : // @see <a href="URL#Value">label</a> // If typeRef != null we may raise a warning here to let user know there's an unused reference... // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) if (typeRef != null) break nextToken; consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); if (parseHref()) { consumeToken(); if (this.tagValue == TAG_VALUE_VALUE) { // String reference are not allowed for @value tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getIndexPosition(), this.sourceParser.modifiers); return false; } // verify end line if (verifyEndLine(previousPosition)) { return createFakeReference(start); } if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd); } else if (this.tagValue == TAG_VALUE_VALUE) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getIndexPosition(), this.sourceParser.modifiers); } return false; case TerminalTokens.TokenNameERROR : consumeToken(); if (this.scanner.currentCharacter == '#') { // @see ...#member reference = parseMember(typeRef); if (reference != null) { return pushSeeRef(reference); } return false; } char[] currentError = this.scanner.getCurrentIdentifierSource(); if (currentError.length>0 && currentError[0] == '"') { if (this.reportProblems) { boolean isUrlRef = false; if (this.tagValue == TAG_SEE_VALUE) { int length=currentError.length, i=1 /* first char is " */; while (i<length && ScannerHelper.isLetter(currentError[i])) { i++; } if (i<(length-2) && currentError[i] == ':' && currentError[i+1] == '/' && currentError[i+2] == '/') { isUrlRef = true; } } if (isUrlRef) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=207765 // handle invalid URL references in javadoc with dedicated message this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition()); } else { this.sourceParser.problemReporter().javadocInvalidReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition()); } } return false; } break nextToken; case TerminalTokens.TokenNameIdentifier : if (typeRef == null) { typeRefStartPosition = this.scanner.getCurrentTokenStartPosition(); typeRef = parseQualifiedName(true); if (this.abort) return false; // May be aborted by specialized parser break; } break nextToken; default : break nextToken; } } // Verify that we got a reference if (reference == null) reference = typeRef; if (reference == null) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; if (this.tagValue == TAG_VALUE_VALUE) { if ((this.kind & DOM_PARSER) != 0) createTag(); return true; } if (this.reportProblems) { this.sourceParser.problemReporter().javadocMissingReference(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers); } return false; } // Reset position at the end of type reference if (this.lastIdentifierEndPosition > this.javadocStart) { this.index = this.lastIdentifierEndPosition+1; this.scanner.currentPosition = this.index; } this.currentTokenType = -1; // In case of @value, we have an invalid reference (only static field refs are valid for this tag) if (this.tagValue == TAG_VALUE_VALUE) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(typeRefStartPosition, this.lineEnd); return false; } int currentIndex = this.index; // store current index char ch = readChar(); switch (ch) { // Verify that line end does not start with an open parenthese (which could be a constructor reference wrongly written...) // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=47215 case '(' : if (this.reportProblems) this.sourceParser.problemReporter().javadocMissingHashCharacter(typeRefStartPosition, this.lineEnd, String.valueOf(this.source, typeRefStartPosition, this.lineEnd-typeRefStartPosition+1)); return false; // Search for the :// URL pattern // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=168849 case ':' : ch = readChar(); if (ch == '/' && ch == readChar()) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(typeRefStartPosition, this.lineEnd); return false; } } } // revert to last stored index this.index = currentIndex; // Verify that we get white space after reference if (!verifySpaceOrEndComment()) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(typeRefStartPosition, end); return false; } // Everything is OK, store reference return pushSeeRef(reference); } catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); } // Reset position to avoid missing tokens when new line was encountered this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected int readToken() throws InvalidInputException { if (this.currentTokenType < 0) { this.tokenPreviousPosition = this.scanner.currentPosition; this.currentTokenType = this.scanner.getNextToken(); if (this.scanner.currentPosition > (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line) this.lineStarted = false; while (this.currentTokenType == TerminalTokens.TokenNameMULTIPLY) { this.currentTokenType = this.scanner.getNextToken(); } } this.index = this.scanner.currentPosition; this.lineStarted = true; // after having read a token, line is obviously started... } return this.currentTokenType; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected int readTokenAndConsume() throws InvalidInputException { int token = readToken(); consumeToken(); return token; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException { // do nothing, just an entry point for recovery return null; }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { MethodRefParameter argument = this.ast.newMethodRefParameter(); ASTNode node = (ASTNode) typeRef; int argStart = node.getStartPosition(); int argEnd = node.getStartPosition()+node.getLength()-1; if (dim > 0) argEnd = (int) dimPositions[dim-1]; if (argNamePos >= 0) argEnd = (int) argNamePos; if (name.length != 0) { final SimpleName argName = new SimpleName(this.ast); argName.internalSetIdentifier(new String(name)); argument.setName(argName); int argNameStart = (int) (argNamePos >>> 32); argName.setSourceRange(argNameStart, argEnd-argNameStart+1); } Type argType = null; if (node.getNodeType() == ASTNode.PRIMITIVE_TYPE) { argType = (PrimitiveType) node; // if (dim > 0) { // argType = this.ast.newArrayType(argType, dim); // argType.setSourceRange(argStart, ((int) dimPositions[dim-1])-argStart+1); // } } else { Name argTypeName = (Name) node; argType = this.ast.newSimpleType(argTypeName); argType.setSourceRange(argStart, node.getLength()); } if (dim > 0 && !isVarargs) { for (int i=0; i<dim; i++) { argType = this.ast.newArrayType(argType); argType.setSourceRange(argStart, ((int) dimPositions[i])-argStart+1); } } argument.setType(argType); argument.setSourceRange(argStart, argEnd - argStart + 1); return argument; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { MemberRef fieldRef = this.ast.newMemberRef(); SimpleName fieldName = new SimpleName(this.ast); fieldName.internalSetIdentifier(new String(this.identifierStack[0])); fieldRef.setName(fieldName); int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; fieldName.setSourceRange(start, end - start + 1); if (receiver == null) { start = this.memberStart; fieldRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; fieldRef.setQualifier(typeRef); start = typeRef.getStartPosition(); end = fieldName.getStartPosition()+fieldName.getLength()-1; fieldRef.setSourceRange(start, end-start+1); } return fieldRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Create method ref MethodRef methodRef = this.ast.newMethodRef(); SimpleName methodName = new SimpleName(this.ast); int length = this.identifierLengthStack[0] - 1; // may be > 0 for member class constructor reference methodName.internalSetIdentifier(new String(this.identifierStack[length])); methodRef.setName(methodName); int start = (int) (this.identifierPositionStack[length] >>> 32); int end = (int) this.identifierPositionStack[length]; methodName.setSourceRange(start, end - start + 1); // Set qualifier if (receiver == null) { start = this.memberStart; methodRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; methodRef.setQualifier(typeRef); start = typeRef.getStartPosition(); } // Add arguments if (arguments != null) { Iterator parameters = arguments.listIterator(); while (parameters.hasNext()) { MethodRefParameter param = (MethodRefParameter) parameters.next(); methodRef.parameters().add(param); } } methodRef.setSourceRange(start, this.scanner.getCurrentTokenEndPosition()-start+1); return methodRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Read tag name int currentPosition = this.index; int token = readTokenAndConsume(); char[] tagName = CharOperation.NO_CHAR; if (currentPosition == this.scanner.startPosition) { this.tagSourceStart = this.scanner.getCurrentTokenStartPosition(); this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); tagName = this.scanner.getCurrentIdentifierSource(); } else { this.tagSourceEnd = currentPosition-1; } // Try to get tag name other than java identifier // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660) if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { tagNameToken: while (token != TerminalTokens.TokenNameEOF && this.index < this.scanner.eofPosition) { int length = tagName.length; // !, ", #, %, &, ', -, :, <, >, * chars and spaces are not allowed in tag names switch (this.scanner.currentCharacter) { case '}': case '*': // break for '*' as this is perhaps the end of comment (bug 65288) case '!': case '#': case '%': case '&': case '\'': case '"': case ':': case '<': case '>': break tagNameToken; case '-': // allowed in tag names as this character is often used in doclets (bug 68087) System.arraycopy(tagName, 0, tagName = new char[length+1], 0, length); tagName[length] = this.scanner.currentCharacter; break; default: if (this.scanner.currentCharacter == ' ' || ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { break tagNameToken; } token = readTokenAndConsume(); char[] ident = this.scanner.getCurrentIdentifierSource(); System.arraycopy(tagName, 0, tagName = new char[length+ident.length], 0, length); System.arraycopy(ident, 0, tagName, length, ident.length); break; } this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); this.scanner.getNextChar(); this.index = this.scanner.currentPosition; } } int length = tagName.length; this.index = this.tagSourceEnd+1; this.scanner.currentPosition = this.tagSourceEnd+1; this.tagSourceStart = previousPosition; // tage name may be empty (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=125903) if (tagName.length == 0) { return false; } // Decide which parse to perform depending on tag name this.tagValue = NO_TAG_VALUE; boolean valid = true; switch (token) { case TerminalTokens.TokenNameIdentifier : switch (tagName[0]) { case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName)) { this.tagValue = TAG_CATEGORY_VALUE; valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) { this.deprecated = true; this.tagValue = TAG_DEPRECATED_VALUE; } else { this.tagValue = TAG_OTHERS_VALUE; } createTag(); break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName)) { if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } this.tagValue = TAG_INHERITDOC_VALUE; } else { this.tagValue = TAG_OTHERS_VALUE; } createTag(); break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) { this.tagValue = TAG_PARAM_VALUE; valid = parseParam(); } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) { this.tagValue = TAG_EXCEPTION_VALUE; valid = parseThrows(); } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) { this.tagValue = TAG_SEE_VALUE; if (this.inlineTagStarted) { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @see inside inline comment valid = false; } else { valid = parseReference(); } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) { this.tagValue = TAG_LINK_VALUE; } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName)) { this.tagValue = TAG_LINKPLAIN_VALUE; } if (this.tagValue != NO_TAG_VALUE) { if (this.inlineTagStarted) { valid = parseReference(); } else { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @link outside inline comment valid = false; } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'v': if (this.sourceLevel >= ClassFileConstants.JDK1_5 && length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName)) { this.tagValue = TAG_VALUE_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; default: this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case TerminalTokens.TokenNamereturn : this.tagValue = TAG_RETURN_VALUE; valid = parseReturn(); break; case TerminalTokens.TokenNamethrows : this.tagValue = TAG_THROWS_VALUE; valid = parseThrows(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: case TerminalTokens.TokenNameenum : case TerminalTokens.TokenNameconst : case TerminalTokens.TokenNamegoto : this.tagValue = TAG_OTHERS_VALUE; createTag(); break; } this.textStart = this.index; return valid; }
(Domain) JavaModelException 133
              
// 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/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
protected IBinaryType getBinaryInfo(ClassFile classFile, IResource resource) throws CoreException { BinaryType binaryType = (BinaryType) classFile.getType(); if (classFile.isOpen()) return (IBinaryType) binaryType.getElementInfo(); // reuse the info from the java model cache // create a temporary info IBinaryType info; try { PackageFragment pkg = (PackageFragment) classFile.getParent(); PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent(); if (root.isArchive()) { // class file in a jar String classFileName = classFile.getElementName(); String classFilePath = Util.concatWith(pkg.names, classFileName, '/'); ZipFile zipFile = null; try { zipFile = ((JarPackageFragmentRoot) root).getJar(); info = ClassFileReader.read(zipFile, classFilePath); } finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } } else { // class file in a directory info = Util.newClassFileReader(resource); } if (info == null) throw binaryType.newNotPresentException(); return info; } catch (ClassFormatException e) { //e.printStackTrace(); return null; } catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// 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, 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 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/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/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/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/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 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/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/JarEntryFile.java
public InputStream getContents() throws CoreException { ZipFile zipFile = null; try { zipFile = getZipFile(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } String entryName = getEntryName(); ZipEntry zipEntry = zipFile.getEntry(entryName); if (zipEntry == null){ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entryName)); } byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); return new ByteArrayInputStream(contents); } catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } }
// 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/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/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/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/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/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 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/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 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 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
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/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
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
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/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
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/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/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/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/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 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
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/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/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/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
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 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 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/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 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/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/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/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/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 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 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/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, 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/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/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/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 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, 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 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 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/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/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/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/Initializer.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this)); }
72
              
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
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(), "&nbsp;".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 } } }
(Domain) ClassFormatException 69
              
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeFieldType(char[] signature) throws ClassFormatException { if (signature == null) return null; int arrayDim = 0; for (int i = 0, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[][] decodeParameterTypes(char[] signature, boolean firstIsSynthetic) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return null; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } char[][] parameterTypes = new char[3][]; int parameterTypesCounter = 0; int arrayDim = 0; for (int i = 1; i < indexOfClosingParen; i++) { if (parameterTypesCounter == parameterTypes.length) { // resize System.arraycopy(parameterTypes, 0, (parameterTypes = new char[parameterTypesCounter * 2][]), 0, parameterTypesCounter); } switch(signature[i]) { case 'B': parameterTypes[parameterTypesCounter++] = BYTE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'C': parameterTypes[parameterTypesCounter++] = CHAR; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'D': parameterTypes[parameterTypesCounter++] = DOUBLE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'F': parameterTypes[parameterTypesCounter++] = FLOAT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'I': parameterTypes[parameterTypesCounter++] = INT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'J': parameterTypes[parameterTypesCounter++] = LONG; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (firstIsSynthetic && parameterTypesCounter == 0) { // skip first synthetic parameter firstIsSynthetic = false; } else { parameterTypes[parameterTypesCounter++] = replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); } i = indexOfSemiColon; arrayDim = 0; break; case 'S': parameterTypes[parameterTypesCounter++] = SHORT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'Z': parameterTypes[parameterTypesCounter++] = BOOLEAN; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } if (parameterTypes.length != parameterTypesCounter) { System.arraycopy(parameterTypes, 0, parameterTypes = new char[parameterTypesCounter][], 0, parameterTypesCounter); } return parameterTypes; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeReturnType(char[] signature) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); int arrayDim = 0; for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private int extractArgCount(char[] signature, char[] className) throws ClassFormatException { int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return 0; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } int parameterTypesCounter = 0; for (int i = 1; i < indexOfClosingParen; i++) { switch(signature[i]) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': parameterTypesCounter++; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); // verify if first parameter is synthetic if (className != null && parameterTypesCounter == 0) { char[] classSignature = Signature.createCharArrayTypeSignature(className, true); int length = indexOfSemiColon-i+1; if (classSignature.length > (length+1)) { // synthetic means that parameter type has same signature than given class for (int j=i, k=0; j<indexOfSemiColon; j++, k++) { if (!(signature[j] == classSignature[k] || (signature[j] == '/' && classSignature[k] == '.' ))) { parameterTypesCounter++; break; } } } else { parameterTypesCounter++; } className = null; // do not verify following parameters } else { parameterTypesCounter++; } i = indexOfSemiColon; break; case '[': break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return parameterTypesCounter; }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, ClassFileBytesDisassembler.DEFAULT); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, mode); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/CodeAttribute.java
public void traverse(IBytecodeVisitor visitor) throws ClassFormatException { int pc = this.codeOffset; int opcode, index, _const, branchOffset; IConstantPoolEntry constantPoolEntry; while (true) { opcode = u1At(this.classFileBytes, 0, pc); switch(opcode) { case IOpcodeMnemonics.NOP : visitor._nop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ACONST_NULL : visitor._aconst_null(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_M1 : visitor._iconst_m1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_0 : visitor._iconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_1 : visitor._iconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_2 : visitor._iconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_3 : visitor._iconst_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_4 : visitor._iconst_4(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_5 : visitor._iconst_5(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_0 : visitor._lconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_1 : visitor._lconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_0 : visitor._fconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_1 : visitor._fconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_2 : visitor._fconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_0 : visitor._dconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_1 : visitor._dconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BIPUSH : visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); pc+=2; break; case IOpcodeMnemonics.SIPUSH : visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); pc+=3; break; case IOpcodeMnemonics.LDC : index = u1At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); pc+=2; break; case IOpcodeMnemonics.LDC_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.LDC2_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Long) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ILOAD : index = u1At(this.classFileBytes, 1, pc); visitor._iload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._lload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._fload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._dload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ALOAD : index = u1At(this.classFileBytes, 1, pc); visitor._aload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ILOAD_0 : visitor._iload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_1 : visitor._iload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_2 : visitor._iload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_3 : visitor._iload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_0 : visitor._lload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_1 : visitor._lload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_2 : visitor._lload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_3 : visitor._lload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_0 : visitor._fload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_1 : visitor._fload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_2 : visitor._fload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_3 : visitor._fload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_0 : visitor._dload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_1 : visitor._dload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_2 : visitor._dload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_3 : visitor._dload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_0 : visitor._aload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_1 : visitor._aload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_2 : visitor._aload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_3 : visitor._aload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IALOAD : visitor._iaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LALOAD : visitor._laload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FALOAD : visitor._faload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DALOAD : visitor._daload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AALOAD : visitor._aaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BALOAD : visitor._baload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CALOAD : visitor._caload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SALOAD : visitor._saload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE : index = u1At(this.classFileBytes, 1, pc); visitor._istore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._lstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._fstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._dstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ASTORE : index = u1At(this.classFileBytes, 1, pc); visitor._astore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ISTORE_0 : visitor._istore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_1 : visitor._istore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_2 : visitor._istore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_3 : visitor._istore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_0 : visitor._lstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_1 : visitor._lstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_2 : visitor._lstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_3 : visitor._lstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_0 : visitor._fstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_1 : visitor._fstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_2 : visitor._fstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_3 : visitor._fstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_0 : visitor._dstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_1 : visitor._dstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_2 : visitor._dstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_3 : visitor._dstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_0 : visitor._astore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_1 : visitor._astore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_2 : visitor._astore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_3 : visitor._astore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IASTORE : visitor._iastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LASTORE : visitor._lastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FASTORE : visitor._fastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DASTORE : visitor._dastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AASTORE : visitor._aastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BASTORE : visitor._bastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CASTORE : visitor._castore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SASTORE : visitor._sastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP : visitor._pop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP2 : visitor._pop2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP : visitor._dup(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X1 : visitor._dup_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X2 : visitor._dup_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2 : visitor._dup2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X1 : visitor._dup2_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X2 : visitor._dup2_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SWAP : visitor._swap(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IADD : visitor._iadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LADD : visitor._ladd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FADD : visitor._fadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DADD : visitor._dadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISUB : visitor._isub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSUB : visitor._lsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSUB : visitor._fsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSUB : visitor._dsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMUL : visitor._imul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LMUL : visitor._lmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FMUL : visitor._fmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DMUL : visitor._dmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IDIV : visitor._idiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LDIV : visitor._ldiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FDIV : visitor._fdiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DDIV : visitor._ddiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IREM : visitor._irem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LREM : visitor._lrem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FREM : visitor._frem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DREM : visitor._drem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.INEG : visitor._ineg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LNEG : visitor._lneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FNEG : visitor._fneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DNEG : visitor._dneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHL : visitor._ishl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHL : visitor._lshl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHR : visitor._ishr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHR : visitor._lshr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IUSHR : visitor._iushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LUSHR : visitor._lushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IAND : visitor._iand(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LAND : visitor._land(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IOR : visitor._ior(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LOR : visitor._lor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IXOR : visitor._ixor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LXOR : visitor._lxor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IINC : index = u1At(this.classFileBytes, 1, pc); _const = i1At(this.classFileBytes, 2, pc); visitor._iinc(pc - this.codeOffset, index, _const); pc+=3; break; case IOpcodeMnemonics.I2L : visitor._i2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2F : visitor._i2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2D : visitor._i2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2I : visitor._l2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2F : visitor._l2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2D : visitor._l2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2I : visitor._f2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2L : visitor._f2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2D : visitor._f2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2I : visitor._d2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2L : visitor._d2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2F : visitor._d2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2B : visitor._i2b(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2C : visitor._i2c(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2S : visitor._i2s(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCMP : visitor._lcmp(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPL : visitor._fcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPG : visitor._fcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPL : visitor._dcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPG : visitor._dcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IFEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._iflt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifle(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmplt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmple(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._goto(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.JSR : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._jsr(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.RET : index = u1At(this.classFileBytes, 1, pc); visitor._ret(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.TABLESWITCH : int startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 pc++; } int defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int low = i4At(this.classFileBytes, 0, pc); pc += 4; int high = i4At(this.classFileBytes, 0, pc); pc += 4; int length = high - low + 1; int[] jumpOffsets = new int[length]; for (int i = 0; i < length; i++) { jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); break; case IOpcodeMnemonics.LOOKUPSWITCH : startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { pc++; } defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int npairs = (int) u4At(this.classFileBytes, 0, pc); int[][] offset_pairs = new int[npairs][2]; pc += 4; for (int i = 0; i < npairs; i++) { offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); pc += 4; offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); break; case IOpcodeMnemonics.IRETURN : visitor._ireturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LRETURN : visitor._lreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FRETURN : visitor._freturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DRETURN : visitor._dreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ARETURN : visitor._areturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.RETURN : visitor._return(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.GETSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.GETFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEVIRTUAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESPECIAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEINTERFACE : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_InterfaceMethodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } byte count = (byte) u1At(this.classFileBytes, 3, pc); int extraArgs = u1At(this.classFileBytes, 4, pc); if (extraArgs != 0) { throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); } visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); pc += 5; break; case IOpcodeMnemonics.INVOKEDYNAMIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_NameAndType) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokedynamic( pc - this.codeOffset, index, this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoNameIndex()), this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoDescriptorIndex())); pc += 5; break; case IOpcodeMnemonics.NEW : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._new(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.NEWARRAY : int atype = u1At(this.classFileBytes, 1, pc); visitor._newarray(pc - this.codeOffset, atype); pc+=2; break; case IOpcodeMnemonics.ANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ARRAYLENGTH : visitor._arraylength(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ATHROW : visitor._athrow(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CHECKCAST : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INSTANCEOF : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.MONITORENTER : visitor._monitorenter(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.MONITOREXIT : visitor._monitorexit(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.WIDE : opcode = u1At(this.classFileBytes, 1, pc); if (opcode == IOpcodeMnemonics.IINC) { index = u2At(this.classFileBytes, 2, pc); _const = i2At(this.classFileBytes, 4, pc); visitor._wide(pc - this.codeOffset, opcode, index, _const); pc += 6; } else { index = u2At(this.classFileBytes, 2, pc); visitor._wide(pc - this.codeOffset , opcode, index); pc += 4; } break; case IOpcodeMnemonics.MULTIANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } int dimensions = u1At(this.classFileBytes, 3, pc); visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); pc+=4; break; case IOpcodeMnemonics.IFNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNONNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnonnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._goto_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.JSR_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._jsr_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.BREAKPOINT : visitor._breakpoint(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP1 : visitor._impdep1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP2 : visitor._impdep2(pc - this.codeOffset); pc++; break; default: throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); } if (pc >= (this.codeLength + this.codeOffset)) { break; } } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/FieldInfo.java
public void throwFormatException() throws ClassFormatException { throw new ClassFormatException(ClassFormatException.ErrBadFieldInfo); }
4
              
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
54
              
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeFieldType(char[] signature) throws ClassFormatException { if (signature == null) return null; int arrayDim = 0; for (int i = 0, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[][] decodeParameterTypes(char[] signature, boolean firstIsSynthetic) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return null; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } char[][] parameterTypes = new char[3][]; int parameterTypesCounter = 0; int arrayDim = 0; for (int i = 1; i < indexOfClosingParen; i++) { if (parameterTypesCounter == parameterTypes.length) { // resize System.arraycopy(parameterTypes, 0, (parameterTypes = new char[parameterTypesCounter * 2][]), 0, parameterTypesCounter); } switch(signature[i]) { case 'B': parameterTypes[parameterTypesCounter++] = BYTE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'C': parameterTypes[parameterTypesCounter++] = CHAR; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'D': parameterTypes[parameterTypesCounter++] = DOUBLE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'F': parameterTypes[parameterTypesCounter++] = FLOAT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'I': parameterTypes[parameterTypesCounter++] = INT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'J': parameterTypes[parameterTypesCounter++] = LONG; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (firstIsSynthetic && parameterTypesCounter == 0) { // skip first synthetic parameter firstIsSynthetic = false; } else { parameterTypes[parameterTypesCounter++] = replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); } i = indexOfSemiColon; arrayDim = 0; break; case 'S': parameterTypes[parameterTypesCounter++] = SHORT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'Z': parameterTypes[parameterTypesCounter++] = BOOLEAN; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } if (parameterTypes.length != parameterTypesCounter) { System.arraycopy(parameterTypes, 0, parameterTypes = new char[parameterTypesCounter][], 0, parameterTypesCounter); } return parameterTypes; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeReturnType(char[] signature) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); int arrayDim = 0; for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private int extractArgCount(char[] signature, char[] className) throws ClassFormatException { int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return 0; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } int parameterTypesCounter = 0; for (int i = 1; i < indexOfClosingParen; i++) { switch(signature[i]) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': parameterTypesCounter++; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); // verify if first parameter is synthetic if (className != null && parameterTypesCounter == 0) { char[] classSignature = Signature.createCharArrayTypeSignature(className, true); int length = indexOfSemiColon-i+1; if (classSignature.length > (length+1)) { // synthetic means that parameter type has same signature than given class for (int j=i, k=0; j<indexOfSemiColon; j++, k++) { if (!(signature[j] == classSignature[k] || (signature[j] == '/' && classSignature[k] == '.' ))) { parameterTypesCounter++; break; } } } else { parameterTypesCounter++; } className = null; // do not verify following parameters } else { parameterTypesCounter++; } i = indexOfSemiColon; break; case '[': break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return parameterTypesCounter; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private void extractReferenceFromConstantPool(byte[] contents, ClassFileReader reader) throws ClassFormatException { int[] constantPoolOffsets = reader.getConstantPoolOffsets(); int constantPoolCount = constantPoolOffsets.length; for (int i = 1; i < constantPoolCount; i++) { int tag = reader.u1At(constantPoolOffsets[i]); /** * u1 tag * u2 class_index * u2 name_and_type_index */ char[] name = null; char[] type = null; switch (tag) { case ClassFileConstants.FieldRefTag : // add reference to the class/interface and field name and type name = extractName(constantPoolOffsets, reader, i); addFieldReference(name); break; case ClassFileConstants.MethodRefTag : // add reference to the class and method name and type case ClassFileConstants.InterfaceMethodRefTag : // add reference to the interface and method name and type name = extractName(constantPoolOffsets, reader, i); type = extractType(constantPoolOffsets, reader, i); if (CharOperation.equals(INIT, name)) { // get class name and see if it's a local type or not char[] className = extractClassName(constantPoolOffsets, reader, i); boolean localType = false; if (className != null) { for (int c = 0, max = className.length; c < max; c++) { switch (className[c]) { case '/': className[c] = '.'; break; case '$': localType = true; break; } } } // add a constructor reference, use class name to extract arg count if it's a local type to remove synthetic parameter addConstructorReference(className, extractArgCount(type, localType?className:null)); } else { // add a method reference addMethodReference(name, extractArgCount(type, null)); } break; case ClassFileConstants.ClassTag : // add a type reference name = extractClassReference(constantPoolOffsets, reader, i); if (name.length > 0 && name[0] == '[') break; // skip over array references name = replace('/', '.', name); // so that it looks like java.lang.String addTypeReference(name); // also add a simple reference on each segment of the qualification (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24741) char[][] qualification = CharOperation.splitOn('.', name); for (int j = 0, length = qualification.length; j < length; j++) { addNameReference(qualification[j]); } break; } } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, ClassFileBytesDisassembler.DEFAULT); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, mode); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/CodeAttribute.java
public void traverse(IBytecodeVisitor visitor) throws ClassFormatException { int pc = this.codeOffset; int opcode, index, _const, branchOffset; IConstantPoolEntry constantPoolEntry; while (true) { opcode = u1At(this.classFileBytes, 0, pc); switch(opcode) { case IOpcodeMnemonics.NOP : visitor._nop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ACONST_NULL : visitor._aconst_null(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_M1 : visitor._iconst_m1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_0 : visitor._iconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_1 : visitor._iconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_2 : visitor._iconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_3 : visitor._iconst_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_4 : visitor._iconst_4(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_5 : visitor._iconst_5(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_0 : visitor._lconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_1 : visitor._lconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_0 : visitor._fconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_1 : visitor._fconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_2 : visitor._fconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_0 : visitor._dconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_1 : visitor._dconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BIPUSH : visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); pc+=2; break; case IOpcodeMnemonics.SIPUSH : visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); pc+=3; break; case IOpcodeMnemonics.LDC : index = u1At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); pc+=2; break; case IOpcodeMnemonics.LDC_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.LDC2_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Long) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ILOAD : index = u1At(this.classFileBytes, 1, pc); visitor._iload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._lload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._fload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._dload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ALOAD : index = u1At(this.classFileBytes, 1, pc); visitor._aload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ILOAD_0 : visitor._iload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_1 : visitor._iload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_2 : visitor._iload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_3 : visitor._iload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_0 : visitor._lload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_1 : visitor._lload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_2 : visitor._lload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_3 : visitor._lload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_0 : visitor._fload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_1 : visitor._fload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_2 : visitor._fload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_3 : visitor._fload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_0 : visitor._dload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_1 : visitor._dload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_2 : visitor._dload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_3 : visitor._dload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_0 : visitor._aload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_1 : visitor._aload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_2 : visitor._aload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_3 : visitor._aload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IALOAD : visitor._iaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LALOAD : visitor._laload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FALOAD : visitor._faload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DALOAD : visitor._daload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AALOAD : visitor._aaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BALOAD : visitor._baload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CALOAD : visitor._caload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SALOAD : visitor._saload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE : index = u1At(this.classFileBytes, 1, pc); visitor._istore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._lstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._fstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._dstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ASTORE : index = u1At(this.classFileBytes, 1, pc); visitor._astore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ISTORE_0 : visitor._istore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_1 : visitor._istore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_2 : visitor._istore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_3 : visitor._istore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_0 : visitor._lstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_1 : visitor._lstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_2 : visitor._lstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_3 : visitor._lstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_0 : visitor._fstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_1 : visitor._fstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_2 : visitor._fstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_3 : visitor._fstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_0 : visitor._dstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_1 : visitor._dstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_2 : visitor._dstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_3 : visitor._dstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_0 : visitor._astore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_1 : visitor._astore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_2 : visitor._astore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_3 : visitor._astore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IASTORE : visitor._iastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LASTORE : visitor._lastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FASTORE : visitor._fastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DASTORE : visitor._dastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AASTORE : visitor._aastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BASTORE : visitor._bastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CASTORE : visitor._castore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SASTORE : visitor._sastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP : visitor._pop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP2 : visitor._pop2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP : visitor._dup(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X1 : visitor._dup_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X2 : visitor._dup_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2 : visitor._dup2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X1 : visitor._dup2_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X2 : visitor._dup2_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SWAP : visitor._swap(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IADD : visitor._iadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LADD : visitor._ladd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FADD : visitor._fadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DADD : visitor._dadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISUB : visitor._isub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSUB : visitor._lsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSUB : visitor._fsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSUB : visitor._dsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMUL : visitor._imul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LMUL : visitor._lmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FMUL : visitor._fmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DMUL : visitor._dmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IDIV : visitor._idiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LDIV : visitor._ldiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FDIV : visitor._fdiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DDIV : visitor._ddiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IREM : visitor._irem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LREM : visitor._lrem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FREM : visitor._frem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DREM : visitor._drem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.INEG : visitor._ineg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LNEG : visitor._lneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FNEG : visitor._fneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DNEG : visitor._dneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHL : visitor._ishl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHL : visitor._lshl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHR : visitor._ishr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHR : visitor._lshr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IUSHR : visitor._iushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LUSHR : visitor._lushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IAND : visitor._iand(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LAND : visitor._land(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IOR : visitor._ior(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LOR : visitor._lor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IXOR : visitor._ixor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LXOR : visitor._lxor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IINC : index = u1At(this.classFileBytes, 1, pc); _const = i1At(this.classFileBytes, 2, pc); visitor._iinc(pc - this.codeOffset, index, _const); pc+=3; break; case IOpcodeMnemonics.I2L : visitor._i2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2F : visitor._i2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2D : visitor._i2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2I : visitor._l2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2F : visitor._l2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2D : visitor._l2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2I : visitor._f2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2L : visitor._f2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2D : visitor._f2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2I : visitor._d2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2L : visitor._d2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2F : visitor._d2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2B : visitor._i2b(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2C : visitor._i2c(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2S : visitor._i2s(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCMP : visitor._lcmp(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPL : visitor._fcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPG : visitor._fcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPL : visitor._dcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPG : visitor._dcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IFEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._iflt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifle(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmplt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmple(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._goto(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.JSR : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._jsr(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.RET : index = u1At(this.classFileBytes, 1, pc); visitor._ret(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.TABLESWITCH : int startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 pc++; } int defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int low = i4At(this.classFileBytes, 0, pc); pc += 4; int high = i4At(this.classFileBytes, 0, pc); pc += 4; int length = high - low + 1; int[] jumpOffsets = new int[length]; for (int i = 0; i < length; i++) { jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); break; case IOpcodeMnemonics.LOOKUPSWITCH : startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { pc++; } defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int npairs = (int) u4At(this.classFileBytes, 0, pc); int[][] offset_pairs = new int[npairs][2]; pc += 4; for (int i = 0; i < npairs; i++) { offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); pc += 4; offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); break; case IOpcodeMnemonics.IRETURN : visitor._ireturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LRETURN : visitor._lreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FRETURN : visitor._freturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DRETURN : visitor._dreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ARETURN : visitor._areturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.RETURN : visitor._return(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.GETSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.GETFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEVIRTUAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESPECIAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEINTERFACE : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_InterfaceMethodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } byte count = (byte) u1At(this.classFileBytes, 3, pc); int extraArgs = u1At(this.classFileBytes, 4, pc); if (extraArgs != 0) { throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); } visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); pc += 5; break; case IOpcodeMnemonics.INVOKEDYNAMIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_NameAndType) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokedynamic( pc - this.codeOffset, index, this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoNameIndex()), this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoDescriptorIndex())); pc += 5; break; case IOpcodeMnemonics.NEW : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._new(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.NEWARRAY : int atype = u1At(this.classFileBytes, 1, pc); visitor._newarray(pc - this.codeOffset, atype); pc+=2; break; case IOpcodeMnemonics.ANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ARRAYLENGTH : visitor._arraylength(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ATHROW : visitor._athrow(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CHECKCAST : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INSTANCEOF : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.MONITORENTER : visitor._monitorenter(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.MONITOREXIT : visitor._monitorexit(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.WIDE : opcode = u1At(this.classFileBytes, 1, pc); if (opcode == IOpcodeMnemonics.IINC) { index = u2At(this.classFileBytes, 2, pc); _const = i2At(this.classFileBytes, 4, pc); visitor._wide(pc - this.codeOffset, opcode, index, _const); pc += 6; } else { index = u2At(this.classFileBytes, 2, pc); visitor._wide(pc - this.codeOffset , opcode, index); pc += 4; } break; case IOpcodeMnemonics.MULTIANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } int dimensions = u1At(this.classFileBytes, 3, pc); visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); pc+=4; break; case IOpcodeMnemonics.IFNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNONNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnonnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._goto_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.JSR_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._jsr_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.BREAKPOINT : visitor._breakpoint(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP1 : visitor._impdep1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP2 : visitor._impdep2(pc - this.codeOffset); pc++; break; default: throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); } if (pc >= (this.codeLength + this.codeOffset)) { break; } } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file) throws ClassFormatException, IOException { return read(file, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getFileByteContent(file); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, file.getAbsolutePath().toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName) throws ClassFormatException, IOException { return read(stream, fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getInputStreamAsByteArray(stream, -1); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, fileName.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename) throws ClassFormatException, java.io.IOException { return read(zip, filename, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { java.util.zip.ZipEntry ze = zip.getEntry(filename); if (ze == null) return null; byte classFileBytes[] = Util.getZipEntryByteContent(ze, zip); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, filename.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName) throws ClassFormatException, java.io.IOException { return read(fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { return read(new File(fileName), fullyInitialize); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
private void initialize() throws ClassFormatException { try { for (int i = 0, max = this.fieldsCount; i < max; i++) { this.fields[i].initialize(); } for (int i = 0, max = this.methodsCount; i < max; i++) { this.methods[i].initialize(); } if (this.innerInfos != null) { for (int i = 0, max = this.innerInfos.length; i < max; i++) { this.innerInfos[i].initialize(); } } if (this.annotations != null) { for (int i = 0, max = this.annotations.length; i < max; i++) { this.annotations[i].initialize(); } } this.getEnclosingMethod(); reset(); } catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/FieldInfo.java
public void throwFormatException() throws ClassFormatException { throw new ClassFormatException(ClassFormatException.ErrBadFieldInfo); }
(Domain) SelectionNodeFound 58
              
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java
public void resolve(BlockScope scope) { super.resolve(scope); // tolerate some error cases if (this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnArgumentName.java
public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { super.bind(scope, typeBinding, used); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnArgumentName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java
public TypeBinding resolveType(BlockScope scope) { // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.tokens, this); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext) { throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSuperReference.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding binding = super.resolveType(scope); if (binding == null || !binding.isValidBinding()) throw new SelectionNodeFound(); else throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); if (this.binding == null) { throw new SelectionNodeFound(); } // tolerate some error cases if (!this.binding.isValidBinding()) { switch (this.binding.problemId()) { case ProblemReasons.NotVisible: // visibility is ignored break; case ProblemReasons.NotFound: if (this.resolvedType != null && this.resolvedType.isValidBinding()) { throw new SelectionNodeFound(this.resolvedType); } throw new SelectionNodeFound(); default: throw new SelectionNodeFound(); } } if (this.anonymousType == null) throw new SelectionNodeFound(this.binding); // if selecting a type for an anonymous type creation, we have to // find its target super constructor (if extending a class) or its target // super interface (if extending an interface) if (this.anonymousType.binding != null) { LocalTypeBinding localType = (LocalTypeBinding) this.anonymousType.binding; if (localType.superInterfaces == Binding.NO_SUPERINTERFACES) { // find the constructor binding inside the super constructor call ConstructorDeclaration constructor = (ConstructorDeclaration) this.anonymousType.declarationOf(this.binding.original()); if (constructor != null) { throw new SelectionNodeFound(constructor.constructorCall.binding); } throw new SelectionNodeFound(this.binding); } // open on the only super interface throw new SelectionNodeFound(localType.superInterfaces[0]); } else { if (this.resolvedType.isInterface()) { throw new SelectionNodeFound(this.resolvedType); } throw new SelectionNodeFound(this.binding); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding binding = super.resolveType(scope); if (binding == null || !binding.isValidBinding()) throw new SelectionNodeFound(); else throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleNameReference.java
public TypeBinding resolveType(BlockScope scope) { if (this.actualReceiverType != null) { this.binding = scope.getField(this.actualReceiverType, this.token, this); if (this.binding != null && this.binding.isValidBinding()) { throw new SelectionNodeFound(this.binding); } } // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.token, Binding.VARIABLE | Binding.TYPE | Binding.PACKAGE, this, true /*resolve*/); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnLocalName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnMessageSend.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); // tolerate some error cases if(this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) { throw new SelectionNodeFound(); } else { if(this.binding.isDefaultAbstract()) { throw new SelectionNodeFound(findNonDefaultAbstractMethod(this.binding)); // 23594 } else { throw new SelectionNodeFound(this.binding); } } }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnNameOfMemberValuePair.java
public void resolveTypeExpecting(BlockScope scope, TypeBinding requiredType) { super.resolveTypeExpecting(scope, requiredType); if(this.binding != null) { throw new SelectionNodeFound(this.binding); } throw new SelectionNodeFound(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.getTypeOrPackage(this.tokens); if (!binding.isValidBinding()) { // tolerate some error cases if (binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(binding); } if (binding instanceof TypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) binding); } else if (binding instanceof PackageBinding) { ProblemReferenceBinding problemBinding = new ProblemReferenceBinding(((PackageBinding)binding).compoundName, null, binding.problemId()); scope.problemReporter().invalidType(this, problemBinding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.getTypeOrPackage(new char[][] {this.token}); if (!binding.isValidBinding()) { if (binding instanceof TypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) binding); } else if (binding instanceof PackageBinding) { ProblemReferenceBinding problemBinding = new ProblemReferenceBinding(((PackageBinding)binding).compoundName, null, binding.problemId()); scope.problemReporter().invalidType(this, problemBinding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { super.resolveTypeEnclosing(scope, enclosingType); // tolerate some error cases if (this.resolvedType == null || !(this.resolvedType.isValidBinding() || this.resolvedType.problemId() == ProblemReasons.NotVisible)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedSingleTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedSingleTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnFieldReference.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); // tolerate some error cases if (this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); //// removed unnecessary code to solve bug 94653 //if(this.resolvedType != null && this.resolvedType.isRawType()) { // ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType()); // throw new SelectionNodeFound(parameterizedTypeBinding); //} throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); //// removed unnecessary code to solve bug 94653 //if(this.resolvedType != null && this.resolvedType.isRawType()) { // ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType()); // throw new SelectionNodeFound(parameterizedTypeBinding); //} throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadoc.java
private void internalResolve(Scope scope) { if (this.selectedNode != null) { switch (scope.kind) { case Scope.CLASS_SCOPE: this.selectedNode.resolveType((ClassScope)scope); break; case Scope.METHOD_SCOPE: this.selectedNode.resolveType((MethodScope)scope); break; } Binding binding = null; if (this.selectedNode instanceof JavadocFieldReference) { JavadocFieldReference fieldRef = (JavadocFieldReference) this.selectedNode; binding = fieldRef.binding; if (binding == null && fieldRef.methodBinding != null) { binding = fieldRef.methodBinding; } } else if (this.selectedNode instanceof JavadocMessageSend) { binding = ((JavadocMessageSend) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocAllocationExpression) { binding = ((JavadocAllocationExpression) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocSingleNameReference) { binding = ((JavadocSingleNameReference) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) this.selectedNode; if (typeRef.packageBinding == null) { binding = typeRef.resolvedType; } } else if (this.selectedNode instanceof JavadocQualifiedTypeReference) { JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) this.selectedNode; if (typeRef.packageBinding == null) { binding = typeRef.resolvedType; } } else { binding = this.selectedNode.resolvedType; } throw new SelectionNodeFound(binding); } else if (this.inheritDocSelected) { // no selection node when inheritDoc tag is selected // But we need to detect it to enable code select on inheritDoc ReferenceContext referenceContext = scope.referenceContext(); if (referenceContext instanceof MethodDeclaration) { throw new SelectionNodeFound(((MethodDeclaration) referenceContext).binding); } } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.selector == assistIdentifier){ if (constructorDeclaration.binding != null) { throw new SelectionNodeFound(constructorDeclaration.binding); } else { if (constructorDeclaration.scope != null) { throw new SelectionNodeFound(new MethodBinding(constructorDeclaration.modifiers, constructorDeclaration.selector, null, null, null, constructorDeclaration.scope.referenceType().binding)); } } } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { if (fieldDeclaration.name == assistIdentifier){ throw new SelectionNodeFound(fieldDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { if (localTypeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(localTypeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { if (memberTypeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(memberTypeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (methodDeclaration.selector == assistIdentifier){ if (methodDeclaration.binding != null) { throw new SelectionNodeFound(methodDeclaration.binding); } else { if (methodDeclaration.scope != null) { throw new SelectionNodeFound(new MethodBinding(methodDeclaration.modifiers, methodDeclaration.selector, null, null, null, methodDeclaration.scope.referenceType().binding)); } } } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { if (typeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(typeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeParameter typeParameter, BlockScope scope) { if (typeParameter.name == assistIdentifier) { throw new SelectionNodeFound(typeParameter.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeParameter typeParameter, ClassScope scope) { if (typeParameter.name == assistIdentifier) { throw new SelectionNodeFound(typeParameter.binding); } return true; }
0 0
(Domain) CompletionNodeFound 51
              
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { if (this.fieldTypeCompletionNode != null) { throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope); } if(this.isCompletionNode) { throw new CompletionNodeFound(this, scope); } else { return super.getTypeBinding(scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { if (this.fieldTypeCompletionNode != null) { throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope); } if(this.isCompletionNode) { throw new CompletionNodeFound(this, enclosingType, scope); } else { return super.resolveTypeEnclosing(scope, enclosingType); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java
public TypeBinding resolveType(BlockScope scope) { if (super.resolveType(scope) == null) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, this.targetType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodTypeParameter.java
public void resolveStatements() { throw new CompletionNodeFound(this, this.scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMessageSend.java
public TypeBinding resolveType(BlockScope scope) { if (this.arguments != null) { int argsLength = this.arguments.length; for (int a = argsLength; --a >= 0;) this.arguments[a].resolveType(scope); } if (this.receiver.isImplicitThis()) throw new CompletionNodeFound(this, null, scope); this.actualReceiverType = this.receiver.resolveType(scope); if (this.actualReceiverType == null || this.actualReceiverType.isBaseType()) throw new CompletionNodeFound(); if (this.actualReceiverType.isArrayType()) this.actualReceiverType = scope.getJavaLangObject(); throw new CompletionNodeFound(this, this.actualReceiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMemberAccess.java
public TypeBinding resolveType(BlockScope scope) { this.actualReceiverType = this.receiver.resolveType(scope); if ((this.actualReceiverType == null || !this.actualReceiverType.isValidBinding()) && this.receiver instanceof MessageSend) { MessageSend messageSend = (MessageSend) this.receiver; if(messageSend.receiver instanceof ThisReference) { Expression[] arguments = messageSend.arguments; int length = arguments == null ? 0 : arguments.length; TypeBinding[] argBindings = new TypeBinding[length]; for (int i = 0; i < length; i++) { argBindings[i] = arguments[i].resolvedType; if(argBindings[i] == null || !argBindings[i].isValidBinding()) { throw new CompletionNodeFound(); } } ProblemMethodBinding problemMethodBinding = new ProblemMethodBinding(messageSend.selector, argBindings, ProblemReasons.NotFound); throw new CompletionNodeFound(this, problemMethodBinding, scope); } } if (this.actualReceiverType == null || this.actualReceiverType.isBaseType() || !this.actualReceiverType.isValidBinding()) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, this.actualReceiverType, scope); // array types are passed along to find the length field }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.parent.getTypeOrPackage(this.tokens); // step up from the ClassScope if (!binding.isValidBinding()) { scope.problemReporter().invalidType(this, (TypeBinding) binding); if (binding.problemId() == ProblemReasons.NotFound) { throw new CompletionNodeFound(this, binding, scope); } throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, binding, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnArgumentName.java
public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { super.bind(scope, typeBinding, used); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnArgumentName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMarkerAnnotationName.java
public TypeBinding resolveType(BlockScope scope) { if(this.type instanceof QualifiedTypeReference) { QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) this.type; Binding binding = scope.parent.getTypeOrPackage(qualifiedTypeReference.tokens); // step up from the ClassScope if (!binding.isValidBinding()) { scope.problemReporter().invalidType(this, (TypeBinding) binding); throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, binding, scope); } throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleNameReference.java
public TypeBinding resolveType(BlockScope scope) { if(scope instanceof MethodScope) { throw new CompletionNodeFound(this, scope, ((MethodScope)scope).insideTypeAnnotation); } throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodName.java
public void resolve(ClassScope upperScope) { super.resolve(upperScope); throw new CompletionNodeFound(this, upperScope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnStringLiteral.java
public TypeBinding resolveType(ClassScope scope) { throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnStringLiteral.java
public TypeBinding resolveType(BlockScope scope) { throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnFieldName.java
public void resolve(MethodScope initializationScope) { super.resolve(initializationScope); throw new CompletionNodeFound(this, initializationScope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnKeyword1.java
protected TypeBinding getTypeBinding(Scope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java
public TypeBinding resolveType(BlockScope scope) { // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.tokens, this); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } if (this.binding.problemId() == ProblemReasons.NotFound) { throw new CompletionNodeFound(this, this.binding, scope); } throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, this.binding, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadoc.java
private void internalResolve(Scope scope) { if (this.completionNode != null) { if (this.completionNode instanceof CompletionOnJavadocTag) { ((CompletionOnJavadocTag)this.completionNode).filterPossibleTags(scope); } else { boolean resolve = true; if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { resolve = ((CompletionOnJavadocParamNameReference)this.completionNode).token != null; } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { resolve = ((CompletionOnJavadocTypeParamReference)this.completionNode).token != null; } if (resolve) { switch (scope.kind) { case Scope.CLASS_SCOPE: this.completionNode.resolveType((ClassScope)scope); break; case Scope.METHOD_SCOPE: this.completionNode.resolveType((MethodScope) scope); break; } } if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { CompletionOnJavadocParamNameReference paramNameReference = (CompletionOnJavadocParamNameReference) this.completionNode; if (scope.kind == Scope.METHOD_SCOPE) { paramNameReference.missingParams = missingParamTags(paramNameReference.binding, (MethodScope)scope); } if (paramNameReference.token == null || paramNameReference.token.length == 0) { paramNameReference.missingTypeParams = missingTypeParameterTags(paramNameReference.binding, scope); } } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { CompletionOnJavadocTypeParamReference typeParamReference = (CompletionOnJavadocTypeParamReference) this.completionNode; typeParamReference.missingParams = missingTypeParameterTags(typeParamReference.resolvedType, scope); } } Binding qualifiedBinding = null; if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference typeRef = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (typeRef.packageBinding == null) { qualifiedBinding = typeRef.resolvedType; } else { qualifiedBinding = typeRef.packageBinding; } } else if (this.completionNode instanceof CompletionOnJavadocMessageSend) { CompletionOnJavadocMessageSend msg = (CompletionOnJavadocMessageSend) this.completionNode; if (!msg.receiver.isThis()) qualifiedBinding = msg.receiver.resolvedType; } else if (this.completionNode instanceof CompletionOnJavadocAllocationExpression) { CompletionOnJavadocAllocationExpression alloc = (CompletionOnJavadocAllocationExpression) this.completionNode; qualifiedBinding = alloc.type.resolvedType; } throw new CompletionNodeFound(this.completionNode, qualifiedBinding, scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnBranchStatementLabel.java
public void resolve(BlockScope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnAnnotationMemberValuePair.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); if (this.resolvedType == null || !this.resolvedType.isValidBinding()) { throw new CompletionNodeFound(); } else { throw new CompletionNodeFound(this.completedMemberValuePair, scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMessageSendName.java
public TypeBinding resolveType(BlockScope scope) { if (this.receiver.isImplicitThis()) throw new CompletionNodeFound(); this.actualReceiverType = this.receiver.resolveType(scope); if (this.actualReceiverType == null || this.actualReceiverType.isBaseType() || this.actualReceiverType.isArrayType()) throw new CompletionNodeFound(); // resolve type arguments if (this.typeArguments != null) { int length = this.typeArguments.length; this.genericTypeArguments = new TypeBinding[length]; for (int i = 0; i < length; i++) { this.genericTypeArguments[i] = this.typeArguments[i].resolveType(scope, true /* check bounds*/); } } throw new CompletionNodeFound(this, this.actualReceiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnKeyword3.java
public TypeBinding resolveType(BlockScope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java
public void resolve(BlockScope scope) { ReferenceBinding receiverType = scope.enclosingSourceType(); if (this.arguments != null) { int argsLength = this.arguments.length; for (int a = argsLength; --a >= 0;) this.arguments[a].resolveType(scope); } if (this.accessMode != This && receiverType != null) { if (receiverType.isHierarchyInconsistent()) throw new CompletionNodeFound(); receiverType = receiverType.superclass(); } if (receiverType == null) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, receiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; if (this.arguments != null) { int argsLength = this.arguments.length; int length = this.arguments.length; argumentTypes = new TypeBinding[length]; for (int a = argsLength; --a >= 0;) { argumentTypes[a] = this.arguments[a].resolveType(scope); } } final boolean isDiamond = this.type != null && (this.type.bits & ASTNode.IsDiamond) != 0; if (this.enclosingInstance != null) { TypeBinding enclosingType = this.enclosingInstance.resolveType(scope); if (enclosingType == null) { // try to propose something even if enclosing type cannot be resolved. // Eg.: new Test<>().new Test<>(#cursor# if (this.enclosingInstance instanceof AllocationExpression) { TypeReference enclosingInstanceType = ((AllocationExpression) this.enclosingInstance).type; if (enclosingInstanceType != null) { enclosingType = enclosingInstanceType.resolvedType; } } } if (enclosingType == null || !(enclosingType instanceof ReferenceBinding)) { throw new CompletionNodeFound(); } this.resolvedType = ((SingleTypeReference) this.type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingType); if (isDiamond && (this.resolvedType instanceof ParameterizedTypeBinding)) { TypeBinding [] inferredTypes = inferElidedTypes(((ParameterizedTypeBinding) this.resolvedType).genericType(), null, argumentTypes, scope); if (inferredTypes != null) { this.resolvedType = this.type.resolvedType = scope.environment().createParameterizedType(((ParameterizedTypeBinding) this.resolvedType).genericType(), inferredTypes, ((ParameterizedTypeBinding) this.resolvedType).enclosingType()); } else { // inference failed. Resolved type will be of the form Test<> this.bits |= ASTNode.IsDiamond; } } if (!(this.resolvedType instanceof ReferenceBinding)) throw new CompletionNodeFound(); // no need to continue if its an array or base type if (this.resolvedType.isInterface()) // handle the anonymous class definition case this.resolvedType = scope.getJavaLangObject(); } else { this.resolvedType = this.type.resolveType(scope, true /* check bounds*/); if (isDiamond && (this.resolvedType instanceof ParameterizedTypeBinding)) { TypeBinding [] inferredTypes = inferElidedTypes(((ParameterizedTypeBinding) this.resolvedType).genericType(), null, argumentTypes, scope); if (inferredTypes != null) { this.resolvedType = this.type.resolvedType = scope.environment().createParameterizedType(((ParameterizedTypeBinding) this.resolvedType).genericType(), inferredTypes, ((ParameterizedTypeBinding) this.resolvedType).enclosingType()); } else { // inference failed. Resolved type will be of the form Test<> this.bits |= ASTNode.IsDiamond; } } if (!(this.resolvedType instanceof ReferenceBinding)) throw new CompletionNodeFound(); // no need to continue if its an array or base type } throw new CompletionNodeFound(this, this.resolvedType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodReturnType.java
public void resolveStatements() { throw new CompletionNodeFound(this, this.scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnLocalName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); throw new CompletionNodeFound(this, this.resolvedType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); throw new CompletionNodeFound(this, this.resolvedType, scope); }
0 0
(Lib) OperationCanceledException 49
              
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { if (VERBOSE) { Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$ Util.verbose(scope.toString()); } if (participants == null) { if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$ return; } /* initialize progress monitor */ int length = participants.length; if (monitor != null) monitor.beginTask(Messages.engine_searching, 100 * length); IndexManager indexManager = JavaModelManager.getIndexManager(); requestor.beginReporting(); for (int i = 0; i < length; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); SearchParticipant participant = participants[i]; try { if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()})); participant.beginSearching(); requestor.enterParticipant(participant); PathCollector pathCollector = new PathCollector(); indexManager.performConcurrentJob( new PatternSearchJob(pattern, participant, scope, pathCollector), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor==null ? null : new SubProgressMonitor(monitor, 50)); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // locate index matches if any (note that all search matches could have been issued during index querying) if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()})); String[] indexMatchPaths = pathCollector.getPaths(); if (indexMatchPaths != null) { pathCollector = null; // release int indexMatchLength = indexMatchPaths.length; SearchDocument[] indexMatches = new SearchDocument[indexMatchLength]; for (int j = 0; j < indexMatchLength; j++) { indexMatches[j] = participant.getDocument(indexMatchPaths[j]); } SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant); participant.locateMatches(matches, pattern, scope, requestor, monitor==null ? null : new SubProgressMonitor(monitor, 50)); } } finally { requestor.exitParticipant(participant); participant.doneSearching(); } } } finally { requestor.endReporting(); if (monitor != null) monitor.done(); } }
// 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 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/JavaSearchParticipant.java
public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { MatchLocator matchLocator = new MatchLocator( pattern, requestor, scope, monitor ); /* eliminating false matches and locating them */ if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); matchLocator.locateMatches(indexMatches); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMatches, int start, int length) throws CoreException { initialize(javaProject, length); // create and resolve binding (equivalent to beginCompilation() in Compiler) boolean mustResolvePattern = this.pattern.mustResolve; boolean mustResolve = mustResolvePattern; this.patternLocator.mayBeGeneric = this.options.sourceLevel >= ClassFileConstants.JDK1_5; boolean bindingsWereCreated = mustResolve; try { for (int i = start, maxUnits = start + length; i < maxUnits; i++) { PossibleMatch possibleMatch = possibleMatches[i]; try { if (!parseAndBuildBindings(possibleMatch, mustResolvePattern)) continue; // Currently we only need to resolve over pattern flag if there's potential parameterized types if (this.patternLocator.mayBeGeneric) { // If pattern does not resolve then rely on possible match node set resolution // which may have been modified while locator was adding possible matches to it if (!mustResolvePattern && !mustResolve) { mustResolve = possibleMatch.nodeSet.mustResolve; bindingsWereCreated = mustResolve; } } else { // Reset matching node resolution with pattern one if there's no potential parameterized type // to minimize side effect on previous search behavior possibleMatch.nodeSet.mustResolve = mustResolvePattern; } // possible match node resolution has been merged with pattern one, so rely on it to know // whether we need to process compilation unit now or later if (!possibleMatch.nodeSet.mustResolve) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } process(possibleMatch, bindingsWereCreated); if (this.numberOfMatches>0 && this.matchesToProcess[this.numberOfMatches-1] == possibleMatch) { // forget last possible match as it was processed this.numberOfMatches--; } } } finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); } } if (mustResolve) this.lookupEnvironment.completeTypeBindings(); // create hierarchy resolver if needed IType focusType = getFocusType(); if (focusType == null) { this.hierarchyResolver = null; } else if (!createHierarchyResolver(focusType, possibleMatches)) { // focus type is not visible, use the super type names instead of the bindings if (computeSuperTypeNames(focusType) == null) return; } } catch (AbortCompilation e) { bindingsWereCreated = false; } if (!mustResolve) { return; } // possible match resolution for (int i = 0; i < this.numberOfMatches; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); PossibleMatch possibleMatch = this.matchesToProcess[i]; this.matchesToProcess[i] = null; // release reference to processed possible match try { process(possibleMatch, bindingsWereCreated); } catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public void locateMatches(SearchDocument[] searchDocuments) throws CoreException { if (this.patternLocator == null) return; int docsLength = searchDocuments.length; int progressLength = docsLength; if (BasicSearchEngine.VERBOSE) { System.out.println("Locating matches in documents ["); //$NON-NLS-1$ for (int i = 0; i < docsLength; i++) System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$ System.out.println("]"); //$NON-NLS-1$ } IJavaProject[] javaModelProjects = null; if (this.searchPackageDeclaration) { javaModelProjects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); progressLength += javaModelProjects.length; } // init infos for progress increasing int n = progressLength<1000 ? Math.min(Math.max(progressLength/200+1, 2),4) : 5 *(progressLength/1000); this.progressStep = progressLength < n ? 1 : progressLength / n; // step should not be 0 this.progressWorked = 0; // extract working copies ArrayList copies = new ArrayList(); for (int i = 0; i < docsLength; i++) { SearchDocument document = searchDocuments[i]; if (document instanceof WorkingCopyDocument) { copies.add(((WorkingCopyDocument)document).workingCopy); } } int copiesLength = copies.size(); this.workingCopies = new org.eclipse.jdt.core.ICompilationUnit[copiesLength]; copies.toArray(this.workingCopies); JavaModelManager manager = JavaModelManager.getJavaModelManager(); this.bindings = new SimpleLookupTable(); try { // optimize access to zip files during search operation manager.cacheZipFiles(this); // initialize handle factory (used as a cache of handles so as to optimize space) if (this.handleFactory == null) this.handleFactory = new HandleFactory(); if (this.progressMonitor != null) { this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$ } // initialize pattern for polymorphic search (i.e. method reference pattern) this.patternLocator.initializePolymorphicSearch(this); JavaProject previousJavaProject = null; PossibleMatchSet matchSet = new PossibleMatchSet(); Util.sort(searchDocuments, new Util.Comparer() { public int compare(Object a, Object b) { return ((SearchDocument)a).getPath().compareTo(((SearchDocument)b).getPath()); } }); int displayed = 0; // progress worked displayed String previousPath = null; SearchParticipant searchParticipant = null; for (int i = 0; i < docsLength; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // skip duplicate paths SearchDocument searchDocument = searchDocuments[i]; if (searchParticipant == null) { searchParticipant = searchDocument.getParticipant(); } searchDocuments[i] = null; // free current document String pathString = searchDocument.getPath(); if (i > 0 && pathString.equals(previousPath)) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; } previousPath = pathString; Openable openable; org.eclipse.jdt.core.ICompilationUnit workingCopy = null; if (searchDocument instanceof WorkingCopyDocument) { workingCopy = ((WorkingCopyDocument)searchDocument).workingCopy; openable = (Openable) workingCopy; } else { openable = this.handleFactory.createOpenable(pathString, this.scope); } if (openable == null) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; // match is outside classpath } // create new parser and lookup environment if this is a new project IResource resource = null; JavaProject javaProject = (JavaProject) openable.getJavaProject(); resource = workingCopy != null ? workingCopy.getResource() : openable.getResource(); if (resource == null) resource = javaProject.getProject(); // case of a file in an external jar or external folder if (!javaProject.equals(previousJavaProject)) { // locate matches in previous project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, i-displayed); displayed = i; } catch (JavaModelException e) { // problem with classpath in this project -> skip it } matchSet.reset(); } previousJavaProject = javaProject; } matchSet.add(new PossibleMatch(this, resource, openable, searchDocument,this.pattern.mustResolve)); } // last project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, docsLength-displayed); } catch (JavaModelException e) { // problem with classpath in last project -> ignore } } if (this.searchPackageDeclaration) { locatePackageDeclarations(searchParticipant, javaModelProjects); } } finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); try { if (BasicSearchEngine.VERBOSE) System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.parser.nodeSet = possibleMatch.nodeSet; CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult); if (parsedUnit != null) { if (!parsedUnit.isEmpty()) { if (mustResolve) { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } if (hasAlreadyDefinedType(parsedUnit)) return false; // skip type has it is hidden so not visible getMethodBodies(parsedUnit, possibleMatch.nodeSet); if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) { // special case: possible match node set force resolution although pattern does not // => we need to build types for this compilation unit this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } } // add the possibleMatch with its parsedUnit to matchesToProcess possibleMatch.parsedUnit = parsedUnit; int size = this.matchesToProcess.length; if (this.numberOfMatches == size) System.arraycopy(this.matchesToProcess, 0, this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0, this.numberOfMatches); this.matchesToProcess[this.numberOfMatches++] = possibleMatch; } } finally { this.parser.nodeSet = null; } return true; }
// in search/org/eclipse/jdt/internal/core/search/matching/LocalVariablePattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) { IPackageFragmentRoot root = (IPackageFragmentRoot)this.localVariable.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); String documentPath; String relativePath; if (root.isArchive()) { IType type = (IType)this.localVariable.getAncestor(IJavaElement.TYPE); relativePath = (type.getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class; documentPath = root.getPath() + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath; } else { IPath path = this.localVariable.getPath(); documentPath = path.toString(); relativePath = Util.relativePath(path, 1/*remove project segment*/); } if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path if (!requestor.acceptIndexMatch(documentPath, this, participant, access)) throw new OperationCanceledException(); } } else if (scope.encloses(documentPath)) { if (!requestor.acceptIndexMatch(documentPath, this, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeParameterPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) { IPackageFragmentRoot root = (IPackageFragmentRoot) this.typeParameter.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); String documentPath; String relativePath; if (root.isArchive()) { IType type = (IType) this.typeParameter.getAncestor(IJavaElement.TYPE); relativePath = (type.getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class; documentPath = root.getPath() + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath; } else { IPath path = this.typeParameter.getPath(); documentPath = path.toString(); relativePath = Util.relativePath(path, 1/*remove project segment*/); } if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path if (!requestor.acceptIndexMatch(documentPath, this, participant, access)) throw new OperationCanceledException(); } } else if (scope.encloses(documentPath)) { if (!requestor.acceptIndexMatch(documentPath, this, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/IntersectingPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); resetQuery(); SimpleSet intersectedNames = null; try { index.startQuery(); do { SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); SimpleSet newIntersectedNames = new SimpleSet(3); for (int i = 0, l = entries.length; i < l; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { String[] names = entry.getDocumentNames(index); if (intersectedNames != null) { for (int j = 0, n = names.length; j < n; j++) if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]); } else { for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]); } } } if (newIntersectedNames.elementSize == 0) return; intersectedNames = newIntersectedNames; } while (hasNextQuery()); } finally { index.stopQuery(); } String containerPath = index.containerPath; char separator = index.separator; Object[] names = intersectedNames.values; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) acceptMatch((String) names[i], containerPath, separator, null/*no pattern*/, requestor, participant, scope, progressMonitor); // AndPatterns cannot provide the decoded result }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
public boolean performConcurrentJob(IJob searchJob, int waitingPolicy, IProgressMonitor progress) { if (VERBOSE) Util.verbose("STARTING concurrent job - " + searchJob); //$NON-NLS-1$ searchJob.ensureReadyToRun(); boolean status = IJob.FAILED; try { int concurrentJobWork = 100; if (progress != null) progress.beginTask("", concurrentJobWork); //$NON-NLS-1$ if (awaitingJobsCount() > 0) { switch (waitingPolicy) { case IJob.ForceImmediate : if (VERBOSE) Util.verbose("-> NOT READY - forcing immediate - " + searchJob);//$NON-NLS-1$ try { disable(); // pause indexing status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); } finally { enable(); } if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ return status; case IJob.CancelIfNotReady : if (VERBOSE) Util.verbose("-> NOT READY - cancelling - " + searchJob); //$NON-NLS-1$ if (VERBOSE) Util.verbose("CANCELED concurrent job - " + searchJob); //$NON-NLS-1$ throw new OperationCanceledException(); case IJob.WaitUntilReady : IProgressMonitor subProgress = null; try { int totalWork = 1000; if (progress != null) { subProgress = new SubProgressMonitor(progress, concurrentJobWork * 8 / 10); subProgress.beginTask("", totalWork); //$NON-NLS-1$ concurrentJobWork = concurrentJobWork * 2 / 10; } // use local variable to avoid potential NPE (see bug 20435 NPE when searching java method // and bug 42760 NullPointerException in JobManager when searching) Thread t = this.processingThread; int originalPriority = t == null ? -1 : t.getPriority(); try { if (t != null) t.setPriority(Thread.currentThread().getPriority()); synchronized(this) { this.awaitingClients++; } IJob previousJob = null; int awaitingJobsCount; int lastJobsCount = totalWork; float lastWorked = 0; float totalWorked = 0; while ((awaitingJobsCount = awaitingJobsCount()) > 0) { if ((subProgress != null && subProgress.isCanceled()) || this.processingThread == null) throw new OperationCanceledException(); IJob currentJob = currentJob(); // currentJob can be null when jobs have been added to the queue but job manager is not enabled if (currentJob != null && currentJob != previousJob) { if (VERBOSE) Util.verbose("-> NOT READY - waiting until ready - " + searchJob);//$NON-NLS-1$ if (subProgress != null) { String indexing = Messages.bind(Messages.jobmanager_filesToIndex, currentJob.getJobFamily(), Integer.toString(awaitingJobsCount)); subProgress.subTask(indexing); // ratio of the amount of work relative to the total work float ratio = awaitingJobsCount < totalWork ? 1 : ((float) totalWork) / awaitingJobsCount; if (lastJobsCount > awaitingJobsCount) { totalWorked += (lastJobsCount - awaitingJobsCount) * ratio; } else { // more jobs were added, just increment by the ratio totalWorked += ratio; } if (totalWorked - lastWorked >= 1) { subProgress.worked((int) (totalWorked - lastWorked)); lastWorked = totalWorked; } lastJobsCount = awaitingJobsCount; } previousJob = currentJob; } try { if (VERBOSE) Util.verbose("-> GOING TO SLEEP - " + searchJob);//$NON-NLS-1$ Thread.sleep(50); } catch (InterruptedException e) { // ignore } } } finally { synchronized(this) { this.awaitingClients--; } if (t != null && originalPriority > -1 && t.isAlive()) t.setPriority(originalPriority); } } finally { if (subProgress != null) subProgress.done(); } } } status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); } finally { if (progress != null) progress.done(); if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ } return status; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
public Index[] getIndexes(IPath[] locations, IProgressMonitor progressMonitor) { // acquire the in-memory indexes on the fly int length = locations.length; Index[] locatedIndexes = new Index[length]; int count = 0; if (this.javaLikeNamesChanged) { this.javaLikeNamesChanged = hasJavaLikeNamesChanged(); } for (int i = 0; i < length; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // may trigger some index recreation work IPath indexLocation = locations[i]; Index index = getIndex(indexLocation); if (index == null) { // only need containerPath if the index must be built IPath containerPath = (IPath) this.indexLocations.keyForValue(indexLocation); if (containerPath != null) {// sanity check index = getIndex(containerPath, indexLocation, true /*reuse index file*/, false /*do not create if none*/); if (index != null && this.javaLikeNamesChanged && !index.isIndexForJar()) { // When a change in java like names extension has been detected, all // non jar files indexes (i.e. containing sources) need to be rebuilt. // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=286379 File indexFile = index.getIndexFile(); if (indexFile.exists()) { if (DEBUG) Util.verbose("Change in javaLikeNames - removing index file for " + containerPath ); //$NON-NLS-1$ indexFile.delete(); } this.indexes.put(indexLocation, null); rebuildIndex(indexLocation, containerPath); index = null; } } else { if (!getJavaPluginWorkingLocation().isPrefixOf(indexLocation)) { // the index belongs to non-jdt search participant if (indexLocation.toFile().exists()) { try { IPath container = getParticipantsContainer(indexLocation); if (container != null) { index = new Index(indexLocation.toOSString(), container.toOSString(), true /*reuse index file*/); this.indexes.put(indexLocation, index); } } catch (IOException e) { // ignore } } } } } if (index != null) locatedIndexes[count++] = index; // only consider indexes which are ready } if (this.javaLikeNamesChanged) { writeJavaLikeNamesFile(); this.javaLikeNamesChanged = false; } if (count < length) { System.arraycopy(locatedIndexes, 0, locatedIndexes=new Index[count], 0, count); } return locatedIndexes; }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
public boolean execute(IProgressMonitor progressMonitor) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); boolean isComplete = COMPLETE; this.executionTime = 0; Index[] indexes = getIndexes(progressMonitor); try { int max = indexes.length; if (progressMonitor != null) progressMonitor.beginTask("", max); //$NON-NLS-1$ for (int i = 0; i < max; i++) { isComplete &= search(indexes[i], progressMonitor); if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } if (JobManager.VERBOSE) Util.verbose("-> execution time: " + this.executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$ return isComplete; } finally { if (progressMonitor != null) progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
public boolean search(Index index, IProgressMonitor progressMonitor) { if (index == null) return COMPLETE; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); ReadWriteMonitor monitor = index.monitor; if (monitor == null) return COMPLETE; // index got deleted since acquired try { monitor.enterRead(); // ask permission to read long start = System.currentTimeMillis(); MatchLocator.findIndexMatches(this.pattern, index, this.requestor, this.participant, this.scope, progressMonitor); this.executionTime += System.currentTimeMillis() - start; return COMPLETE; } catch (IOException e) { if (e instanceof java.io.EOFException) e.printStackTrace(); return FAILED; } finally { monitor.exitRead(); // finished reading } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void acceptMatch(String relativePath, String containerPath, char separator, SearchPattern pattern, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) { if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the document path StringBuffer documentPath = new StringBuffer(containerPath.length() + 1 + relativePath.length()); documentPath.append(containerPath); documentPath.append(separator); documentPath.append(relativePath); if (!requestor.acceptIndexMatch(documentPath.toString(), pattern, participant, access)) throw new OperationCanceledException(); } } else { StringBuffer buffer = new StringBuffer(containerPath.length() + 1 + relativePath.length()); buffer.append(containerPath); buffer.append(separator); buffer.append(relativePath); String documentPath = buffer.toString(); boolean encloses = (scope instanceof HierarchyScope) ? ((HierarchyScope)scope).encloses(documentPath, monitor) : scope.encloses(documentPath); if (encloses) if (!requestor.acceptIndexMatch(documentPath, pattern, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { index.startQuery(); SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); String containerPath = index.containerPath; char separator = index.separator; for (int i = 0, l = entries.length; i < l; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { // TODO (kent) some clients may not need the document names String[] names = entry.getDocumentNames(index); for (int j = 0, n = names.length; j < n; j++) acceptMatch(names[j], containerPath, separator, decodedResult, requestor, participant, scope, monitor); } } } finally { index.stopQuery(); } }
// 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 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/JavaModelOperation.java
protected void checkCanceled() { if (isCanceled()) { throw new OperationCanceledException(Messages.operation_cancelled); } }
// 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/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/builder/BuildNotifier.java
public void checkCancel() { if (this.monitor != null && this.monitor.isCanceled()) throw new OperationCanceledException(); }
// 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/hierarchy/TypeHierarchy.java
protected void checkCanceled() { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); BinaryTypeBinding typeBinding = this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction); try { this.remember(binaryType, typeBinding); } catch (AbortCompilation e) { // ignore } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); // find most enclosing type first (needed when explicit askForType(...) is done // with a member type (e.g. p.A$B)) ISourceType sourceType = sourceTypes[0]; while (sourceType.getEnclosingType() != null) sourceType = sourceType.getEnclosingType(); // build corresponding compilation unit CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit( new ISourceType[] {sourceType}, // ignore secondary types, to improve laziness SourceTypeConverter.MEMBER_TYPE, // need member types // no need for field initialization this.lookupEnvironment.problemReporter, result); // build bindings if (unit != null) { try { this.lookupEnvironment.buildTypeBindings(unit, accessRestriction); org.eclipse.jdt.core.ICompilationUnit cu = ((SourceTypeElementInfo)sourceType).getHandle().getCompilationUnit(); rememberAllTypes(unit, cu, false); this.lookupEnvironment.completeTypeBindings(unit, true/*build constructor only*/); } catch (AbortCompilation e) { // missing 'java.lang' package: ignore } } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
private void reportHierarchy(IType focus, TypeDeclaration focusLocalType, ReferenceBinding binaryTypeBinding) { // set focus type binding if (focus != null) { if (binaryTypeBinding != null) { // binary type this.focusType = binaryTypeBinding; } else { // source type if (focusLocalType != null) { // anonymous or local type this.focusType = focusLocalType.binding; } else { // top level or member type char[] fullyQualifiedName = focus.getFullyQualifiedName().toCharArray(); setFocusType(CharOperation.splitOn('.', fullyQualifiedName)); } } } // be resilient and fix super type bindings fixSupertypeBindings(); int objectIndex = -1; IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; for (int current = this.typeIndex; current >= 0; current--) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); ReferenceBinding typeBinding = this.typeBindings[current]; // java.lang.Object treated at the end if (typeBinding.id == TypeIds.T_JavaLangObject) { objectIndex = current; continue; } IGenericType suppliedType = this.typeModels[current]; if (!subOrSuperOfFocus(typeBinding)) { continue; // ignore types outside of hierarchy } IType superclass; if (typeBinding.isInterface()){ // do not connect interfaces to Object superclass = null; } else { superclass = findSuperClass(suppliedType, typeBinding); } IType[] superinterfaces = findSuperInterfaces(suppliedType, typeBinding); this.builder.connect(suppliedType, this.builder.getHandle(suppliedType, typeBinding), superclass, superinterfaces); } // add java.lang.Object only if the super class is not missing if (objectIndex > -1 && (!this.hasMissingSuperClass || this.focusType == null)) { IGenericType objectType = this.typeModels[objectIndex]; this.builder.connect(objectType, this.builder.getHandle(objectType, this.typeBindings[objectIndex]), null, null); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void resolve(Openable[] openables, HashSet localTypes, IProgressMonitor monitor) { try { int openablesLength = openables.length; CompilationUnitDeclaration[] parsedUnits = new CompilationUnitDeclaration[openablesLength]; boolean[] hasLocalType = new boolean[openablesLength]; org.eclipse.jdt.core.ICompilationUnit[] cus = new org.eclipse.jdt.core.ICompilationUnit[openablesLength]; int unitsIndex = 0; CompilationUnitDeclaration focusUnit = null; ReferenceBinding focusBinaryBinding = null; IType focus = this.builder.getType(); Openable focusOpenable = null; if (focus != null) { if (focus.isBinary()) { focusOpenable = (Openable)focus.getClassFile(); } else { focusOpenable = (Openable)focus.getCompilationUnit(); } } // build type bindings Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); for (int i = 0; i < openablesLength; i++) { Openable openable = openables[i]; if (openable instanceof org.eclipse.jdt.core.ICompilationUnit) { org.eclipse.jdt.core.ICompilationUnit cu = (org.eclipse.jdt.core.ICompilationUnit)openable; // contains a potential subtype as a local or anonymous type? boolean containsLocalType = false; if (localTypes == null) { // case of hierarchy on region containsLocalType = true; } else { IPath path = cu.getPath(); containsLocalType = localTypes.contains(path.toString()); } // build parsed unit CompilationUnitDeclaration parsedUnit = null; if (cu.isOpen()) { // create parsed unit from source element infos CompilationResult result = new CompilationResult((ICompilationUnit)cu, i, openablesLength, this.options.maxProblemsPerUnit); SourceTypeElementInfo[] typeInfos = null; try { IType[] topLevelTypes = cu.getTypes(); int topLevelLength = topLevelTypes.length; if (topLevelLength == 0) continue; // empty cu: no need to parse (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65677) typeInfos = new SourceTypeElementInfo[topLevelLength]; for (int j = 0; j < topLevelLength; j++) { IType topLevelType = topLevelTypes[j]; typeInfos[j] = (SourceTypeElementInfo)((JavaElement)topLevelType).getElementInfo(); } } catch (JavaModelException e) { // types/cu exist since cu is opened } int flags = !containsLocalType ? SourceTypeConverter.MEMBER_TYPE : SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE | SourceTypeConverter.LOCAL_TYPE; parsedUnit = SourceTypeConverter.buildCompilationUnit( typeInfos, flags, this.lookupEnvironment.problemReporter, result); // We would have got all the necessary local types by now and hence there is no further need // to parse the method bodies. Parser.getMethodBodies, which is called latter in this function, // will not parse the method statements if ASTNode.HasAllMethodBodies is set. if (containsLocalType) parsedUnit.bits |= ASTNode.HasAllMethodBodies; } else { // create parsed unit from file IFile file = (IFile) cu.getResource(); ICompilationUnit sourceUnit = this.builder.createCompilationUnitFromPath(openable, file); CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); parsedUnit = parser.dietParse(sourceUnit, unitResult); } if (parsedUnit != null) { hasLocalType[unitsIndex] = containsLocalType; cus[unitsIndex] = cu; parsedUnits[unitsIndex++] = parsedUnit; try { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); if (openable.equals(focusOpenable)) { focusUnit = parsedUnit; } } catch (AbortCompilation e) { // classpath problem for this type: ignore } } } else { // cache binary type binding ClassFile classFile = (ClassFile)openable; IBinaryType binaryType = (IBinaryType) JavaModelManager.getJavaModelManager().getInfo(classFile.getType()); if (binaryType == null) { // create binary type from file if (classFile.getPackageFragmentRoot().isArchive()) { binaryType = this.builder.createInfoFromClassFileInJar(classFile); } else { IResource file = classFile.resource(); binaryType = this.builder.createInfoFromClassFile(classFile, file); } } if (binaryType != null) { try { BinaryTypeBinding binaryTypeBinding = this.lookupEnvironment.cacheBinaryType(binaryType, false/*don't need field and method (bug 125067)*/, null /*no access restriction*/); remember(binaryType, binaryTypeBinding); if (openable.equals(focusOpenable)) { focusBinaryBinding = binaryTypeBinding; } } catch (AbortCompilation e) { // classpath problem for this type: ignore } } } } // remember type declaration of focus if local/anonymous early (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=210498) TypeDeclaration focusLocalType = null; if (focus != null && focusBinaryBinding == null && focusUnit != null && ((Member)focus).getOuterMostLocalContext() != null) { focusLocalType = new ASTNodeFinder(focusUnit).findType(focus); } for (int i = 0; i <= this.typeIndex; i++) { IGenericType suppliedType = this.typeModels[i]; if (suppliedType != null && suppliedType.isBinaryType()) { CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted; // fault in its hierarchy... try { // ensure that unitBeingCompleted is set so that we don't get an AbortCompilation for a missing type // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213249 ) if (previousUnitBeingCompleted == null) { this.lookupEnvironment.unitBeingCompleted = FakeUnit; } ReferenceBinding typeBinding = this.typeBindings[i]; typeBinding.superclass(); typeBinding.superInterfaces(); } catch (AbortCompilation e) { // classpath problem for this type: ignore } finally { this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted; } } } // complete type bindings (i.e. connect super types) for (int i = 0; i < unitsIndex; i++) { CompilationUnitDeclaration parsedUnit = parsedUnits[i]; if (parsedUnit != null) { try { if (hasLocalType[i]) { // NB: no-op if method bodies have been already parsed if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); parser.getMethodBodies(parsedUnit); } } catch (AbortCompilation e) { // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) hasLocalType[i] = false; } } } // complete type bindings and build fields and methods only for local types // (in this case the constructor is needed when resolving local types) // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=145333) try { this.lookupEnvironment.completeTypeBindings(parsedUnits, hasLocalType, unitsIndex); // remember type bindings for (int i = 0; i < unitsIndex; i++) { CompilationUnitDeclaration parsedUnit = parsedUnits[i]; if (parsedUnit != null && !parsedUnit.hasErrors()) { boolean containsLocalType = hasLocalType[i]; if (containsLocalType) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); parsedUnit.scope.faultInTypes(); parsedUnit.resolve(); } rememberAllTypes(parsedUnit, cus[i], containsLocalType); } } } catch (AbortCompilation e) { // skip it silently } worked(monitor, 1); // if no potential subtype was a real subtype of the binary focus type, no need to go further // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=54043) if (focusBinaryBinding == null && focus != null && focus.isBinary()) { char[] fullyQualifiedName = focus.getFullyQualifiedName().toCharArray(); focusBinaryBinding = this.lookupEnvironment.getCachedType(CharOperation.splitOn('.', fullyQualifiedName)); if (focusBinaryBinding == null) return; } reportHierarchy(focus, focusLocalType, focusBinaryBinding); } catch (ClassCastException e){ // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if (TypeHierarchy.DEBUG) e.printStackTrace(); } finally { reset(); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
protected void worked(IProgressMonitor monitor, int work) { if (monitor != null) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } else { monitor.worked(work); } } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
protected void worked(IProgressMonitor monitor, int work) { if (monitor != null) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } else { monitor.worked(work); } } }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
public void findTypes(char[] prefix, final boolean findMembers, boolean camelCaseMatch, int searchFor, final ISearchRequestor storage, IProgressMonitor monitor) { /* if (true){ findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; } */ try { final String excludePath; if (this.unitToSkip != null) { if (!(this.unitToSkip instanceof IJavaElement)) { // revert to model investigation findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); return; } excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); } else { excludePath = null; } int lastDotIndex = CharOperation.lastIndexOf('.', prefix); char[] qualification, simpleName; if (lastDotIndex < 0) { qualification = null; if (camelCaseMatch) { simpleName = prefix; } else { simpleName = CharOperation.toLowerCase(prefix); } } else { qualification = CharOperation.subarray(prefix, 0, lastDotIndex); if (camelCaseMatch) { simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length); } else { simpleName = CharOperation.toLowerCase( CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length)); } } IProgressMonitor progressMonitor = new IProgressMonitor() { boolean isCanceled = false; public void beginTask(String name, int totalWork) { // implements interface method } public void done() { // implements interface method } public void internalWorked(double work) { // implements interface method } public boolean isCanceled() { return this.isCanceled; } public void setCanceled(boolean value) { this.isCanceled = value; } public void setTaskName(String name) { // implements interface method } public void subTask(String name) { // implements interface method } public void worked(int work) { // implements interface method } }; IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0) return; // accept only top level types storage.acceptType(packageName, simpleTypeName, enclosingTypeNames, modifiers, access); } }; int matchRule = SearchPattern.R_PREFIX_MATCH; if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH; if (monitor != null) { IndexManager indexManager = JavaModelManager.getIndexManager(); if (indexManager.awaitingJobsCount() == 0) { // indexes were already there, so perform an immediate search to avoid any index rebuilt new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { // indexes were not ready, give the indexing a chance to finish small jobs by sleeping 100ms... try { Thread.sleep(100); } catch (InterruptedException e) { // Do nothing } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (indexManager.awaitingJobsCount() == 0) { // indexes are now ready, so perform an immediate search to avoid any index rebuilt new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { // Indexes are still not ready, so look for types in the model instead of a search request findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } } } else { try { new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, progressMonitor); } catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } } } catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
public void findConstructorDeclarations(char[] prefix, boolean camelCaseMatch, final ISearchRequestor storage, IProgressMonitor monitor) { try { final String excludePath; if (this.unitToSkip != null && this.unitToSkip instanceof IJavaElement) { excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); } else { excludePath = null; } int lastDotIndex = CharOperation.lastIndexOf('.', prefix); char[] qualification, simpleName; if (lastDotIndex < 0) { qualification = null; if (camelCaseMatch) { simpleName = prefix; } else { simpleName = CharOperation.toLowerCase(prefix); } } else { qualification = CharOperation.subarray(prefix, 0, lastDotIndex); if (camelCaseMatch) { simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length); } else { simpleName = CharOperation.toLowerCase( CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length)); } } IProgressMonitor progressMonitor = new IProgressMonitor() { boolean isCanceled = false; public void beginTask(String name, int totalWork) { // implements interface method } public void done() { // implements interface method } public void internalWorked(double work) { // implements interface method } public boolean isCanceled() { return this.isCanceled; } public void setCanceled(boolean value) { this.isCanceled = value; } public void setTaskName(String name) { // implements interface method } public void subTask(String name) { // implements interface method } public void worked(int work) { // implements interface method } }; IRestrictedAccessConstructorRequestor constructorRequestor = new IRestrictedAccessConstructorRequestor() { public void acceptConstructor( int modifiers, char[] simpleTypeName, int parameterCount, char[] signature, char[][] parameterTypes, char[][] parameterNames, int typeModifiers, char[] packageName, int extraFlags, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; storage.acceptConstructor( modifiers, simpleTypeName, parameterCount, signature, parameterTypes, parameterNames, typeModifiers, packageName, extraFlags, path, access); } }; int matchRule = SearchPattern.R_PREFIX_MATCH; if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH; if (monitor != null) { IndexManager indexManager = JavaModelManager.getIndexManager(); while (indexManager.awaitingJobsCount() > 0) { try { Thread.sleep(50); // indexes are not ready, sleep 50ms... } catch (InterruptedException e) { // Do nothing } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations( qualification, simpleName, matchRule, getSearchScope(), constructorRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { try { new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations( qualification, simpleName, matchRule, getSearchScope(), constructorRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, progressMonitor); } catch (OperationCanceledException e) { // Do nothing } } } catch (JavaModelException e) { // Do nothing } }
// in model/org/eclipse/jdt/internal/compiler/SourceElementParser.java
public CompilationUnitDeclaration parseCompilationUnit( ICompilationUnit unit, boolean fullParse, IProgressMonitor pm) { boolean old = this.diet; CompilationUnitDeclaration parsedUnit = null; try { this.diet = true; this.reportReferenceInfo = fullParse; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit); parsedUnit = parse(unit, compilationUnitResult); if (pm != null && pm.isCanceled()) throw new OperationCanceledException(Messages.operation_cancelled); if (this.scanner.recordLineSeparator) { this.requestor.acceptLineSeparatorPositions(compilationUnitResult.getLineSeparatorPositions()); } int initialStart = this.scanner.initialPosition; int initialEnd = this.scanner.eofPosition; if (this.reportLocalDeclarations || fullParse){ this.diet = false; getMethodBodies(parsedUnit); } this.scanner.resetTo(initialStart, initialEnd); this.notifier.notifySourceElementRequestor( parsedUnit, this.scanner.initialPosition, this.scanner.eofPosition, this.reportReferenceInfo, this.sourceEnds, this.nodesToCategories); return parsedUnit; } catch (AbortCompilation e) { // ignore this exception } finally { this.diet = old; reset(); } return parsedUnit; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
void checkCancel() { if (this.monitor != null && this.monitor.isCanceled()) { throw new OperationCanceledException(); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
private void worked(int work) { if (this.monitor != null) { if (this.monitor.isCanceled()) throw new OperationCanceledException(); this.monitor.worked(work); } }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
protected void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) throw new OperationCanceledException(); }
0 0
(Lib) IOException 31
              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
void initialize(boolean reuseExistingFile) throws IOException { if (this.indexFile.exists()) { if (reuseExistingFile) { FileInputStream stream = new FileInputStream(this.indexFile); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, 128); try { char[] signature = readStreamChars(stream); if (!CharOperation.equals(signature, SIGNATURE_CHARS)) { throw new IOException(Messages.exception_wrongFormat); } this.headerInfoOffset = readStreamInt(stream); if (this.headerInfoOffset > 0) { // file is empty if its not set stream.skip(this.headerInfoOffset - this.bufferEnd); // assume that the header info offset is over current buffer end this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); readHeaderInfo(stream); } } finally { stream.close(); } return; } if (!this.indexFile.delete()) { if (DEBUG) System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$ } } if (this.indexFile.createNewFile()) { FileOutputStream stream = new FileOutputStream(this.indexFile, false); try { this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; writeStreamChars(stream, SIGNATURE_CHARS); writeStreamInt(stream, -1); // file is empty // write the buffer to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } } finally { stream.close(); } } else { if (DEBUG) System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$ } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException { if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file if (DEBUG) System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$ } else if (!newIndexFile.createNewFile()) { if (DEBUG) System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$ } int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize; this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); this.categoryTables = new HashtableOfObject(size); this.separator = diskIndex.separator; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException { // assume write lock is held // compute & write out new docNames String[] docNames = readAllDocumentNames(); int previousLength = docNames.length; int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames SimpleLookupTable indexedDocuments = new SimpleLookupTable(3); // for each new/changed document in the memoryIndex docNames = computeDocumentNames(docNames, positions, indexedDocuments, memoryIndex); if (docNames.length == 0) { if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved // index is now empty since all the saved documents were removed DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath()); newDiskIndex.initialize(false); return newDiskIndex; } DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$ try { newDiskIndex.initializeFrom(this, newDiskIndex.indexFile); FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false); int offsetToHeader = -1; try { newDiskIndex.writeAllDocumentNames(docNames, stream); docNames = null; // free up the space // add each new/changed doc to empty category tables using its new position # if (indexedDocuments.elementSize > 0) { Object[] names = indexedDocuments.keyTable; Object[] integerPositions = indexedDocuments.valueTable; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) newDiskIndex.copyQueryResults( (HashtableOfObject) memoryIndex.docsToReferences.get(names[i]), ((Integer) integerPositions[i]).intValue()); } indexedDocuments = null; // free up the space // merge each category table with the new ones & write them out if (previousLength == 0) newDiskIndex.writeCategories(stream); else newDiskIndex.mergeCategories(this, positions, stream); offsetToHeader = newDiskIndex.streamEnd; newDiskIndex.writeHeaderInfo(stream); positions = null; // free up the space } finally { stream.close(); this.streamBuffer = null; } newDiskIndex.writeOffsetToHeader(offsetToHeader); // rename file by deleting previous index file & renaming temp one if (this.indexFile.exists() && !this.indexFile.delete()) { if (DEBUG) System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$ } if (!newDiskIndex.indexFile.renameTo(this.indexFile)) { if (DEBUG) System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$ } } catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; } newDiskIndex.indexFile = this.indexFile; return newDiskIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readHeaderInfo(FileInputStream stream) throws IOException { // must be same order as writeHeaderInfo() this.numberOfChunks = readStreamInt(stream); this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF; this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF; this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF); long fileLength = this.indexFile.length(); if (this.numberOfChunks > fileLength ) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } this.chunkOffsets = new int[this.numberOfChunks]; for (int i = 0; i < this.numberOfChunks; i++) this.chunkOffsets[i] = readStreamInt(stream); this.startOfCategoryTables = readStreamInt(stream); int size = readStreamInt(stream); this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); if (size > fileLength) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } char[] previousCategory = null; int offset = -1; for (int i = 0; i < size; i++) { char[] categoryName = INTERNED_CATEGORY_NAMES.get(readStreamChars(stream)); offset = readStreamInt(stream); this.categoryOffsets.put(categoryName, offset); // cache offset to category table if (previousCategory != null) { this.categoryEnds.put(previousCategory, offset); // cache end of the category table } previousCategory = categoryName; } if (previousCategory != null) { this.categoryEnds.put(previousCategory, this.headerInfoOffset); // cache end of the category table } this.categoryTables = new HashtableOfObject(3); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry loadClasspathEntry() throws IOException { int id = loadInt(); if (id < 0 || id > this.allClasspathEntryCount) throw new IOException("Unexpected classpathentry id"); //$NON-NLS-1$ if (id < this.allClasspathEntryCount) return this.allClasspathEntries[id]; int contentKind = loadInt(); int entryKind = loadInt(); IPath path = loadPath(); IPath[] inclusionPatterns = loadPaths(); IPath[] exclusionPatterns = loadPaths(); IPath sourceAttachmentPath = loadPath(); IPath sourceAttachmentRootPath = loadPath(); IPath specificOutputLocation = loadPath(); boolean isExported = loadBoolean(); IAccessRule[] accessRules = loadAccessRules(); boolean combineAccessRules = loadBoolean(); IClasspathAttribute[] extraAttributes = loadAttributes(); IClasspathEntry entry = new ClasspathEntry(contentKind, entryKind, path, inclusionPatterns, exclusionPatterns, sourceAttachmentPath, sourceAttachmentRootPath, specificOutputLocation, isExported, accessRules, combineAccessRules, extraAttributes); IClasspathEntry[] array = this.allClasspathEntries; if (array == null || id == array.length) { array = new IClasspathEntry[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allClasspathEntries, 0, array, 0, id); this.allClasspathEntries = array; } array[id] = entry; this.allClasspathEntryCount = id + 1; return entry; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private String loadString() throws IOException { int id = loadInt(); if (id < 0 || id > this.allStringsCount) throw new IOException("Unexpected string id"); //$NON-NLS-1$ if (id < this.allStringsCount) return this.allStrings[id]; String string = this.in.readUTF(); String[] array = this.allStrings; if (array == null || id == array.length) { array = new String[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allStrings, 0, array, 0, id); this.allStrings = array; } array[id] = string; this.allStringsCount = id + 1; return string; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static UserLibrary createFromString(Reader reader) throws IOException { Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase(TAG_USERLIBRARY)) { throw new IOException(Messages.file_badFormat); } String version= cpElement.getAttribute(TAG_VERSION); boolean isSystem= Boolean.valueOf(cpElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue(); NodeList list= cpElement.getChildNodes(); int length = list.getLength(); ArrayList res= new ArrayList(length); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equals(TAG_ARCHIVE)) { String pathString = element.getAttribute(TAG_PATH); String sourceAttachString = element.hasAttribute(TAG_SOURCEATTACHMENT) ? element.getAttribute(TAG_SOURCEATTACHMENT) : null; String sourceAttachRootString = element.hasAttribute(TAG_SOURCEATTACHMENTROOT) ? element.getAttribute(TAG_SOURCEATTACHMENTROOT) : null; IPath entryPath = null; IPath sourceAttachPath = null; IPath sourceAttachRootPath = null; if (version.equals(VERSION_ONE)) { entryPath = Path.fromOSString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromOSString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromOSString(sourceAttachRootString); } else { entryPath = Path.fromPortableString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromPortableString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromPortableString(sourceAttachRootString); } NodeList children = element.getElementsByTagName("*"); //$NON-NLS-1$ boolean[] foundChildren = new boolean[children.getLength()]; NodeList attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = ClasspathEntry.decodeExtraAttributes(attributeList); attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = ClasspathEntry.decodeAccessRules(attributeList); IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, sourceAttachPath, sourceAttachRootPath, accessRules, extraAttributes, false/*not exported*/); res.add(entry); } } } IClasspathEntry[] entries= (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]); return new UserLibrary(entries, isSystem); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static byte[] readByteTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } return bytes; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static long[] readLongTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if (length % 8 != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into longs long[] longs = new long[length / 8]; int i = 0; int longIndex = 0; while (true) { longs[longIndex++] = (((long) (bytes[i++] & 0xFF)) << 56) + (((long) (bytes[i++] & 0xFF)) << 48) + (((long) (bytes[i++] & 0xFF)) << 40) + (((long) (bytes[i++] & 0xFF)) << 32) + (((long) (bytes[i++] & 0xFF)) << 24) + (((long) (bytes[i++] & 0xFF)) << 16) + (((long) (bytes[i++] & 0xFF)) << 8) + (bytes[i++] & 0xFF); if (i == length) break; } return longs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static char[] readTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if ((length & 1) != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into chars char[] chars = new char[length / 2]; int i = 0; int charIndex = 0; while (true) { chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); if (i == length) break; } return chars; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static String buildAllDirectoriesInto(String outputPath, String relativeFileName) throws IOException { char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; File f; outputPath = outputPath.replace('/', fileSeparatorChar); // these could be optimized out if we normalized paths once and for // all relativeFileName = relativeFileName.replace('/', fileSeparatorChar); String outputDirPath, fileName; int separatorIndex = relativeFileName.lastIndexOf(fileSeparatorChar); if (separatorIndex == -1) { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath.substring(0, outputPath.length() - 1); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath; fileName = outputPath + fileSeparator + relativeFileName; } } else { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath + relativeFileName.substring(0, separatorIndex); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath + fileSeparator + relativeFileName.substring(0, separatorIndex); fileName = outputPath + fileSeparator + relativeFileName; } } f = new File(outputDirPath); f.mkdirs(); if (f.isDirectory()) { return fileName; } else { // the directory creation failed for some reason - retry using // a slower algorithm so as to refine the diagnostic if (outputPath.endsWith(fileSeparator)) { outputPath = outputPath.substring(0, outputPath.length() - 1); } f = new File(outputPath); boolean checkFileType = false; if (f.exists()) { checkFileType = true; // pre-existed } else { // we have to create that directory if (!f.mkdirs()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValidAll, f.getAbsolutePath())); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } StringBuffer outDir = new StringBuffer(outputPath); outDir.append(fileSeparator); StringTokenizer tokenizer = new StringTokenizer(relativeFileName, fileSeparator); String token = tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { f = new File(outDir.append(token).append(fileSeparator).toString()); checkFileType = false; // reset if (f.exists()) { checkFileType = true; // this is suboptimal, but it catches corner cases // in which a regular file pre-exists } else { // we have to create that directory if (!f.mkdir()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValid, outDir.substring(outputPath.length() + 1, outDir.length() - 1), outputPath)); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } token = tokenizer.nextToken(); } // token contains the last one return outDir.append(token).toString(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { InputStream stream = null; try { InputStream inputStream = zip.getInputStream(ze); if (inputStream == null) throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ stream = new BufferedInputStream(inputStream); return getInputStreamAsByteArray(stream, (int) ze.getSize()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
4
              
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
131
              
// in scripts/GenerateBuildScript.java
private static void dumpAllProperties(Writer writer, File sourceDir, ArrayList collector, String gcj_exe, String dest_dir) throws IOException { writer.write(" <echo message=\"compiling resources -> .o\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ for (int i = 0, max = collector.size(); i < max; i++) { String absolutePath = (String) collector.get(i); String fileName = absolutePath.substring(sourceDir.getAbsolutePath().length() + 1); writer.write(MessageFormat.format(" <exec dir=\"{1}\" executable=\"$'{'gcc-path'}'/bin/{0}\">" + LINE_SEPARATOR, new Object[] { gcj_exe, dest_dir})); //$NON-NLS-1$ writer.write(" <arg line=\"--resource "); //$NON-NLS-1$ writer.write(fileName + " " + fileName + " -c -o " + getObjectName(fileName) + "\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ writer.write(" </exec>" + LINE_SEPARATOR); //$NON-NLS-1$ } }
// in scripts/GenerateBuildScript.java
private static void dumpAllClassFiles(Writer writer, File sourceDir, ArrayList collector, String gcj_exe, String dest_dir) throws IOException { writer.write(" <echo message=\"compiling class files -> .o\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ writer.write( MessageFormat.format( " <apply failonerror=\"true\" executable=\"$'{'gcc-path'}'/bin/{0}\" dest=\"{1}\" parallel=\"false\">" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"--verbose\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"--classpath={1}\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-O2\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-c\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-fassume-compiled\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-march=pentium4\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-mfpmath=sse\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <srcfile/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-o\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <targetfile/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <fileset dir=\"{1}\" includes=\"**/*.class\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <mapper type=\"glob\" from=\"*.class\" to=\"*.o\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " </apply>" + LINE_SEPARATOR + LINE_SEPARATOR,//$NON-NLS-1$ new Object[] { gcj_exe, dest_dir })); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
public void initialize() throws IOException { // nothing to do }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
public void initialize() throws IOException { if (this.zipFile == null) { this.zipFile = new ZipFile(this.file); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MultiTypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { if (this.simpleNames == null) { // if no simple names then return all possible ones from index return index.query(getIndexCategories(), null, -1); // match rule is irrelevant when the key is null } int count = -1; int numOfNames = this.simpleNames.length; EntryResult[][] allResults = numOfNames > 1 ? new EntryResult[numOfNames][] : null; for (int i = 0; i < numOfNames; i++) { char[] key = this.simpleNames[i]; int matchRule = getMatchRule(); switch(getMatchMode()) { case R_PREFIX_MATCH : // do a prefix query with the simpleName break; case R_EXACT_MATCH : // do a prefix query with the simpleName matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; key = CharOperation.append(key, SEPARATOR); break; case R_PATTERN_MATCH : if (key[key.length - 1] != '*') key = CharOperation.concat(key, ONE_STAR, SEPARATOR); break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the simpleName break; } EntryResult[] entries = index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null if (entries != null) { if (allResults == null) return entries; allResults[++count] = entries; } } if (count == -1) return null; int total = 0; for (int i = 0; i <= count; i++) total += allResults[i].length; EntryResult[] allEntries = new EntryResult[total]; int next = 0; for (int i = 0; i <= count; i++) { EntryResult[] entries = allResults[i]; System.arraycopy(entries, 0, allEntries, next, entries.length); next += entries.length; } return allEntries; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public static void findIndexMatches(SearchPattern pattern, Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { pattern.findIndexMatches(index, requestor, participant, scope, monitor); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.selector; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_EXACT_MATCH : if (this.selector != null && this.parameterCount >= 0 && !this.varargs) key = createIndexKey(this.selector, this.parameterCount); else { // do a prefix query with the selector matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; } break; case R_PREFIX_MATCH : // do a prefix query with the selector break; case R_PATTERN_MATCH : if (this.parameterCount >= 0 && !this.varargs) key = createIndexKey(this.selector == null ? ONE_STAR : this.selector, this.parameterCount); else if (this.selector != null && this.selector[this.selector.length - 1] != '*') key = CharOperation.concat(this.selector, ONE_STAR, SEPARATOR); // else do a pattern query with just the selector break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the selector break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { return index.query(CATEGORIES, SECONDARY_PATTERN_KEY, R_PATTERN_MATCH | R_CASE_SENSITIVE); }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.superSimpleName; // can be null int matchRule = getMatchRule(); // cannot include the superQualification since it may not exist in the index switch(getMatchMode()) { case R_EXACT_MATCH : // do a prefix query with the superSimpleName matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; if (this.superSimpleName != null) key = CharOperation.append(this.superSimpleName, SEPARATOR); break; case R_PREFIX_MATCH : // do a prefix query with the superSimpleName break; case R_PATTERN_MATCH : // do a pattern query with the superSimpleName break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the superSimpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { // per construction, OR pattern can only be used with a PathCollector (which already gather results using a set) try { index.startQuery(); for (int i = 0, length = this.patterns.length; i < length; i++) this.patterns[i].findIndexMatches(index, requestor, participant, scope, progressMonitor); } finally { index.stopQuery(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.declaringSimpleName; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_EXACT_MATCH : if (this.declaringSimpleName != null && this.parameterCount >= 0 && !this.varargs) { key = createIndexKey(this.declaringSimpleName, this.parameterCount); } matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; break; case R_PREFIX_MATCH : // do a prefix query with the declaringSimpleName break; case R_PATTERN_MATCH : if (this.parameterCount >= 0 && !this.varargs) { key = CharOperation.concat(createIndexKey(this.declaringSimpleName == null ? ONE_STAR : this.declaringSimpleName, this.parameterCount), ONE_STAR); } else if (this.declaringSimpleName != null && this.declaringSimpleName[this.declaringSimpleName.length - 1] != '*') { key = CharOperation.concat(this.declaringSimpleName, ONE_STAR, SEPARATOR); } else if (key != null){ key = CharOperation.concat(key, ONE_STAR); } // else do a pattern query with just the declaringSimpleName break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the declaringSimpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.simpleName; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_PREFIX_MATCH : // do a prefix query with the simpleName break; case R_EXACT_MATCH : matchRule &= ~R_EXACT_MATCH; if (this.simpleName != null) { matchRule |= R_PREFIX_MATCH; key = this.pkg == null ? CharOperation.append(this.simpleName, SEPARATOR) : CharOperation.concat(this.simpleName, SEPARATOR, this.pkg, SEPARATOR, CharOperation.NO_CHAR); break; // do a prefix query with the simpleName and possibly the pkg } matchRule |= R_PATTERN_MATCH; // $FALL-THROUGH$ - fall thru to encode the key and do a pattern query case R_PATTERN_MATCH : if (this.pkg == null) { if (this.simpleName == null) { switch(this.typeSuffix) { case CLASS_SUFFIX : case INTERFACE_SUFFIX : case ENUM_SUFFIX : case ANNOTATION_TYPE_SUFFIX : case CLASS_AND_INTERFACE_SUFFIX : case CLASS_AND_ENUM_SUFFIX : case INTERFACE_AND_ANNOTATION_SUFFIX : // null key already returns all types // key = new char[] {ONE_STAR[0], SEPARATOR, ONE_STAR[0]}; break; } } else if (this.simpleName[this.simpleName.length - 1] != '*') { key = CharOperation.concat(this.simpleName, ONE_STAR, SEPARATOR); } break; // do a pattern query with the current encoded key } // must decode to check enclosingTypeNames due to the encoding of local types key = CharOperation.concat( this.simpleName == null ? ONE_STAR : this.simpleName, SEPARATOR, this.pkg, SEPARATOR, ONE_STAR); break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the simpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/IntersectingPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); resetQuery(); SimpleSet intersectedNames = null; try { index.startQuery(); do { SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); SimpleSet newIntersectedNames = new SimpleSet(3); for (int i = 0, l = entries.length; i < l; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { String[] names = entry.getDocumentNames(index); if (intersectedNames != null) { for (int j = 0, n = names.length; j < n; j++) if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]); } else { for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]); } } } if (newIntersectedNames.elementSize == 0) return; intersectedNames = newIntersectedNames; } while (hasNextQuery()); } finally { index.stopQuery(); } String containerPath = index.containerPath; char separator = index.separator; Object[] names = intersectedNames.values; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) acceptMatch((String) names[i], containerPath, separator, null/*no pattern*/, requestor, participant, scope, progressMonitor); // AndPatterns cannot provide the decoded result }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
public void saveIndex(Index index) throws IOException { // must have permission to write from the write monitor if (index.hasChanged()) { if (VERBOSE) Util.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$ index.save(); } synchronized (this) { IPath containerPath = new Path(index.containerPath); if (this.jobEnd > this.jobStart) { for (int i = this.jobEnd; i > this.jobStart; i--) { // skip the current job IJob job = this.awaitingJobs[i]; if (job instanceof IndexRequest) if (((IndexRequest) job).containerPath.equals(containerPath)) return; } } IPath indexLocation = computeIndexLocation(containerPath); updateIndexState(indexLocation, SAVED_STATE); } }
// in search/org/eclipse/jdt/internal/core/index/EntryResult.java
public String[] getDocumentNames(Index index) throws java.io.IOException { if (this.documentTables != null) { int length = this.documentTables.length; if (length == 1 && this.documentNames == null) { // have a single table Object offset = this.documentTables[0]; int[] numbers = index.diskIndex.readDocumentNumbers(offset); String[] names = new String[numbers.length]; for (int i = 0, l = numbers.length; i < l; i++) names[i] = index.diskIndex.readDocumentName(numbers[i]); return names; } for (int i = 0; i < length; i++) { Object offset = this.documentTables[i]; int[] numbers = index.diskIndex.readDocumentNumbers(offset); for (int j = 0, k = numbers.length; j < k; j++) addDocumentName(index.diskIndex.readDocumentName(numbers[j])); } } if (this.documentNames == null) return CharOperation.NO_STRINGS; String[] names = new String[this.documentNames.elementSize]; int count = 0; Object[] values = this.documentNames.values; for (int i = 0, l = values.length; i < l; i++) if (values[i] != null) names[count++] = (String) values[i]; return names; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public EntryResult[] query(char[][] categories, char[] key, int matchRule) throws IOException { if (this.memoryIndex.shouldMerge() && this.monitor.exitReadEnterWrite()) { try { save(); } finally { this.monitor.exitWriteEnterRead(); } } HashtableOfObject results; int rule = matchRule & MATCH_RULE_INDEX_MASK; if (this.memoryIndex.hasChanged()) { results = this.diskIndex.addQueryResults(categories, key, rule, this.memoryIndex); results = this.memoryIndex.addQueryResults(categories, key, rule, results); } else { results = this.diskIndex.addQueryResults(categories, key, rule, null); } if (results == null) return null; EntryResult[] entryResults = new EntryResult[results.elementSize]; int count = 0; Object[] values = results.valueTable; for (int i = 0, l = values.length; i < l; i++) { EntryResult result = (EntryResult) values[i]; if (result != null) entryResults[count++] = result; } return entryResults; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public String[] queryDocumentNames(String substring) throws IOException { SimpleSet results; if (this.memoryIndex.hasChanged()) { results = this.diskIndex.addDocumentNames(substring, this.memoryIndex); this.memoryIndex.addDocumentNames(substring, results); } else { results = this.diskIndex.addDocumentNames(substring, null); } if (results.elementSize == 0) return null; String[] documentNames = new String[results.elementSize]; int count = 0; Object[] paths = results.values; for (int i = 0, l = paths.length; i < l; i++) if (paths[i] != null) documentNames[count++] = (String) paths[i]; return documentNames; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public void reset() throws IOException { this.memoryIndex = new MemoryIndex(); this.diskIndex = new DiskIndex(this.diskIndex.indexFile.getCanonicalPath()); this.diskIndex.initialize(false/*do not reuse the index file*/); }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public void save() throws IOException { // must own the write lock of the monitor if (!hasChanged()) return; int numberOfChanges = this.memoryIndex.docsToReferences.elementSize; this.diskIndex.separator = this.separator; this.diskIndex = this.diskIndex.mergeWith(this.memoryIndex); this.memoryIndex = new MemoryIndex(); if (numberOfChanges > 1000) System.gc(); // reclaim space if the MemoryIndex was very BIG }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
SimpleSet addDocumentNames(String substring, MemoryIndex memoryIndex) throws IOException { // must skip over documents which have been added/changed/deleted in the memory index String[] docNames = readAllDocumentNames(); SimpleSet results = new SimpleSet(docNames.length); if (substring == null) { if (memoryIndex == null) { for (int i = 0, l = docNames.length; i < l; i++) results.add(docNames[i]); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; for (int i = 0, l = docNames.length; i < l; i++) { String docName = docNames[i]; if (!docsToRefs.containsKey(docName)) results.add(docName); } } } else { if (memoryIndex == null) { for (int i = 0, l = docNames.length; i < l; i++) if (docNames[i].startsWith(substring, 0)) results.add(docNames[i]); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; for (int i = 0, l = docNames.length; i < l; i++) { String docName = docNames[i]; if (docName.startsWith(substring, 0) && !docsToRefs.containsKey(docName)) results.add(docName); } } } return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private HashtableOfObject addQueryResult(HashtableOfObject results, char[] word, Object docs, MemoryIndex memoryIndex, boolean prevResults) throws IOException { // must skip over documents which have been added/changed/deleted in the memory index if (results == null) results = new HashtableOfObject(13); EntryResult result = prevResults ? (EntryResult) results.get(word) : null; if (memoryIndex == null) { if (result == null) results.putUnsafely(word, new EntryResult(word, docs)); else result.addDocumentTable(docs); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; if (result == null) result = new EntryResult(word, null); int[] docNumbers = readDocumentNumbers(docs); for (int i = 0, l = docNumbers.length; i < l; i++) { String docName = readDocumentName(docNumbers[i]); if (!docsToRefs.containsKey(docName)) result.addDocumentName(docName); } if (!result.isEmpty()) results.put(word, result); } return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
HashtableOfObject addQueryResults(char[][] categories, char[] key, int matchRule, MemoryIndex memoryIndex) throws IOException { // assumes sender has called startQuery() & will call stopQuery() when finished if (this.categoryOffsets == null) return null; // file is empty HashtableOfObject results = null; // initialized if needed // No need to check the results table for duplicacy while processing the // first category table or if the first category tables doesn't have any results. boolean prevResults = false; if (key == null) { for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], true); // cache if key is null since its a definite match if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; if (results == null) results = new HashtableOfObject(wordsToDocNumbers.elementSize); for (int j = 0, m = words.length; j < m; j++) if (words[j] != null) results = addQueryResult(results, words[j], values[j], memoryIndex, prevResults); } prevResults = results != null; } if (results != null && this.cachedChunks == null) cacheDocumentNames(); } else { switch (matchRule) { case SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); Object value; if (wordsToDocNumbers != null && (value = wordsToDocNumbers.get(key)) != null) results = addQueryResult(results, key, value, memoryIndex, prevResults); prevResults = results != null; } break; case SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CASE_SENSITIVE: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; for (int j = 0, m = words.length; j < m; j++) { char[] word = words[j]; if (word != null && key[0] == word[0] && CharOperation.prefixEquals(key, word)) results = addQueryResult(results, word, values[j], memoryIndex, prevResults); } } prevResults = results != null; } break; default: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; for (int j = 0, m = words.length; j < m; j++) { char[] word = words[j]; if (word != null && Index.isMatch(key, word, matchRule)) results = addQueryResult(results, word, values[j], memoryIndex, prevResults); } } prevResults = results != null; } } } if (results == null) return null; return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void cacheDocumentNames() throws IOException { // will need all document names so get them now this.cachedChunks = new String[this.numberOfChunks][]; FileInputStream stream = new FileInputStream(this.indexFile); try { if (this.numberOfChunks > 5) BUFFER_READ_SIZE <<= 1; int offset = this.chunkOffsets[0]; stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); for (int i = 0; i < this.numberOfChunks; i++) { int size = i == this.numberOfChunks - 1 ? this.sizeOfLastChunk : CHUNK_SIZE; readChunk(this.cachedChunks[i] = new String[size], stream, 0, size); } } catch (IOException e) { this.cachedChunks = null; throw e; } finally { stream.close(); this.streamBuffer = null; BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
void initialize(boolean reuseExistingFile) throws IOException { if (this.indexFile.exists()) { if (reuseExistingFile) { FileInputStream stream = new FileInputStream(this.indexFile); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, 128); try { char[] signature = readStreamChars(stream); if (!CharOperation.equals(signature, SIGNATURE_CHARS)) { throw new IOException(Messages.exception_wrongFormat); } this.headerInfoOffset = readStreamInt(stream); if (this.headerInfoOffset > 0) { // file is empty if its not set stream.skip(this.headerInfoOffset - this.bufferEnd); // assume that the header info offset is over current buffer end this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); readHeaderInfo(stream); } } finally { stream.close(); } return; } if (!this.indexFile.delete()) { if (DEBUG) System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$ } } if (this.indexFile.createNewFile()) { FileOutputStream stream = new FileOutputStream(this.indexFile, false); try { this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; writeStreamChars(stream, SIGNATURE_CHARS); writeStreamInt(stream, -1); // file is empty // write the buffer to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } } finally { stream.close(); } } else { if (DEBUG) System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$ } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException { if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file if (DEBUG) System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$ } else if (!newIndexFile.createNewFile()) { if (DEBUG) System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$ } int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize; this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); this.categoryTables = new HashtableOfObject(size); this.separator = diskIndex.separator; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void mergeCategories(DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException { // at this point, this.categoryTables contains the names -> wordsToDocs added in copyQueryResults() char[][] oldNames = onDisk.categoryOffsets.keyTable; for (int i = 0, l = oldNames.length; i < l; i++) { char[] oldName = oldNames[i]; if (oldName != null && !this.categoryTables.containsKey(oldName)) this.categoryTables.put(oldName, null); } char[][] categoryNames = this.categoryTables.keyTable; for (int i = 0, l = categoryNames.length; i < l; i++) if (categoryNames[i] != null) mergeCategory(categoryNames[i], onDisk, positions, stream); this.categoryTables = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void mergeCategory(char[] categoryName, DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException { HashtableOfObject wordsToDocs = (HashtableOfObject) this.categoryTables.get(categoryName); if (wordsToDocs == null) wordsToDocs = new HashtableOfObject(3); HashtableOfObject oldWordsToDocs = onDisk.readCategoryTable(categoryName, true); if (oldWordsToDocs != null) { char[][] oldWords = oldWordsToDocs.keyTable; Object[] oldArrayOffsets = oldWordsToDocs.valueTable; nextWord: for (int i = 0, l = oldWords.length; i < l; i++) { char[] oldWord = oldWords[i]; if (oldWord != null) { int[] oldDocNumbers = (int[]) oldArrayOffsets[i]; int length = oldDocNumbers.length; int[] mappedNumbers = new int[length]; int count = 0; for (int j = 0; j < length; j++) { int pos = positions[oldDocNumbers[j]]; if (pos > RE_INDEXED) // forget any reference to a document which was deleted or re_indexed mappedNumbers[count++] = pos; } if (count < length) { if (count == 0) continue nextWord; // skip words which no longer have any references System.arraycopy(mappedNumbers, 0, mappedNumbers = new int[count], 0, count); } Object o = wordsToDocs.get(oldWord); if (o == null) { wordsToDocs.putUnsafely(oldWord, mappedNumbers); } else { IntList list = null; if (o instanceof IntList) { list = (IntList) o; } else { list = new IntList((int[]) o); wordsToDocs.put(oldWord, list); } for (int j = 0; j < count; j++) list.add(mappedNumbers[j]); } } } onDisk.categoryTables.put(categoryName, null); // flush cached table } writeCategoryTable(categoryName, wordsToDocs, stream); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException { // assume write lock is held // compute & write out new docNames String[] docNames = readAllDocumentNames(); int previousLength = docNames.length; int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames SimpleLookupTable indexedDocuments = new SimpleLookupTable(3); // for each new/changed document in the memoryIndex docNames = computeDocumentNames(docNames, positions, indexedDocuments, memoryIndex); if (docNames.length == 0) { if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved // index is now empty since all the saved documents were removed DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath()); newDiskIndex.initialize(false); return newDiskIndex; } DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$ try { newDiskIndex.initializeFrom(this, newDiskIndex.indexFile); FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false); int offsetToHeader = -1; try { newDiskIndex.writeAllDocumentNames(docNames, stream); docNames = null; // free up the space // add each new/changed doc to empty category tables using its new position # if (indexedDocuments.elementSize > 0) { Object[] names = indexedDocuments.keyTable; Object[] integerPositions = indexedDocuments.valueTable; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) newDiskIndex.copyQueryResults( (HashtableOfObject) memoryIndex.docsToReferences.get(names[i]), ((Integer) integerPositions[i]).intValue()); } indexedDocuments = null; // free up the space // merge each category table with the new ones & write them out if (previousLength == 0) newDiskIndex.writeCategories(stream); else newDiskIndex.mergeCategories(this, positions, stream); offsetToHeader = newDiskIndex.streamEnd; newDiskIndex.writeHeaderInfo(stream); positions = null; // free up the space } finally { stream.close(); this.streamBuffer = null; } newDiskIndex.writeOffsetToHeader(offsetToHeader); // rename file by deleting previous index file & renaming temp one if (this.indexFile.exists() && !this.indexFile.delete()) { if (DEBUG) System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$ } if (!newDiskIndex.indexFile.renameTo(this.indexFile)) { if (DEBUG) System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$ } } catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; } newDiskIndex.indexFile = this.indexFile; return newDiskIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private synchronized String[] readAllDocumentNames() throws IOException { if (this.numberOfChunks <= 0) return CharOperation.NO_STRINGS; FileInputStream stream = new FileInputStream(this.indexFile); try { int offset = this.chunkOffsets[0]; stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); int lastIndex = this.numberOfChunks - 1; String[] docNames = new String[lastIndex * CHUNK_SIZE + this.sizeOfLastChunk]; for (int i = 0; i < this.numberOfChunks; i++) readChunk(docNames, stream, i * CHUNK_SIZE, i < lastIndex ? CHUNK_SIZE : this.sizeOfLastChunk); return docNames; } finally { stream.close(); this.streamBuffer = null; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private synchronized HashtableOfObject readCategoryTable(char[] categoryName, boolean readDocNumbers) throws IOException { // result will be null if categoryName is unknown int offset = this.categoryOffsets.get(categoryName); if (offset == HashtableOfIntValues.NO_VALUE) { return null; } if (this.categoryTables == null) { this.categoryTables = new HashtableOfObject(3); } else { HashtableOfObject cachedTable = (HashtableOfObject) this.categoryTables.get(categoryName); if (cachedTable != null) { if (readDocNumbers) { // must cache remaining document number arrays Object[] arrayOffsets = cachedTable.valueTable; for (int i = 0, l = arrayOffsets.length; i < l; i++) if (arrayOffsets[i] instanceof Integer) arrayOffsets[i] = readDocumentNumbers(arrayOffsets[i]); } return cachedTable; } } FileInputStream stream = new FileInputStream(this.indexFile); HashtableOfObject categoryTable = null; char[][] matchingWords = null; int count = 0; int firstOffset = -1; this.streamBuffer = new byte[BUFFER_READ_SIZE]; try { stream.skip(offset); this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); int size = readStreamInt(stream); try { if (size < 0) { // DEBUG System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ } categoryTable = new HashtableOfObject(size); } catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; } int largeArraySize = 256; for (int i = 0; i < size; i++) { char[] word = readStreamChars(stream); int arrayOffset = readStreamInt(stream); // if arrayOffset is: // <= 0 then the array size == 1 with the value -> -arrayOffset // > 1 & < 256 then the size of the array is > 1 & < 256, the document array follows immediately // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table) if (arrayOffset <= 0) { categoryTable.putUnsafely(word, new int[] {-arrayOffset}); // store 1 element array by negating documentNumber } else if (arrayOffset < largeArraySize) { categoryTable.putUnsafely(word, readStreamDocumentArray(stream, arrayOffset)); // read in-lined array providing size } else { arrayOffset = readStreamInt(stream); // read actual offset if (readDocNumbers) { if (matchingWords == null) matchingWords = new char[size][]; if (count == 0) firstOffset = arrayOffset; matchingWords[count++] = word; } categoryTable.putUnsafely(word, new Integer(arrayOffset)); // offset to array in the file } } this.categoryTables.put(INTERNED_CATEGORY_NAMES.get(categoryName), categoryTable); // cache the table as long as its not too big // in practice, some tables can be greater than 500K when they contain more than 10K elements this.cachedCategoryName = categoryTable.elementSize < 20000 ? categoryName : null; } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { stream.close(); } if (matchingWords != null && count > 0) { stream = new FileInputStream(this.indexFile); try { stream.skip(firstOffset); this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); for (int i = 0; i < count; i++) { // each array follows the previous one categoryTable.put(matchingWords[i], readStreamDocumentArray(stream, readStreamInt(stream))); } } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { stream.close(); } } this.streamBuffer = null; return categoryTable; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readChunk(String[] docNames, FileInputStream stream, int index, int size) throws IOException { String current = new String(readStreamChars(stream)); docNames[index++] = current; for (int i = 1; i < size; i++) { if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int start = this.streamBuffer[this.bufferIndex++] & 0xFF; int end = this.streamBuffer[this.bufferIndex++] & 0xFF; String next = new String(readStreamChars(stream)); if (start > 0) { if (end > 0) { int length = current.length(); next = current.substring(0, start) + next + current.substring(length - end, length); } else { next = current.substring(0, start) + next; } } else if (end > 0) { int length = current.length(); next = next + current.substring(length - end, length); } docNames[index++] = next; current = next; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized int[] readDocumentNumbers(Object arrayOffset) throws IOException { // arrayOffset is either a cached array of docNumbers or an Integer offset in the file if (arrayOffset instanceof int[]) return (int[]) arrayOffset; FileInputStream stream = new FileInputStream(this.indexFile); try { int offset = ((Integer) arrayOffset).intValue(); stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); return readStreamDocumentArray(stream, readStreamInt(stream)); } finally { stream.close(); this.streamBuffer = null; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readHeaderInfo(FileInputStream stream) throws IOException { // must be same order as writeHeaderInfo() this.numberOfChunks = readStreamInt(stream); this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF; this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF; this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF); long fileLength = this.indexFile.length(); if (this.numberOfChunks > fileLength ) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } this.chunkOffsets = new int[this.numberOfChunks]; for (int i = 0; i < this.numberOfChunks; i++) this.chunkOffsets[i] = readStreamInt(stream); this.startOfCategoryTables = readStreamInt(stream); int size = readStreamInt(stream); this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); if (size > fileLength) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } char[] previousCategory = null; int offset = -1; for (int i = 0; i < size; i++) { char[] categoryName = INTERNED_CATEGORY_NAMES.get(readStreamChars(stream)); offset = readStreamInt(stream); this.categoryOffsets.put(categoryName, offset); // cache offset to category table if (previousCategory != null) { this.categoryEnds.put(previousCategory, offset); // cache end of the category table } previousCategory = categoryName; } if (previousCategory != null) { this.categoryEnds.put(previousCategory, this.headerInfoOffset); // cache end of the category table } this.categoryTables = new HashtableOfObject(3); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readStreamBuffer(FileInputStream stream) throws IOException { // if we're about to read a known amount at the end of the existing buffer, but it does not completely fit // so we need to shift the remaining bytes to be read, and fill the buffer from the stream if (this.bufferEnd < this.streamBuffer.length) return; // we're at the end of the stream - nothing left to read int bytesInBuffer = this.bufferEnd - this.bufferIndex; if (bytesInBuffer > 0) System.arraycopy(this.streamBuffer, this.bufferIndex, this.streamBuffer, 0, bytesInBuffer); this.bufferEnd = bytesInBuffer + stream.read(this.streamBuffer, bytesInBuffer, this.bufferIndex); this.bufferIndex = 0; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private char[] readStreamChars(FileInputStream stream) throws IOException { // read chars array length if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int length = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; length += this.streamBuffer[this.bufferIndex++] & 0xFF; // fill the chars from bytes buffer char[] word = new char[length]; int i = 0; while (i < length) { // how many characters can be decoded without refilling the buffer? int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3); // all the characters must already be in the buffer if we're at the end of the stream if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null) charsInBuffer = length; while (i < charsInBuffer) { byte b = this.streamBuffer[this.bufferIndex++]; switch (b & 0xF0) { case 0x00 : case 0x10 : case 0x20 : case 0x30 : case 0x40 : case 0x50 : case 0x60 : case 0x70 : word[i++]= (char) b; break; case 0xC0 : case 0xD0 : char next = (char) this.streamBuffer[this.bufferIndex++]; if ((next & 0xC0) != 0x80) { throw new UTFDataFormatException(); } char ch = (char) ((b & 0x1F) << 6); ch |= next & 0x3F; word[i++] = ch; break; case 0xE0 : char first = (char) this.streamBuffer[this.bufferIndex++]; char second = (char) this.streamBuffer[this.bufferIndex++]; if ((first & second & 0xC0) != 0x80) { throw new UTFDataFormatException(); } ch = (char) ((b & 0x0F) << 12); ch |= ((first& 0x3F) << 6); ch |= second & 0x3F; word[i++] = ch; break; default: throw new UTFDataFormatException(); } } if (i < length && stream != null) readStreamBuffer(stream); } return word; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private int[] readStreamDocumentArray(FileInputStream stream, int arraySize) throws IOException { int[] indexes = new int[arraySize]; if (arraySize == 0) return indexes; int i = 0; switch (this.documentReferenceSize) { case 1 : while (i < arraySize) { // how many bytes without refilling the buffer? int bytesInBuffer = i + this.bufferEnd - this.bufferIndex; if (bytesInBuffer > arraySize) bytesInBuffer = arraySize; while (i < bytesInBuffer) { indexes[i++] = this.streamBuffer[this.bufferIndex++] & 0xFF; } if (i < arraySize && stream != null) readStreamBuffer(stream); } break; case 2 : while (i < arraySize) { // how many shorts without refilling the buffer? int shortsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 2); if (shortsInBuffer > arraySize) shortsInBuffer = arraySize; while (i < shortsInBuffer) { int val = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; indexes[i++] = val + (this.streamBuffer[this.bufferIndex++] & 0xFF); } if (i < arraySize && stream != null) readStreamBuffer(stream); } break; default : while (i < arraySize) { indexes[i++] = readStreamInt(stream); } break; } return indexes; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private int readStreamInt(FileInputStream stream) throws IOException { if (this.bufferIndex + 4 >= this.bufferEnd) { readStreamBuffer(stream); } int val = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 24; val += (this.streamBuffer[this.bufferIndex++] & 0xFF) << 16; val += (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; return val + (this.streamBuffer[this.bufferIndex++] & 0xFF); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeAllDocumentNames(String[] sortedDocNames, FileOutputStream stream) throws IOException { if (sortedDocNames.length == 0) throw new IllegalArgumentException(); // assume the file was just created by initializeFrom() this.streamBuffer = new byte[BUFFER_WRITE_SIZE]; this.bufferIndex = 0; this.streamEnd = 0; // in order, write: SIGNATURE & headerInfoOffset place holder, then each compressed chunk of document names writeStreamChars(stream, SIGNATURE_CHARS); this.headerInfoOffset = this.streamEnd; writeStreamInt(stream, -1); // will overwrite with correct value later int size = sortedDocNames.length; this.numberOfChunks = (size / CHUNK_SIZE) + 1; this.sizeOfLastChunk = size % CHUNK_SIZE; if (this.sizeOfLastChunk == 0) { this.numberOfChunks--; this.sizeOfLastChunk = CHUNK_SIZE; } this.documentReferenceSize = size <= 0x7F ? 1 : (size <= 0x7FFF ? 2 : 4); // number of bytes used to encode a reference this.chunkOffsets = new int[this.numberOfChunks]; int lastIndex = this.numberOfChunks - 1; for (int i = 0; i < this.numberOfChunks; i++) { this.chunkOffsets[i] = this.streamEnd; int chunkSize = i == lastIndex ? this.sizeOfLastChunk : CHUNK_SIZE; int chunkIndex = i * CHUNK_SIZE; String current = sortedDocNames[chunkIndex]; writeStreamChars(stream, current.toCharArray()); for (int j = 1; j < chunkSize; j++) { String next = sortedDocNames[chunkIndex + j]; int len1 = current.length(); int len2 = next.length(); int max = len1 < len2 ? len1 : len2; int start = 0; // number of identical characters at the beginning (also the index of first character that is different) while (current.charAt(start) == next.charAt(start)) { start++; if (max == start) break; // current is 'abba', next is 'abbab' } if (start > 255) start = 255; int end = 0; // number of identical characters at the end while (current.charAt(--len1) == next.charAt(--len2)) { end++; if (len2 == start) break; // current is 'abbba', next is 'abba' if (len1 == 0) break; // current is 'xabc', next is 'xyabc' } if (end > 255) end = 255; if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) start; this.streamBuffer[this.bufferIndex++] = (byte) end; this.streamEnd += 2; int last = next.length() - end; writeStreamChars(stream, (start < last ? CharOperation.subarray(next.toCharArray(), start, last) : CharOperation.NO_CHAR)); current = next; } } this.startOfCategoryTables = this.streamEnd + 1; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeCategories(FileOutputStream stream) throws IOException { char[][] categoryNames = this.categoryTables.keyTable; Object[] tables = this.categoryTables.valueTable; for (int i = 0, l = categoryNames.length; i < l; i++) if (categoryNames[i] != null) writeCategoryTable(categoryNames[i], (HashtableOfObject) tables[i], stream); this.categoryTables = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeCategoryTable(char[] categoryName, HashtableOfObject wordsToDocs, FileOutputStream stream) throws IOException { // the format of a category table is as follows: // any document number arrays with >= 256 elements are written before the table (the offset to each array is remembered) // then the number of word->int[] pairs in the table is written // for each word -> int[] pair, the word is written followed by: // an int <= 0 if the array size == 1 // an int > 1 & < 256 for the size of the array if its > 1 & < 256, the document array follows immediately // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table) int largeArraySize = 256; Object[] values = wordsToDocs.valueTable; for (int i = 0, l = values.length; i < l; i++) { Object o = values[i]; if (o != null) { if (o instanceof IntList) o = values[i] = ((IntList) values[i]).asArray(); int[] documentNumbers = (int[]) o; if (documentNumbers.length >= largeArraySize) { values[i] = new Integer(this.streamEnd); writeDocumentNumbers(documentNumbers, stream); } } } this.categoryOffsets.put(categoryName, this.streamEnd); // remember the offset to the start of the table this.categoryTables.put(categoryName, null); // flush cached table writeStreamInt(stream, wordsToDocs.elementSize); char[][] words = wordsToDocs.keyTable; for (int i = 0, l = words.length; i < l; i++) { Object o = values[i]; if (o != null) { writeStreamChars(stream, words[i]); if (o instanceof int[]) { int[] documentNumbers = (int[]) o; if (documentNumbers.length == 1) writeStreamInt(stream, -documentNumbers[0]); // store an array of 1 element by negating the documentNumber (can be zero) else writeDocumentNumbers(documentNumbers, stream); } else { writeStreamInt(stream, largeArraySize); // mark to identify that an offset follows writeStreamInt(stream, ((Integer) o).intValue()); // offset in the file of the array of document numbers } } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeDocumentNumbers(int[] documentNumbers, FileOutputStream stream) throws IOException { // must store length as a positive int to detect in-lined array of 1 element int length = documentNumbers.length; writeStreamInt(stream, length); Util.sort(documentNumbers); int start = 0; switch (this.documentReferenceSize) { case 1 : while ((this.bufferIndex + length - start) >= BUFFER_WRITE_SIZE) { // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part int bytesLeft = BUFFER_WRITE_SIZE - this.bufferIndex; for (int i=0; i < bytesLeft; i++) { this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } while (start < length) { this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } this.streamEnd += length; break; case 2 : while ((this.bufferIndex + ((length - start) * 2)) >= BUFFER_WRITE_SIZE) { // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part int shortsLeft = (BUFFER_WRITE_SIZE - this.bufferIndex) / 2; for (int i=0; i < shortsLeft; i++) { this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8); this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } while (start < length) { this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8); this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } this.streamEnd += length * 2; break; default : while (start < length) { writeStreamInt(stream, documentNumbers[start++]); } break; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeHeaderInfo(FileOutputStream stream) throws IOException { writeStreamInt(stream, this.numberOfChunks); if ((this.bufferIndex + 3) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) this.sizeOfLastChunk; this.streamBuffer[this.bufferIndex++] = (byte) this.documentReferenceSize; this.streamBuffer[this.bufferIndex++] = (byte) this.separator; this.streamEnd += 3; // apend the file with chunk offsets for (int i = 0; i < this.numberOfChunks; i++) { writeStreamInt(stream, this.chunkOffsets[i]); } writeStreamInt(stream, this.startOfCategoryTables); // append the file with the category offsets... # of name -> offset pairs, followed by each name & an offset to its word->doc# table writeStreamInt(stream, this.categoryOffsets.elementSize); char[][] categoryNames = this.categoryOffsets.keyTable; int[] offsets = this.categoryOffsets.valueTable; for (int i = 0, l = categoryNames.length; i < l; i++) { if (categoryNames[i] != null) { writeStreamChars(stream, categoryNames[i]); writeStreamInt(stream, offsets[i]); } } // ensure buffer is written to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeOffsetToHeader(int offsetToHeader) throws IOException { if (offsetToHeader > 0) { RandomAccessFile file = new RandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$ try { file.seek(this.headerInfoOffset); // offset to position in header file.writeInt(offsetToHeader); this.headerInfoOffset = offsetToHeader; // update to reflect the correct offset } finally { file.close(); } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamChars(FileOutputStream stream, char[] array) throws IOException { if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } int length = array.length; this.streamBuffer[this.bufferIndex++] = (byte) ((length >>> 8) & 0xFF); // store chars array length instead of bytes this.streamBuffer[this.bufferIndex++] = (byte) (length & 0xFF); // this will allow to read it faster this.streamEnd += 2; // we're assuming that very few char[] are so large that we need to flush the buffer more than once, if at all int totalBytesNeeded = length * 3; if (totalBytesNeeded <= BUFFER_WRITE_SIZE) { if (this.bufferIndex + totalBytesNeeded > BUFFER_WRITE_SIZE) { // flush the buffer now to make sure there is room for the array stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } writeStreamChars(stream, array, 0, length); } else { int charsPerWrite = BUFFER_WRITE_SIZE / 3; int start = 0; while (start < length) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; int charsLeftToWrite = length - start; int end = start + (charsPerWrite < charsLeftToWrite ? charsPerWrite : charsLeftToWrite); writeStreamChars(stream, array, start, end); start = end; } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamChars(FileOutputStream stream, char[] array, int start, int end) throws IOException { // start can NOT be == end // must have checked that there is enough room for end - start * 3 bytes in the buffer int oldIndex = this.bufferIndex; while (start < end) { int ch = array[start++]; if ((ch & 0x007F) == ch) { this.streamBuffer[this.bufferIndex++] = (byte) ch; } else if ((ch & 0x07FF) == ch) { // first two bits are stored in first byte byte b = (byte) (ch >> 6); b &= 0x1F; b |= 0xC0; this.streamBuffer[this.bufferIndex++] = b; // last six bits are stored in second byte b = (byte) (ch & 0x3F); b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; } else { // first four bits are stored in first byte byte b = (byte) (ch >> 12); b &= 0x0F; b |= 0xE0; this.streamBuffer[this.bufferIndex++] = b; // six following bits are stored in second byte b = (byte) (ch >> 6); b &= 0x3F; b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; // last six bits are stored in third byte b = (byte) (ch & 0x3F); b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; } } this.streamEnd += this.bufferIndex - oldIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamInt(FileOutputStream stream, int val) throws IOException { if ((this.bufferIndex + 4) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) (val >> 24); this.streamBuffer[this.bufferIndex++] = (byte) (val >> 16); this.streamBuffer[this.bufferIndex++] = (byte) (val >> 8); this.streamBuffer[this.bufferIndex++] = (byte) val; this.streamEnd += 4; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { index.startQuery(); SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); String containerPath = index.containerPath; char separator = index.separator; for (int i = 0, l = entries.length; i < l; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { // TODO (kent) some clients may not need the document names String[] names = entry.getDocumentNames(index); for (int j = 0, n = names.length; j < n; j++) acceptMatch(names[j], containerPath, separator, decodedResult, requestor, participant, scope, monitor); } } } finally { index.stopQuery(); } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public EntryResult[] queryIn(Index index) throws IOException { return index.query(getIndexCategories(), getIndexKey(), getMatchRule()); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
void load() throws IOException { loadProjects(getJavaModel()); loadVariables(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IAccessRule loadAccessRule() throws IOException { int problemId = loadInt(); IPath pattern = loadPath(); return new ClasspathAccessRule(pattern.toString().toCharArray(), problemId); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IAccessRule[] loadAccessRules() throws IOException { int count = loadInt(); if (count == 0) return ClasspathEntry.NO_ACCESS_RULES; IAccessRule[] rules = new IAccessRule[count]; for (int i = 0; i < count; ++i) rules[i] = loadAccessRule(); return rules; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathAttribute loadAttribute() throws IOException { String name = loadString(); String value = loadString(); return new ClasspathAttribute(name, value); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathAttribute[] loadAttributes() throws IOException { int count = loadInt(); if (count == 0) return ClasspathEntry.NO_EXTRA_ATTRIBUTES; IClasspathAttribute[] attributes = new IClasspathAttribute[count]; for (int i = 0; i < count; ++i) attributes[i] = loadAttribute(); return attributes; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private boolean loadBoolean() throws IOException { return this.in.readBoolean(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry[] loadClasspathEntries() throws IOException { int count = loadInt(); IClasspathEntry[] entries = new IClasspathEntry[count]; for (int i = 0; i < count; ++i) entries[i] = loadClasspathEntry(); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry loadClasspathEntry() throws IOException { int id = loadInt(); if (id < 0 || id > this.allClasspathEntryCount) throw new IOException("Unexpected classpathentry id"); //$NON-NLS-1$ if (id < this.allClasspathEntryCount) return this.allClasspathEntries[id]; int contentKind = loadInt(); int entryKind = loadInt(); IPath path = loadPath(); IPath[] inclusionPatterns = loadPaths(); IPath[] exclusionPatterns = loadPaths(); IPath sourceAttachmentPath = loadPath(); IPath sourceAttachmentRootPath = loadPath(); IPath specificOutputLocation = loadPath(); boolean isExported = loadBoolean(); IAccessRule[] accessRules = loadAccessRules(); boolean combineAccessRules = loadBoolean(); IClasspathAttribute[] extraAttributes = loadAttributes(); IClasspathEntry entry = new ClasspathEntry(contentKind, entryKind, path, inclusionPatterns, exclusionPatterns, sourceAttachmentPath, sourceAttachmentRootPath, specificOutputLocation, isExported, accessRules, combineAccessRules, extraAttributes); IClasspathEntry[] array = this.allClasspathEntries; if (array == null || id == array.length) { array = new IClasspathEntry[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allClasspathEntries, 0, array, 0, id); this.allClasspathEntries = array; } array[id] = entry; this.allClasspathEntryCount = id + 1; return entry; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadContainers(IJavaProject project) throws IOException { boolean projectIsAccessible = project.getProject().isAccessible(); int count = loadInt(); for (int i = 0; i < count; ++i) { IPath path = loadPath(); IClasspathEntry[] entries = loadClasspathEntries(); if (!projectIsAccessible) // avoid leaking deleted project's persisted container, // but still read the container as it is is part of the file format continue; IClasspathContainer container = new PersistedClasspathContainer(project, path, entries); containerPut(project, path, container); Map oldContainers = (Map) JavaModelManager.this.previousSessionContainers.get(project); if (oldContainers == null) { oldContainers = new HashMap(); JavaModelManager.this.previousSessionContainers.put(project, oldContainers); } oldContainers.put(path, container); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private int loadInt() throws IOException { return this.in.readInt(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IPath loadPath() throws IOException { if (loadBoolean()) return null; String portableString = loadString(); IPath path = (IPath) this.allPaths.get(portableString); if (path == null) { path = Path.fromPortableString(portableString); this.allPaths.put(portableString, path); } return path; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IPath[] loadPaths() throws IOException { int count = loadInt(); IPath[] pathArray = new IPath[count]; for (int i = 0; i < count; ++i) pathArray[i] = loadPath(); return pathArray; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadProjects(IJavaModel model) throws IOException { int count = loadInt(); for (int i = 0; i < count; ++i) { String projectName = loadString(); loadContainers(model.getJavaProject(projectName)); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private String loadString() throws IOException { int id = loadInt(); if (id < 0 || id > this.allStringsCount) throw new IOException("Unexpected string id"); //$NON-NLS-1$ if (id < this.allStringsCount) return this.allStrings[id]; String string = this.in.readUTF(); String[] array = this.allStrings; if (array == null || id == array.length) { array = new String[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allStrings, 0, array, 0, id); this.allStrings = array; } array[id] = string; this.allStringsCount = id + 1; return string; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadVariables() throws IOException { int size = loadInt(); Map loadedVars = new HashMap(size); for (int i = 0; i < size; ++i) { String varName = loadString(); IPath varPath = loadPath(); if (varPath != null) loadedVars.put(varName, varPath); } JavaModelManager.this.previousSessionVariables.putAll(loadedVars); JavaModelManager.this.variables.putAll(loadedVars); }
// 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 saveAccessRule(ClasspathAccessRule rule) throws IOException { saveInt(rule.problemId); savePath(rule.getPattern()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAccessRules(IAccessRule[] rules) throws IOException { int count = rules == null ? 0 : rules.length; saveInt(count); for (int i = 0; i < count; ++i) saveAccessRule((ClasspathAccessRule) rules[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAttribute(IClasspathAttribute attribute) throws IOException { saveString(attribute.getName()); saveString(attribute.getValue()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAttributes(IClasspathAttribute[] attributes) throws IOException { int count = attributes == null ? 0 : attributes.length; saveInt(count); for (int i = 0; i < count; ++i) saveAttribute(attributes[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathEntries(IClasspathEntry[] entries) throws IOException { int count = entries == null ? 0 : entries.length; saveInt(count); for (int i = 0; i < count; ++i) saveClasspathEntry(entries[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathEntry(IClasspathEntry entry) throws IOException { if (saveNewId(entry, this.classpathEntryIds)) { saveInt(entry.getContentKind()); saveInt(entry.getEntryKind()); savePath(entry.getPath()); savePaths(entry.getInclusionPatterns()); savePaths(entry.getExclusionPatterns()); savePath(entry.getSourceAttachmentPath()); savePath(entry.getSourceAttachmentRootPath()); savePath(entry.getOutputLocation()); this.out.writeBoolean(entry.isExported()); saveAccessRules(entry.getAccessRules()); this.out.writeBoolean(entry.combineAccessRules()); saveAttributes(entry.getExtraAttributes()); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveContainers(IJavaProject project, Map containerMap) throws IOException { saveInt(containerMap.size()); for (Iterator i = containerMap.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); IPath path = (IPath) entry.getKey(); IClasspathContainer container = (IClasspathContainer) entry.getValue(); IClasspathEntry[] cpEntries = null; if (container == null) { // container has not been initialized yet, use previous // session value // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=73969) container = getPreviousSessionContainer(path, project); } if (container != null) cpEntries = container.getClasspathEntries(); savePath(path); saveClasspathEntries(cpEntries); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveInt(int value) throws IOException { this.out.writeInt(value); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private boolean saveNewId(Object key, HashtableOfObjectToInt map) throws IOException { int id = map.get(key); if (id == -1) { int newId = map.size(); map.put(key, newId); saveInt(newId); return true; } else { saveInt(id); return false; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void savePath(IPath path) throws IOException { if (path == null) { this.out.writeBoolean(true); } else { this.out.writeBoolean(false); saveString(path.toPortableString()); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void savePaths(IPath[] paths) throws IOException { int count = paths == null ? 0 : paths.length; saveInt(count); for (int i = 0; i < count; ++i) savePath(paths[i]); }
// 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
private void saveString(String string) throws IOException { if (saveNewId(string, this.stringIds)) this.out.writeUTF(string); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariables(Map map) throws IOException { saveInt(map.size()); for (Iterator i = map.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); String varName = (String) entry.getKey(); IPath varPath = (IPath) entry.getValue(); saveString(varName); savePath(varPath); } }
// in model/org/eclipse/jdt/internal/core/builder/State.java
static State read(IProject project, DataInputStream in) throws IOException { if (JavaBuilder.DEBUG) System.out.println("About to read state " + project.getName()); //$NON-NLS-1$ if (VERSION != in.readByte()) { if (JavaBuilder.DEBUG) System.out.println("Found non-compatible state version... answered null for " + project.getName()); //$NON-NLS-1$ return null; } State newState = new State(); newState.javaProjectName = in.readUTF(); if (!project.getName().equals(newState.javaProjectName)) { if (JavaBuilder.DEBUG) System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$ return null; } newState.buildNumber = in.readInt(); newState.lastStructuralBuildTime = in.readLong(); int length = in.readInt(); newState.sourceLocations = new ClasspathMultiDirectory[length]; for (int i = 0; i < length; i++) { IContainer sourceFolder = project, outputFolder = project; String folderName; if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName); if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName); ClasspathMultiDirectory md = (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in), readNames(in)); if (in.readBoolean()) md.hasIndependentOutputFolder = true; newState.sourceLocations[i] = md; } length = in.readInt(); newState.binaryLocations = new ClasspathLocation[length]; IWorkspaceRoot root = project.getWorkspace().getRoot(); for (int i = 0; i < length; i++) { switch (in.readByte()) { case SOURCE_FOLDER : newState.binaryLocations[i] = newState.sourceLocations[in.readInt()]; break; case BINARY_FOLDER : IPath path = new Path(in.readUTF()); IContainer outputFolder = path.segmentCount() == 1 ? (IContainer) root.getProject(path.toString()) : (IContainer) root.getFolder(path); newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean(), readRestriction(in)); break; case EXTERNAL_JAR : newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF(), in.readLong(), readRestriction(in)); break; case INTERNAL_JAR : newState.binaryLocations[i] = ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF())), readRestriction(in)); } } newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong())); String[] internedTypeLocators = new String[length = in.readInt()]; for (int i = 0; i < length; i++) internedTypeLocators[i] = in.readUTF(); newState.typeLocators = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) newState.recordLocatorForType(in.readUTF(), internedTypeLocators[in.readInt()]); char[][] internedRootNames = ReferenceCollection.internSimpleNames(readNames(in), false); char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false); char[][][] internedQualifiedNames = new char[length = in.readInt()][][]; for (int i = 0; i < length; i++) { int qLength = in.readInt(); char[][] qName = new char[qLength][]; for (int j = 0; j < qLength; j++) qName[j] = internedSimpleNames[in.readInt()]; internedQualifiedNames[i] = qName; } internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames, false); newState.references = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) { String typeLocator = internedTypeLocators[in.readInt()]; ReferenceCollection collection = null; switch (in.readByte()) { case 1 : char[][] additionalTypeNames = readNames(in); char[][][] qualifiedNames = new char[in.readInt()][][]; for (int j = 0, m = qualifiedNames.length; j < m; j++) qualifiedNames[j] = internedQualifiedNames[in.readInt()]; char[][] simpleNames = new char[in.readInt()][]; for (int j = 0, m = simpleNames.length; j < m; j++) simpleNames[j] = internedSimpleNames[in.readInt()]; char[][] rootNames = new char[in.readInt()][]; for (int j = 0, m = rootNames.length; j < m; j++) rootNames[j] = internedRootNames[in.readInt()]; collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames, rootNames); break; case 2 : char[][][] qNames = new char[in.readInt()][][]; for (int j = 0, m = qNames.length; j < m; j++) qNames[j] = internedQualifiedNames[in.readInt()]; char[][] sNames = new char[in.readInt()][]; for (int j = 0, m = sNames.length; j < m; j++) sNames[j] = internedSimpleNames[in.readInt()]; char[][] rNames = new char[in.readInt()][]; for (int j = 0, m = rNames.length; j < m; j++) rNames[j] = internedRootNames[in.readInt()]; collection = new ReferenceCollection(qNames, sNames, rNames); } newState.references.put(typeLocator, collection); } if (JavaBuilder.DEBUG) System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$ return newState; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static char[] readName(DataInputStream in) throws IOException { int nLength = in.readInt(); char[] name = new char[nLength]; for (int j = 0; j < nLength; j++) name[j] = in.readChar(); return name; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static char[][] readNames(DataInputStream in) throws IOException { int length = in.readInt(); char[][] names = new char[length][]; for (int i = 0; i < length; i++) names[i] = readName(in); return names; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static AccessRuleSet readRestriction(DataInputStream in) throws IOException { int length = in.readInt(); if (length == 0) return null; // no restriction specified AccessRule[] accessRules = new AccessRule[length]; for (int i = 0; i < length; i++) { char[] pattern = readName(in); int problemId = in.readInt(); accessRules[i] = new ClasspathAccessRule(pattern, problemId); } JavaModelManager manager = JavaModelManager.getJavaModelManager(); return new AccessRuleSet(accessRules, in.readByte(), manager.intern(in.readUTF())); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
void write(DataOutputStream out) throws IOException { int length; Object[] keyTable; Object[] valueTable; /* * byte VERSION * String project name * int build number * int last structural build number */ out.writeByte(VERSION); out.writeUTF(this.javaProjectName); out.writeInt(this.buildNumber); out.writeLong(this.lastStructuralBuildTime); /* * ClasspathMultiDirectory[] * int id * String path(s) */ out.writeInt(length = this.sourceLocations.length); for (int i = 0; i < length; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; out.writeUTF(md.sourceFolder.getProjectRelativePath().toString()); out.writeUTF(md.binaryFolder.getProjectRelativePath().toString()); writeNames(md.inclusionPatterns, out); writeNames(md.exclusionPatterns, out); out.writeBoolean(md.hasIndependentOutputFolder); } /* * ClasspathLocation[] * int id * String path(s) */ out.writeInt(length = this.binaryLocations.length); next : for (int i = 0; i < length; i++) { ClasspathLocation c = this.binaryLocations[i]; if (c instanceof ClasspathMultiDirectory) { out.writeByte(SOURCE_FOLDER); for (int j = 0, m = this.sourceLocations.length; j < m; j++) { if (this.sourceLocations[j] == c) { out.writeInt(j); continue next; } } } else if (c instanceof ClasspathDirectory) { out.writeByte(BINARY_FOLDER); ClasspathDirectory cd = (ClasspathDirectory) c; out.writeUTF(cd.binaryFolder.getFullPath().toString()); out.writeBoolean(cd.isOutputFolder); writeRestriction(cd.accessRuleSet, out); } else { ClasspathJar jar = (ClasspathJar) c; if (jar.resource == null) { out.writeByte(EXTERNAL_JAR); out.writeUTF(jar.zipFilename); out.writeLong(jar.lastModified()); } else { out.writeByte(INTERNAL_JAR); out.writeUTF(jar.resource.getFullPath().toString()); } writeRestriction(jar.accessRuleSet, out); } } /* * Structural build numbers table * String prereq project name * int last structural build number */ out.writeInt(length = this.structuralBuildTimes.elementSize); if (length > 0) { keyTable = this.structuralBuildTimes.keyTable; valueTable = this.structuralBuildTimes.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; out.writeUTF((String) keyTable[i]); out.writeLong(((Long) valueTable[i]).longValue()); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$ } /* * String[] Interned type locators */ out.writeInt(length = this.references.elementSize); SimpleLookupTable internedTypeLocators = new SimpleLookupTable(length); if (length > 0) { keyTable = this.references.keyTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; String key = (String) keyTable[i]; out.writeUTF(key); internedTypeLocators.put(key, new Integer(internedTypeLocators.elementSize)); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("references table is inconsistent"); //$NON-NLS-1$ } /* * Type locators table * String type name * int interned locator id */ out.writeInt(length = this.typeLocators.elementSize); if (length > 0) { keyTable = this.typeLocators.keyTable; valueTable = this.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; out.writeUTF((String) keyTable[i]); Integer index = (Integer) internedTypeLocators.get(valueTable[i]); out.writeInt(index.intValue()); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$ } /* * char[][] Interned root names * char[][][] Interned qualified names * char[][] Interned simple names */ SimpleLookupTable internedRootNames = new SimpleLookupTable(3); SimpleLookupTable internedQualifiedNames = new SimpleLookupTable(31); SimpleLookupTable internedSimpleNames = new SimpleLookupTable(31); valueTable = this.references.valueTable; for (int i = 0, l = valueTable.length; i < l; i++) { if (valueTable[i] != null) { ReferenceCollection collection = (ReferenceCollection) valueTable[i]; char[][] rNames = collection.rootReferences; for (int j = 0, m = rNames.length; j < m; j++) { char[] rName = rNames[j]; if (!internedRootNames.containsKey(rName)) // remember the names have been interned internedRootNames.put(rName, new Integer(internedRootNames.elementSize)); } char[][][] qNames = collection.qualifiedNameReferences; for (int j = 0, m = qNames.length; j < m; j++) { char[][] qName = qNames[j]; if (!internedQualifiedNames.containsKey(qName)) { // remember the names have been interned internedQualifiedNames.put(qName, new Integer(internedQualifiedNames.elementSize)); for (int k = 0, n = qName.length; k < n; k++) { char[] sName = qName[k]; if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize)); } } } char[][] sNames = collection.simpleNameReferences; for (int j = 0, m = sNames.length; j < m; j++) { char[] sName = sNames[j]; if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize)); } } } char[][] internedArray = new char[internedRootNames.elementSize][]; Object[] rootNames = internedRootNames.keyTable; Object[] positions = internedRootNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedArray[index] = (char[]) rootNames[i]; } } writeNames(internedArray, out); // now write the interned simple names internedArray = new char[internedSimpleNames.elementSize][]; Object[] simpleNames = internedSimpleNames.keyTable; positions = internedSimpleNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedArray[index] = (char[]) simpleNames[i]; } } writeNames(internedArray, out); // now write the interned qualified names as arrays of interned simple names char[][][] internedQArray = new char[internedQualifiedNames.elementSize][][]; Object[] qualifiedNames = internedQualifiedNames.keyTable; positions = internedQualifiedNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedQArray[index] = (char[][]) qualifiedNames[i]; } } out.writeInt(length = internedQArray.length); for (int i = 0; i < length; i++) { char[][] qName = internedQArray[i]; int qLength = qName.length; out.writeInt(qLength); for (int j = 0; j < qLength; j++) { Integer index = (Integer) internedSimpleNames.get(qName[j]); out.writeInt(index.intValue()); } } /* * References table * int interned locator id * ReferenceCollection */ out.writeInt(length = this.references.elementSize); if (length > 0) { keyTable = this.references.keyTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; Integer index = (Integer) internedTypeLocators.get(keyTable[i]); out.writeInt(index.intValue()); ReferenceCollection collection = (ReferenceCollection) valueTable[i]; if (collection instanceof AdditionalTypeCollection) { out.writeByte(1); AdditionalTypeCollection atc = (AdditionalTypeCollection) collection; writeNames(atc.definedTypeNames, out); } else { out.writeByte(2); } char[][][] qNames = collection.qualifiedNameReferences; int qLength = qNames.length; out.writeInt(qLength); for (int j = 0; j < qLength; j++) { index = (Integer) internedQualifiedNames.get(qNames[j]); out.writeInt(index.intValue()); } char[][] sNames = collection.simpleNameReferences; int sLength = sNames.length; out.writeInt(sLength); for (int j = 0; j < sLength; j++) { index = (Integer) internedSimpleNames.get(sNames[j]); out.writeInt(index.intValue()); } char[][] rNames = collection.rootReferences; int rLength = rNames.length; out.writeInt(rLength); for (int j = 0; j < rLength; j++) { index = (Integer) internedRootNames.get(rNames[j]); out.writeInt(index.intValue()); } } } if (JavaBuilder.DEBUG && length != 0) System.out.println("references table is inconsistent"); //$NON-NLS-1$ } }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeName(char[] name, DataOutputStream out) throws IOException { int nLength = name.length; out.writeInt(nLength); for (int j = 0; j < nLength; j++) out.writeChar(name[j]); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeNames(char[][] names, DataOutputStream out) throws IOException { int length = names == null ? 0 : names.length; out.writeInt(length); for (int i = 0; i < length; i++) writeName(names[i], out); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeRestriction(AccessRuleSet accessRuleSet, DataOutputStream out) throws IOException { if (accessRuleSet == null) { out.writeInt(0); } else { AccessRule[] accessRules = accessRuleSet.getAccessRules(); int length = accessRules.length; out.writeInt(length); if (length != 0) { for (int i = 0; i < length; i++) { AccessRule accessRule = accessRules[i]; writeName(accessRule.pattern, out); out.writeInt(accessRule.problemId); } out.writeByte(accessRuleSet.classpathEntryType); out.writeUTF(accessRuleSet.classpathEntryName); } } }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
public static State readState(IProject project, DataInputStream in) throws IOException { return State.read(project, in); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
public static void writeState(Object state, DataOutputStream out) throws IOException { ((State) state).write(out); }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static String serialize(IClasspathEntry[] entries, boolean isSystemLibrary) throws IOException { ByteArrayOutputStream s = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$ XMLWriter xmlWriter = new XMLWriter(writer, null/*use the workspace line delimiter*/, true/*print XML version*/); HashMap library = new HashMap(); library.put(TAG_VERSION, String.valueOf(CURRENT_VERSION)); library.put(TAG_SYSTEMLIBRARY, String.valueOf(isSystemLibrary)); xmlWriter.printTag(TAG_USERLIBRARY, library, true, true, false); for (int i = 0, length = entries.length; i < length; ++i) { ClasspathEntry cpEntry = (ClasspathEntry) entries[i]; HashMap archive = new HashMap(); archive.put(TAG_PATH, cpEntry.getPath().toPortableString()); IPath sourceAttach= cpEntry.getSourceAttachmentPath(); if (sourceAttach != null) archive.put(TAG_SOURCEATTACHMENT, sourceAttach.toPortableString()); IPath sourceAttachRoot= cpEntry.getSourceAttachmentRootPath(); if (sourceAttachRoot != null) archive.put(TAG_SOURCEATTACHMENTROOT, sourceAttachRoot.toPortableString()); boolean hasExtraAttributes = cpEntry.extraAttributes != null && cpEntry.extraAttributes.length != 0; boolean hasRestrictions = cpEntry.getAccessRuleSet() != null; // access rule set is null if no access rules xmlWriter.printTag(TAG_ARCHIVE, archive, true, true, !(hasExtraAttributes || hasRestrictions)); // write extra attributes if necessary if (hasExtraAttributes) { cpEntry.encodeExtraAttributes(xmlWriter, true, true); } // write extra attributes and restriction if necessary if (hasRestrictions) { cpEntry.encodeAccessRules(xmlWriter, true, true); } // write archive end tag if necessary if (hasExtraAttributes || hasRestrictions) { xmlWriter.endTag(TAG_ARCHIVE, true/*insert tab*/, true/*insert new line*/); } } xmlWriter.endTag(TAG_USERLIBRARY, true/*insert tab*/, true/*insert new line*/); writer.flush(); writer.close(); return s.toString("UTF8");//$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static UserLibrary createFromString(Reader reader) throws IOException { Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase(TAG_USERLIBRARY)) { throw new IOException(Messages.file_badFormat); } String version= cpElement.getAttribute(TAG_VERSION); boolean isSystem= Boolean.valueOf(cpElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue(); NodeList list= cpElement.getChildNodes(); int length = list.getLength(); ArrayList res= new ArrayList(length); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equals(TAG_ARCHIVE)) { String pathString = element.getAttribute(TAG_PATH); String sourceAttachString = element.hasAttribute(TAG_SOURCEATTACHMENT) ? element.getAttribute(TAG_SOURCEATTACHMENT) : null; String sourceAttachRootString = element.hasAttribute(TAG_SOURCEATTACHMENTROOT) ? element.getAttribute(TAG_SOURCEATTACHMENTROOT) : null; IPath entryPath = null; IPath sourceAttachPath = null; IPath sourceAttachRootPath = null; if (version.equals(VERSION_ONE)) { entryPath = Path.fromOSString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromOSString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromOSString(sourceAttachRootString); } else { entryPath = Path.fromPortableString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromPortableString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromPortableString(sourceAttachRootString); } NodeList children = element.getElementsByTagName("*"); //$NON-NLS-1$ boolean[] foundChildren = new boolean[children.getLength()]; NodeList attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = ClasspathEntry.decodeExtraAttributes(attributeList); attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = ClasspathEntry.decodeAccessRules(attributeList); IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, sourceAttachPath, sourceAttachRootPath, accessRules, extraAttributes, false/*not exported*/); res.add(entry); } } } IClasspathEntry[] entries= (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]); return new UserLibrary(entries, isSystem); }
// 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/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/Java2HTMLEntityReader.java
protected String computeSubstitution(int c) throws IOException { StringBuffer buf = new StringBuffer(); // Accumulate *s into the buffer until we see something other than *. while (c == '*') { this.bits &= ~BEGIN_LINE; c = nextChar(); buf.append('*'); } if (c == -1) // Snippet must have ended with *s. Just return them. return buf.toString(); if (c == '/' && buf.length() > 0) { /* * Translate a * that precedes a / to &#42; so it isn't * misinterpreted as the end of the Javadoc comment that contains * the code we are formatting. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=109636 */ buf.setLength(buf.length() - 1); buf.append("&#42;/"); //$NON-NLS-1$ } else if (c == '@' && (this.bits & BEGIN_LINE) != 0) { /* * When @ is first on a line, translate it to &#064; so it isn't * misinterpreted as a Javadoc tag. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=197169 */ buf.append("&#064;"); //$NON-NLS-1$ } else { /* * Ordinary processing. If the character needs an entity in HTML, * add the entity, otherwise add the character. */ String entity = (String) fgEntityLookup.get(String.valueOf((char) c)); if (entity != null) buf.append(entity); else buf.append((char) c); } // Update bits for the benefit of the next character. if (c == '\n' || c == '\r') { this.bits |= BEGIN_LINE; } else if (!ScannerHelper.isWhitespace((char) c)) { this.bits &= ~BEGIN_LINE; } return buf.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public String getString() throws IOException { StringBuffer buf= new StringBuffer(); int ch; while ((ch= read()) != -1) { buf.append((char)ch); } return buf.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
protected int nextChar() throws IOException { this.fReadFromBuffer= (this.fBuffer.length() > 0); if (this.fReadFromBuffer) { char ch= this.fBuffer.charAt(this.fIndex++); if (this.fIndex >= this.fBuffer.length()) { this.fBuffer.setLength(0); this.fIndex= 0; } return ch; } else { int ch= this.fCharAfterWhiteSpace; if (ch == -1) { ch= this.fReader.read(); } if (this.fSkipWhiteSpace && ScannerHelper.isWhitespace((char)ch)) { do { ch= this.fReader.read(); } while (ScannerHelper.isWhitespace((char)ch)); if (ch != -1) { this.fCharAfterWhiteSpace= ch; return ' '; } } else { this.fCharAfterWhiteSpace= -1; } return ch; } }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public int read() throws IOException { int c; do { c= nextChar(); while (!this.fReadFromBuffer && c != -1) { String s= computeSubstitution(c); if (s == null) break; if (s.length() > 0) this.fBuffer.insert(0, s); c= nextChar(); } } while (this.fSkipWhiteSpace && this.fWasWhiteSpace && (c == ' ')); this.fWasWhiteSpace= (c == ' ' || c == '\r' || c == '\n'); return c; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public int read(char cbuf[], int off, int len) throws IOException { int end= off + len; for (int i= off; i < end; i++) { int ch= read(); if (ch == -1) { if (i == off) { return -1; } else { return i - off; } } cbuf[i]= (char)ch; } return len; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public boolean ready() throws IOException { return this.fReader.ready(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public void close() throws IOException { this.fReader.close(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public void reset() throws IOException { this.fReader.reset(); this.fWasWhiteSpace= true; this.fCharAfterWhiteSpace= -1; this.fBuffer.setLength(0); this.fIndex= 0; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
protected String computeSubstitution(int c) throws IOException { if (c == '&') return processEntity(); return null; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
private String processEntity() throws IOException { StringBuffer buf= new StringBuffer(); int ch= nextChar(); while (ScannerHelper.isLetterOrDigit((char) ch) || ch == '#') { buf.append((char) ch); ch= nextChar(); } if (ch == ';') return entity2Text(buf.toString()); buf.insert(0, '&'); if (ch != -1) buf.append((char) ch); return buf.toString(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
public final static void initTables() throws java.io.IOException { final String prefix = FILEPREFIX; int i = 0; lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ char[] chars = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ check_table = new short[chars.length]; for (int c = chars.length; c-- > 0;) { check_table[c] = (short) (chars[c] - 32768); } asb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ asr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ nasb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ nasr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ non_terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ term_action = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_prefix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_suffix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_state_set = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_rhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_state = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ in_symb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ rhs = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ term_check = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_la = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ name = readNameTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ rules_compliance = readLongTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ readableName = readReadableNameTable(READABLE_NAMES_FILE_NAME); reverse_index = computeReverseTable(terminal_index, non_terminal_index, name); recovery_templates_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ recovery_templates = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ statements_recovery_filter = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ base_action = lhs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static byte[] readByteTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } return bytes; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static long[] readLongTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if (length % 8 != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into longs long[] longs = new long[length / 8]; int i = 0; int longIndex = 0; while (true) { longs[longIndex++] = (((long) (bytes[i++] & 0xFF)) << 56) + (((long) (bytes[i++] & 0xFF)) << 48) + (((long) (bytes[i++] & 0xFF)) << 40) + (((long) (bytes[i++] & 0xFF)) << 32) + (((long) (bytes[i++] & 0xFF)) << 24) + (((long) (bytes[i++] & 0xFF)) << 16) + (((long) (bytes[i++] & 0xFF)) << 8) + (bytes[i++] & 0xFF); if (i == length) break; } return longs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static String[] readNameTable(String filename) throws java.io.IOException { char[] contents = readTable(filename); char[][] nameAsChar = CharOperation.splitOn('\n', contents); String[] result = new String[nameAsChar.length + 1]; result[0] = null; for (int i = 0; i < nameAsChar.length; i++) { result[i + 1] = new String(nameAsChar[i]); } return result; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static char[] readTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if ((length & 1) != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into chars char[] chars = new char[length / 2]; int i = 0; int charIndex = 0; while (true) { chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); if (i == length) break; } return chars; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file) throws ClassFormatException, IOException { return read(file, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getFileByteContent(file); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, file.getAbsolutePath().toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName) throws ClassFormatException, IOException { return read(stream, fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getInputStreamAsByteArray(stream, -1); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, fileName.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename) throws ClassFormatException, java.io.IOException { return read(zip, filename, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { java.util.zip.ZipEntry ze = zip.getEntry(filename); if (ze == null) return null; byte classFileBytes[] = Util.getZipEntryByteContent(ze, zip); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, filename.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName) throws ClassFormatException, java.io.IOException { return read(fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { return read(new File(fileName), fullyInitialize); }
// in compiler/org/eclipse/jdt/internal/compiler/util/ManifestAnalyzer.java
public boolean analyzeManifestContents(InputStream inputStream) throws IOException { char[] chars = Util.getInputStreamAsCharArray(inputStream, -1, Util.UTF_8); int state = START, substate = 0; StringBuffer currentJarToken = new StringBuffer(); int currentChar; this.classpathSectionsCount = 0; this.calledFilesNames = null; for (int i = 0, max = chars.length; i < max;) { currentChar = chars[i++]; if (currentChar == '\r') { // skip \r, will consider \n later (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=251079 ) if (i < max) { currentChar = chars[i++]; } } switch (state) { case START: if (currentChar == CLASSPATH_HEADER_TOKEN[0]) { state = IN_CLASSPATH_HEADER; substate = 1; } else { state = SKIP_LINE; } break; case IN_CLASSPATH_HEADER: if (currentChar == '\n') { state = START; } else if (currentChar != CLASSPATH_HEADER_TOKEN[substate++]) { state = SKIP_LINE; } else if (substate == CLASSPATH_HEADER_TOKEN.length) { state = PAST_CLASSPATH_HEADER; } break; case PAST_CLASSPATH_HEADER: if (currentChar == ' ') { state = SKIPPING_WHITESPACE; this.classpathSectionsCount++; } else { return false; } break; case SKIPPING_WHITESPACE: if (currentChar == '\n') { state = CONTINUING; } else if (currentChar != ' ') { currentJarToken.append((char) currentChar); state = READING_JAR; } else { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); } break; case CONTINUING: if (currentChar == '\n') { addCurrentTokenJarWhenNecessary(currentJarToken); state = START; } else if (currentChar == ' ') { state = SKIPPING_WHITESPACE; } else if (currentChar == CLASSPATH_HEADER_TOKEN[0]) { addCurrentTokenJarWhenNecessary(currentJarToken); state = IN_CLASSPATH_HEADER; substate = 1; } else if (this.calledFilesNames == null) { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); state = START; } else { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); state = SKIP_LINE; } break; case SKIP_LINE: if (currentChar == '\n') { state = START; } break; case READING_JAR: if (currentChar == '\n') { // appends token below state = CONTINUING; // >>>>>>>>>>> Add a break to not add the jar yet as it can continue on the next line break; } else if (currentChar == ' ') { // appends token below state = SKIPPING_WHITESPACE; } else { currentJarToken.append((char) currentChar); break; } addCurrentTokenJarWhenNecessary(currentJarToken); break; } } switch (state) { case START: return true; case IN_CLASSPATH_HEADER: return true; case PAST_CLASSPATH_HEADER: return false; case SKIPPING_WHITESPACE: // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); return true; case CONTINUING: // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); return true; case SKIP_LINE: if (this.classpathSectionsCount != 0) { if (this.calledFilesNames == null) { return false; } } return true; case READING_JAR: // >>>>>>>>>>>>>>>>>> Add the latest jar read return false; } return true; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static String buildAllDirectoriesInto(String outputPath, String relativeFileName) throws IOException { char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; File f; outputPath = outputPath.replace('/', fileSeparatorChar); // these could be optimized out if we normalized paths once and for // all relativeFileName = relativeFileName.replace('/', fileSeparatorChar); String outputDirPath, fileName; int separatorIndex = relativeFileName.lastIndexOf(fileSeparatorChar); if (separatorIndex == -1) { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath.substring(0, outputPath.length() - 1); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath; fileName = outputPath + fileSeparator + relativeFileName; } } else { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath + relativeFileName.substring(0, separatorIndex); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath + fileSeparator + relativeFileName.substring(0, separatorIndex); fileName = outputPath + fileSeparator + relativeFileName; } } f = new File(outputDirPath); f.mkdirs(); if (f.isDirectory()) { return fileName; } else { // the directory creation failed for some reason - retry using // a slower algorithm so as to refine the diagnostic if (outputPath.endsWith(fileSeparator)) { outputPath = outputPath.substring(0, outputPath.length() - 1); } f = new File(outputPath); boolean checkFileType = false; if (f.exists()) { checkFileType = true; // pre-existed } else { // we have to create that directory if (!f.mkdirs()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValidAll, f.getAbsolutePath())); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } StringBuffer outDir = new StringBuffer(outputPath); outDir.append(fileSeparator); StringTokenizer tokenizer = new StringTokenizer(relativeFileName, fileSeparator); String token = tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { f = new File(outDir.append(token).append(fileSeparator).toString()); checkFileType = false; // reset if (f.exists()) { checkFileType = true; // this is suboptimal, but it catches corner cases // in which a regular file pre-exists } else { // we have to create that directory if (!f.mkdir()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValid, outDir.substring(outputPath.length() + 1, outDir.length() - 1), outputPath)); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } token = tokenizer.nextToken(); } // token contains the last one return outDir.append(token).toString(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException { return getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getFileByteContent(File file) throws IOException { InputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); return getInputStreamAsByteArray(stream, (int) file.length()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] getFileCharContent(File file, String encoding) throws IOException { InputStream stream = null; try { stream = new FileInputStream(file); return getInputStreamAsCharArray(stream, (int) file.length(), encoding); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
private static FileOutputStream getFileOutputStream(boolean generatePackagesStructure, String outputPath, String relativeFileName) throws IOException { if (generatePackagesStructure) { return new FileOutputStream(new File(buildAllDirectoriesInto(outputPath, relativeFileName))); } else { String fileName = null; char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; // First we ensure that the outputPath exists outputPath = outputPath.replace('/', fileSeparatorChar); // To be able to pass the mkdirs() method we need to remove the extra file separator at the end of the outDir name int indexOfPackageSeparator = relativeFileName.lastIndexOf(fileSeparatorChar); if (indexOfPackageSeparator == -1) { if (outputPath.endsWith(fileSeparator)) { fileName = outputPath + relativeFileName; } else { fileName = outputPath + fileSeparator + relativeFileName; } } else { int length = relativeFileName.length(); if (outputPath.endsWith(fileSeparator)) { fileName = outputPath + relativeFileName.substring(indexOfPackageSeparator + 1, length); } else { fileName = outputPath + fileSeparator + relativeFileName.substring(indexOfPackageSeparator + 1, length); } } return new FileOutputStream(new File(fileName)); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException { byte[] contents; if (length == -1) { contents = new byte[0]; int contentsLength = 0; int amountRead = -1; do { int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (contentsLength + amountRequested > contents.length) { System.arraycopy( contents, 0, contents = new byte[contentsLength + amountRequested], 0, contentsLength); } // read as many bytes as possible amountRead = stream.read(contents, contentsLength, amountRequested); if (amountRead > 0) { // remember length of contents contentsLength += amountRead; } } while (amountRead != -1); // resize contents if necessary if (contentsLength < contents.length) { System.arraycopy( contents, 0, contents = new byte[contentsLength], 0, contentsLength); } } else { contents = new byte[length]; int len = 0; int readSize = 0; while ((readSize != -1) && (len != length)) { // See PR 1FMS89U // We record first the read size. In this case len is the actual read size. len += readSize; readSize = stream.read(contents, len, length - len); } } return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) throws IOException { BufferedReader reader = null; try { reader = encoding == null ? new BufferedReader(new InputStreamReader(stream)) : new BufferedReader(new InputStreamReader(stream, encoding)); } catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); } char[] contents; int totalRead = 0; if (length == -1) { contents = CharOperation.NO_CHAR; } else { // length is a good guess when the encoding produces less or the same amount of characters than the file length contents = new char[length]; // best guess } while (true) { int amountRequested; if (totalRead < length) { // until known length is met, reuse same array sized eagerly amountRequested = length - totalRead; } else { // reading beyond known length int current = reader.read(); if (current < 0) break; amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (totalRead + 1 + amountRequested > contents.length) System.arraycopy(contents, 0, contents = new char[totalRead + 1 + amountRequested], 0, totalRead); // add current character contents[totalRead++] = (char) current; // coming from totalRead==length } // read as many chars as possible int amountRead = reader.read(contents, totalRead, amountRequested); if (amountRead < 0) break; totalRead += amountRead; } // Do not keep first character for UTF-8 BOM encoding int start = 0; if (totalRead > 0 && UTF_8.equals(encoding)) { if (contents[0] == 0xFEFF) { // if BOM char then skip totalRead--; start = 1; } } // resize contents if necessary if (totalRead < contents.length) System.arraycopy(contents, start, contents = new char[totalRead], 0, totalRead); return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { InputStream stream = null; try { InputStream inputStream = zip.getInputStream(ze); if (inputStream == null) throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ stream = new BufferedInputStream(inputStream); return getInputStreamAsByteArray(stream, (int) ze.getSize()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static void writeToDisk(boolean generatePackagesStructure, String outputPath, String relativeFileName, ClassFile classFile) throws IOException { FileOutputStream file = getFileOutputStream(generatePackagesStructure, outputPath, relativeFileName); /* use java.nio to write if (true) { FileChannel ch = file.getChannel(); try { ByteBuffer buffer = ByteBuffer.allocate(classFile.headerOffset + classFile.contentsOffset); buffer.put(classFile.header, 0, classFile.headerOffset); buffer.put(classFile.contents, 0, classFile.contentsOffset); buffer.flip(); while (true) { if (ch.write(buffer) == 0) break; } } finally { ch.close(); } return; } */ BufferedOutputStream output = new BufferedOutputStream(file, DEFAULT_WRITING_SIZE); // BufferedOutputStream output = new BufferedOutputStream(file); try { // if no IOException occured, output cannot be null output.write(classFile.header, 0, classFile.headerOffset); output.write(classFile.contents, 0, classFile.contentsOffset); output.flush(); } catch(IOException e) { throw e; } finally { output.close(); } }
(Lib) IllegalStateException 25
              
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
public boolean visit(BinaryExpression binaryExpression, BlockScope scope) { switch((binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) { case OperatorIds.AND : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameAND, scope); case OperatorIds.DIVIDE : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameDIVIDE, scope); case OperatorIds.GREATER : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER, scope); case OperatorIds.GREATER_EQUAL : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER_EQUAL, scope); case OperatorIds.LEFT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLEFT_SHIFT, scope); case OperatorIds.LESS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS, scope); case OperatorIds.LESS_EQUAL : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS_EQUAL, scope); case OperatorIds.MINUS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMINUS, scope); case OperatorIds.MULTIPLY : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMULTIPLY, scope); case OperatorIds.OR : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameOR, scope); case OperatorIds.PLUS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNamePLUS, scope); case OperatorIds.REMAINDER : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameREMAINDER, scope); case OperatorIds.RIGHT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameRIGHT_SHIFT, scope); case OperatorIds.UNSIGNED_RIGHT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT, scope); case OperatorIds.XOR : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameXOR, scope); default: throw new IllegalStateException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
Object decodeDefaultValue() { Object value = null; // u1 tag; int tag = u1At(this.readOffset); this.readOffset++; int constValueOffset = -1; switch (tag) { case 'Z': // boolean constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = BooleanConstant.fromValue(i4At(constValueOffset + 1) == 1); this.readOffset += 2; break; case 'I': // integer constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = IntConstant.fromValue(i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'C': // char constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = CharConstant.fromValue((char) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'B': // byte constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = ByteConstant.fromValue((byte) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'S': // short constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = ShortConstant.fromValue((short) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'D': // double constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = DoubleConstant.fromValue(doubleAt(constValueOffset + 1)); this.readOffset += 2; break; case 'F': // float constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = FloatConstant.fromValue(floatAt(constValueOffset + 1)); this.readOffset += 2; break; case 'J': // long constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = LongConstant.fromValue(i8At(constValueOffset + 1)); this.readOffset += 2; break; case 's': // String constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = StringConstant.fromValue(String.valueOf(utf8At(constValueOffset + 3, u2At(constValueOffset + 1)))); this.readOffset += 2; break; case 'e': constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] typeName = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); this.readOffset += 2; constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] constName = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); this.readOffset += 2; value = new EnumConstantSignature(typeName, constName); break; case 'c': constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] className = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); value = new ClassSignature(className); this.readOffset += 2; break; case '@': value = new AnnotationInfo(this.reference, this.constantPoolOffsets, this.readOffset + this.structOffset, false, true); this.readOffset += ((AnnotationInfo) value).readOffset; break; case '[': int numberOfValues = u2At(this.readOffset); this.readOffset += 2; if (numberOfValues == 0) { value = EmptyValueArray; } else { Object[] arrayElements = new Object[numberOfValues]; value = arrayElements; for (int i = 0; i < numberOfValues; i++) arrayElements[i] = decodeDefaultValue(); } break; default: throw new IllegalStateException("Unrecognized tag " + (char) tag); //$NON-NLS-1$ } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int readRetentionPolicy(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'e': int utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] typeName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); currentOffset += 2; if (typeName.length == 38 && CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_RETENTIONPOLICY)) { utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] constName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); this.standardAnnotationTagBits |= Annotation.getRetentionPolicy(constName); } currentOffset += 2; break; case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; for (int i = 0; i < numberOfValues; i++) currentOffset = scanElementValue(currentOffset); break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int readTargetValue(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'e': int utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] typeName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); currentOffset += 2; if (typeName.length == 34 && CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_ELEMENTTYPE)) { utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] constName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); this.standardAnnotationTagBits |= Annotation.getTargetElementType(constName); } currentOffset += 2; break; case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; if (numberOfValues == 0) { this.standardAnnotationTagBits |= TagBits.AnnotationTarget; } else { for (int i = 0; i < numberOfValues; i++) currentOffset = readTargetValue(currentOffset); } break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int scanElementValue(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case 'e': currentOffset += 4; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; for (int i = 0; i < numberOfValues; i++) currentOffset = scanElementValue(currentOffset); break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static void collectRunningVMBootclasspath(List bootclasspaths) { /* no bootclasspath specified * we can try to retrieve the default librairies of the VM used to run * the batch compiler */ String javaversion = System.getProperty("java.version");//$NON-NLS-1$ if (javaversion != null && javaversion.equalsIgnoreCase("1.1.8")) { //$NON-NLS-1$ throw new IllegalStateException(); } /* * Handle >= JDK 1.2.2 settings: retrieve the bootclasspath */ // check bootclasspath properties for Sun, JRockit and Harmony VMs String bootclasspathProperty = System.getProperty("sun.boot.class.path"); //$NON-NLS-1$ if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) { // IBM J9 VMs bootclasspathProperty = System.getProperty("vm.boot.class.path"); //$NON-NLS-1$ if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) { // Harmony using IBM VME bootclasspathProperty = System.getProperty("org.apache.harmony.boot.class.path"); //$NON-NLS-1$ } } if ((bootclasspathProperty != null) && (bootclasspathProperty.length() != 0)) { StringTokenizer tokenizer = new StringTokenizer(bootclasspathProperty, File.pathSeparator); String token; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); FileSystem.Classpath currentClasspath = FileSystem.getClasspath(token, null, null); if (currentClasspath != null) { bootclasspaths.add(currentClasspath); } } } else { // try to get all jars inside the lib folder of the java home final File javaHome = getJavaHome(); if (javaHome != null) { File[] directoriesToCheck = null; if (System.getProperty("os.name").startsWith("Mac")) {//$NON-NLS-1$//$NON-NLS-2$ directoriesToCheck = new File[] { new File(javaHome, "../Classes"), //$NON-NLS-1$ }; } else { // fall back to try to retrieve them out of the lib directory directoriesToCheck = new File[] { new File(javaHome, "lib") //$NON-NLS-1$ }; } File[][] systemLibrariesJars = Main.getLibrariesFiles(directoriesToCheck); if (systemLibrariesJars != null) { for (int i = 0, max = systemLibrariesJars.length; i < max; i++) { File[] current = systemLibrariesJars[i]; if (current != null) { for (int j = 0, max2 = current.length; j < max2; j++) { FileSystem.Classpath classpath = FileSystem.getClasspath(current[j].getAbsolutePath(), null, false, null, null); if (classpath != null) { bootclasspaths.add(classpath); } } } } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
static Object convertMemberValue(Object binaryValue, LookupEnvironment env, char[][][] missingTypeNames) { if (binaryValue == null) return null; if (binaryValue instanceof Constant) return binaryValue; if (binaryValue instanceof ClassSignature) return env.getTypeFromSignature(((ClassSignature) binaryValue).getTypeName(), 0, -1, false, null, missingTypeNames); if (binaryValue instanceof IBinaryAnnotation) return createAnnotation((IBinaryAnnotation) binaryValue, env, missingTypeNames); if (binaryValue instanceof EnumConstantSignature) { EnumConstantSignature ref = (EnumConstantSignature) binaryValue; ReferenceBinding enumType = (ReferenceBinding) env.getTypeFromSignature(ref.getTypeName(), 0, -1, false, null, missingTypeNames); enumType = (ReferenceBinding) resolveType(enumType, env, false /* no raw conversion */); return enumType.getField(ref.getEnumConstantName(), false); } if (binaryValue instanceof Object[]) { Object[] objects = (Object[]) binaryValue; int length = objects.length; if (length == 0) return objects; Object[] values = new Object[length]; for (int i = 0; i < length; i++) values[i] = convertMemberValue(objects[i], env, missingTypeNames); return values; } // should never reach here. throw new IllegalStateException(); }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/AnnotationHolder.java
Object getDefaultValue() { if (this.defaultValue instanceof UnresolvedReferenceBinding) { if (this.env == null) throw new IllegalStateException(); this.defaultValue = ((UnresolvedReferenceBinding) this.defaultValue).resolve(this.env, false); } return this.defaultValue; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static CompilationUnitDeclaration parse( org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit, NodeSearcher nodeSearcher, Map settings, int flags) { if (sourceUnit == null) { throw new IllegalStateException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); boolean statementsRecovery = (flags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0; compilerOptions.performMethodsFullRecovery = statementsRecovery; compilerOptions.performStatementsRecovery = statementsRecovery; compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0; Parser parser = new CommentRecorderParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()), false); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult); if (compilationUnitDeclaration.ignoreMethodBodies) { compilationUnitDeclaration.ignoreFurtherInvestigation = true; // if initial diet parse did not work, no need to dig into method bodies. return compilationUnitDeclaration; } if (nodeSearcher != null) { char[] source = parser.scanner.getSource(); int searchPosition = nodeSearcher.position; if (searchPosition < 0 || searchPosition > source.length) { // the position is out of range. There is no need to search for a node. return compilationUnitDeclaration; } compilationUnitDeclaration.traverse(nodeSearcher, compilationUnitDeclaration.scope); org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodeSearcher.found; if (node == null) { return compilationUnitDeclaration; } org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType; if (node instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration)node).parseStatements(parser, compilationUnitDeclaration); } else if (enclosingTypeDeclaration != null) { if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) { ((org.eclipse.jdt.internal.compiler.ast.Initializer) node).parseStatements(parser, enclosingTypeDeclaration, compilationUnitDeclaration); } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) { ((org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)node).parseMethods(parser, compilationUnitDeclaration); } } } else { //fill the methods bodies in order for the code to be generated //real parse of the method.... org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types; if (types != null) { for (int j = 0, typeLength = types.length; j < typeLength; j++) { types[j].parseMethods(parser, compilationUnitDeclaration); } } } return compilationUnitDeclaration; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static IBinding[] resolve( final IJavaElement[] elements, int apiLevel, Map compilerOptions, IJavaProject javaProject, WorkingCopyOwner owner, int flags, IProgressMonitor monitor) { final int length = elements.length; final HashMap sourceElementPositions = new HashMap(); // a map from ICompilationUnit to int[] (positions in elements) int cuNumber = 0; final HashtableOfObjectToInt binaryElementPositions = new HashtableOfObjectToInt(); // a map from String (binding key) to int (position in elements) for (int i = 0; i < length; i++) { IJavaElement element = elements[i]; if (!(element instanceof SourceRefElement)) throw new IllegalStateException(element + " is not part of a compilation unit or class file"); //$NON-NLS-1$ Object cu = element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { // source member IntArrayList intList = (IntArrayList) sourceElementPositions.get(cu); if (intList == null) { sourceElementPositions.put(cu, intList = new IntArrayList()); cuNumber++; } intList.add(i); } else { // binary member try { String key = ((BinaryMember) element).getKey(true/*open to get resolved info*/); binaryElementPositions.put(key, i); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } } } ICompilationUnit[] cus = new ICompilationUnit[cuNumber]; sourceElementPositions.keySet().toArray(cus); int bindingKeyNumber = binaryElementPositions.size(); String[] bindingKeys = new String[bindingKeyNumber]; binaryElementPositions.keysToArray(bindingKeys); class Requestor extends ASTRequestor { IBinding[] bindings = new IBinding[length]; public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } } public void acceptBinding(String bindingKey, IBinding binding) { int index = binaryElementPositions.get(bindingKey); this.bindings[index] = binding; } } Requestor requestor = new Requestor(); resolve(cus, bindingKeys, requestor, apiLevel, compilerOptions, javaProject, owner, flags, monitor); return requestor.bindings; }
// in dom/org/eclipse/jdt/core/dom/AST.java
TextEdit rewrite(IDocument document, Map options) { if (document == null) { throw new IllegalArgumentException(); } if (this.rewriter == null) { throw new IllegalStateException("Modifications record is not enabled"); //$NON-NLS-1$ } return this.rewriter.rewriteAST(document, options); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private List getClasspath() throws IllegalStateException { Main main = new Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*systemExit*/, null/*options*/, null/*progress*/); ArrayList allClasspaths = new ArrayList(); try { if ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0) { org.eclipse.jdt.internal.compiler.util.Util.collectRunningVMBootclasspath(allClasspaths); } if (this.sourcepaths != null) { for (int i = 0, max = this.sourcepaths.length; i < max; i++) { String encoding = this.sourcepathsEncodings == null ? null : this.sourcepathsEncodings[i]; main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.sourcepaths[i], encoding, true, false); } } if (this.classpaths != null) { for (int i = 0, max = this.classpaths.length; i < max; i++) { main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.classpaths[i], null, false, false); } } ArrayList pendingErrors = main.pendingErrors; if (pendingErrors != null && pendingErrors.size() != 0) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } } catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } return allClasspaths; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public ASTNode createAST(IProgressMonitor monitor) { ASTNode result = null; if (monitor != null) monitor.beginTask("", 1); //$NON-NLS-1$ try { if (this.rawSource == null && this.typeRoot == null) { throw new IllegalStateException("source not specified"); //$NON-NLS-1$ } result = internalCreateAST(monitor); } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); if (monitor != null) monitor.done(); } return result; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void createASTs(ICompilationUnit[] compilationUnits, String[] bindingKeys, ASTRequestor requestor, IProgressMonitor monitor) { try { int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) { if (this.project == null) throw new IllegalStateException("project not specified"); //$NON-NLS-1$ if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } CompilationUnitResolver.resolve(compilationUnits, bindingKeys, requestor, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner, flags, monitor); } else { CompilationUnitResolver.parse(compilationUnits, requestor, this.apiLevel, this.compilerOptions, flags, monitor); } } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void createASTs(String[] sourceFilePaths, String[] encodings, String[] bindingKeys, FileASTRequestor requestor, IProgressMonitor monitor) { try { int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) { if (this.classpaths == null && this.sourcepaths == null && ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) == 0)) { throw new IllegalStateException("no environment is specified"); //$NON-NLS-1$ } if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } CompilationUnitResolver.resolve(sourceFilePaths, encodings, bindingKeys, requestor, this.apiLevel, this.compilerOptions, getClasspath(), flags, monitor); } else { CompilationUnitResolver.parse(sourceFilePaths, encodings, requestor, this.apiLevel, this.compilerOptions, flags, monitor); } } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public IBinding[] createBindings(IJavaElement[] elements, IProgressMonitor monitor) { try { if (this.project == null) throw new IllegalStateException("project or classpath not specified"); //$NON-NLS-1$ int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } return CompilationUnitResolver.resolve(elements, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner, flags, monitor); } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private ASTNode internalCreateAST(IProgressMonitor monitor) { boolean needToResolveBindings = (this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0; switch(this.astKind) { case K_CLASS_BODY_DECLARATIONS : case K_EXPRESSION : case K_STATEMENTS : if (this.rawSource == null) { if (this.typeRoot != null) { // get the source from the type root if (this.typeRoot instanceof ICompilationUnit) { org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.typeRoot; this.rawSource = sourceUnit.getContents(); } else if (this.typeRoot instanceof IClassFile) { try { String sourceString = this.typeRoot.getSource(); if (sourceString != null) { this.rawSource = sourceString.toCharArray(); } } catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); } } } } if (this.rawSource != null) { if (this.sourceOffset + this.sourceLength > this.rawSource.length) { throw new IllegalStateException(); } return internalCreateASTForKind(); } break; case K_COMPILATION_UNIT : CompilationUnitDeclaration compilationUnitDeclaration = null; try { NodeSearcher searcher = null; org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = null; WorkingCopyOwner wcOwner = this.workingCopyOwner; if (this.typeRoot instanceof ICompilationUnit) { /* * this.compilationUnitSource is an instance of org.eclipse.jdt.internal.core.CompilationUnit that implements * both org.eclipse.jdt.core.ICompilationUnit and org.eclipse.jdt.internal.compiler.env.ICompilationUnit */ sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.typeRoot; /* * use a BasicCompilation that caches the source instead of using the compilationUnitSource directly * (if it is a working copy, the source can change between the parse and the AST convertion) * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75632) */ sourceUnit = new BasicCompilationUnit(sourceUnit.getContents(), sourceUnit.getPackageName(), new String(sourceUnit.getFileName()), this.project); wcOwner = ((ICompilationUnit) this.typeRoot).getOwner(); } else if (this.typeRoot instanceof IClassFile) { try { String sourceString = this.typeRoot.getSource(); if (sourceString == null) { throw new IllegalStateException(); } PackageFragment packageFragment = (PackageFragment) this.typeRoot.getParent(); BinaryType type = (BinaryType) this.typeRoot.findPrimaryType(); IBinaryType binaryType = (IBinaryType) type.getElementInfo(); // file name is used to recreate the Java element, so it has to be the toplevel .class file name char[] fileName = binaryType.getFileName(); int firstDollar = CharOperation.indexOf('$', fileName); if (firstDollar != -1) { char[] suffix = SuffixConstants.SUFFIX_class; int suffixLength = suffix.length; char[] newFileName = new char[firstDollar + suffixLength]; System.arraycopy(fileName, 0, newFileName, 0, firstDollar); System.arraycopy(suffix, 0, newFileName, firstDollar, suffixLength); fileName = newFileName; } sourceUnit = new BasicCompilationUnit(sourceString.toCharArray(), Util.toCharArrays(packageFragment.names), new String(fileName), this.project); } catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); } } else if (this.rawSource != null) { needToResolveBindings = ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) && this.unitName != null && (this.project != null || this.classpaths != null || this.sourcepaths != null || ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0)) && this.compilerOptions != null; sourceUnit = new BasicCompilationUnit(this.rawSource, null, this.unitName == null ? "" : this.unitName, this.project); //$NON-NLS-1$ } else { throw new IllegalStateException(); } if ((this.bits & CompilationUnitResolver.PARTIAL) != 0) { searcher = new NodeSearcher(this.focalPointPosition); } int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if (searcher == null && ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0)) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if (needToResolveBindings) { if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } try { // parse and resolve compilationUnitDeclaration = CompilationUnitResolver.resolve( sourceUnit, this.project, getClasspath(), searcher, this.compilerOptions, this.workingCopyOwner, flags, monitor); } catch (JavaModelException e) { flags &= ~ICompilationUnit.ENABLE_BINDINGS_RECOVERY; compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; } } else { compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; } CompilationUnit result = CompilationUnitResolver.convert( compilationUnitDeclaration, sourceUnit.getContents(), this.apiLevel, this.compilerOptions, needToResolveBindings, wcOwner, needToResolveBindings ? new DefaultBindingResolver.BindingTables() : null, flags, monitor, this.project != null); result.setTypeRoot(this.typeRoot); return result; } finally { if (compilationUnitDeclaration != null && ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0)) { compilationUnitDeclaration.cleanUp(); } } } throw new IllegalStateException(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private ASTNode internalCreateASTForKind() { final ASTConverter converter = new ASTConverter(this.compilerOptions, false, null); converter.compilationUnitSource = this.rawSource; converter.compilationUnitSourceLength = this.rawSource.length; converter.scanner.setSource(this.rawSource); AST ast = AST.newAST(this.apiLevel); ast.setDefaultNodeFlag(ASTNode.ORIGINAL); ast.setBindingResolver(new BindingResolver()); if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { ast.setFlag(ICompilationUnit.ENABLE_STATEMENTS_RECOVERY); } converter.setAST(ast); CodeSnippetParsingUtil codeSnippetParsingUtil = new CodeSnippetParsingUtil((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0); CompilationUnit compilationUnit = ast.newCompilationUnit(); if (this.sourceLength == -1) { this.sourceLength = this.rawSource.length; } switch(this.astKind) { case K_STATEMENTS : ConstructorDeclaration constructorDeclaration = codeSnippetParsingUtil.parseStatements( this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0); RecoveryScannerData data = constructorDeclaration.compilationResult.recoveryScannerData; if(data != null) { Scanner scanner = converter.scanner; converter.scanner = new RecoveryScanner(scanner, data.removeUnused()); converter.docParser.scanner = converter.scanner; converter.scanner.setSource(scanner.source); compilationUnit.setStatementsRecoveryData(data); } RecordedParsingInformation recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; int[][] comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); Block block = ast.newBlock(); block.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength); org.eclipse.jdt.internal.compiler.ast.Statement[] statements = constructorDeclaration.statements; if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) { if (statements[i] instanceof org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { converter.checkAndAddMultipleLocalDeclaration(statements, i, block.statements()); } else { Statement statement = converter.convert(statements[i]); if (statement != null) { block.statements().add(statement); } } } } rootNodeToCompilationUnit(ast, compilationUnit, block, recordedParsingInformation, data); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return block; case K_EXPRESSION : org.eclipse.jdt.internal.compiler.ast.Expression expression = codeSnippetParsingUtil.parseExpression(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true); recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); if (expression != null) { Expression expression2 = converter.convert(expression); rootNodeToCompilationUnit(expression2.getAST(), compilationUnit, expression2, codeSnippetParsingUtil.recordedParsingInformation, null); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return expression2; } else { CategorizedProblem[] problems = recordedParsingInformation.problems; if (problems != null) { compilationUnit.setProblems(problems); } ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return compilationUnit; } case K_CLASS_BODY_DECLARATIONS : final org.eclipse.jdt.internal.compiler.ast.ASTNode[] nodes = codeSnippetParsingUtil.parseClassBodyDeclarations( this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0); recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); if (nodes != null) { // source has no syntax error or the statement recovery is enabled TypeDeclaration typeDeclaration = converter.convert(nodes); typeDeclaration.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength); rootNodeToCompilationUnit(typeDeclaration.getAST(), compilationUnit, typeDeclaration, codeSnippetParsingUtil.recordedParsingInformation, null); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return typeDeclaration; } else { // source has syntax error and the statement recovery is disabled CategorizedProblem[] problems = recordedParsingInformation.problems; if (problems != null) { compilationUnit.setProblems(problems); } ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return compilationUnit; } } throw new IllegalStateException(); }
3
              
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
1
              
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private List getClasspath() throws IllegalStateException { Main main = new Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*systemExit*/, null/*options*/, null/*progress*/); ArrayList allClasspaths = new ArrayList(); try { if ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0) { org.eclipse.jdt.internal.compiler.util.Util.collectRunningVMBootclasspath(allClasspaths); } if (this.sourcepaths != null) { for (int i = 0, max = this.sourcepaths.length; i < max; i++) { String encoding = this.sourcepathsEncodings == null ? null : this.sourcepathsEncodings[i]; main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.sourcepaths[i], encoding, true, false); } } if (this.classpaths != null) { for (int i = 0, max = this.classpaths.length; i < max; i++) { main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.classpaths[i], null, false, false); } } ArrayList pendingErrors = main.pendingErrors; if (pendingErrors != null && pendingErrors.size() != 0) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } } catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } return allClasspaths; }
(Domain) AbortMethod 17
              
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; if (this.constant != Constant.NotAConstant) { if (valueRequired) { codeStream.generateConstant(this.constant, this.implicitConversion); } } else { switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // reading a field if (!valueRequired) break; FieldBinding codegenField = ((FieldBinding) this.binding).original(); Constant fieldConstant = codegenField.constant(); if (fieldConstant == Constant.NotAConstant) { // directly use inlined value for constant fields if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); if (codegenField.isStatic()) { codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { if ((this.bits & DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & DepthMASK) >> DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } } else { // managing private access if (!codegenField.isStatic()) { if ((this.bits & DepthMASK) != 0) { // internal error, per construction we should have found it // not yet supported currentScope.problemReporter().needImplementation(this); } else { generateReceiver(codeStream); } } else { codeStream.aconst_null(); } codeStream.generateEmulatedReadAccessForField(codegenField); } if (this.genericCast != null) codeStream.checkcast(this.genericCast); codeStream.generateImplicitConversion(this.implicitConversion); } else { // directly use the inlined value codeStream.generateConstant(fieldConstant, this.implicitConversion); } break; case Binding.LOCAL : // reading a local LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (!valueRequired) break; // outer local? if ((this.bits & DepthMASK) != 0) { // outer local can be reached either through a synthetic arg or a synthetic field VariableBinding[] path = currentScope.getEmulationPath(localBinding); codeStream.generateOuterAccess(path, this, localBinding, currentScope); } else { // regular local variable read codeStream.load(localBinding); } codeStream.generateImplicitConversion(this.implicitConversion); break; } } codeStream.recordPositionsFrom(pc, this.sourceStart); }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.isStatic()) { if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { // used to store the value codeStream.generateEmulationForField(codegenField); codeStream.aconst_null(); // used to retrieve the actual value codeStream.aconst_null(); codeStream.generateEmulatedReadAccessForField(codegenField); } } else { if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { if ((this.bits & DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & DepthMASK) >> DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } codeStream.dup(); TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { if ((this.bits & DepthMASK) != 0) { // internal error, per construction we should have found it // not yet supported currentScope.problemReporter().needImplementation(this); } // used to store the value codeStream.generateEmulationForField(codegenField); generateReceiver(codeStream); // used to retrieve the actual value codeStream.dup(); codeStream.generateEmulatedReadAccessForField(codegenField); } } break; case Binding.LOCAL : // assigning to a local variable (cannot assign to outer local) LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // using incr bytecode if possible Constant assignConstant; switch (localBinding.type.id) { case T_JavaLangString : codeStream.generateStringConcatenationAppend(currentScope, this, expression); if (valueRequired) { codeStream.dup(); } codeStream.store(localBinding, false); return; case T_int : assignConstant = expression.constant; if (localBinding.resolvedPosition == -1) { if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } if ((assignConstant != Constant.NotAConstant) && (assignConstant.typeID() != TypeIds.T_float) // only for integral types && (assignConstant.typeID() != TypeIds.T_double)) { // TODO (philippe) is this test needed ? switch (operator) { case PLUS : int increment = assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; case MINUS : increment = -assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; } } //$FALL-THROUGH$ default : if (localBinding.resolvedPosition == -1) { assignConstant = expression.constant; if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } codeStream.load(localBinding); } } // perform the actual compound operation int operationTypeID; switch(operationTypeID = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4) { case T_JavaLangString : case T_JavaLangObject : case T_undefined : codeStream.generateStringConcatenationAppend(currentScope, null, expression); break; default : // promote the array reference to the suitable operation type codeStream.generateImplicitConversion(this.implicitConversion); // generate the increment value (will by itself be promoted to the operation value) if (expression == IntLiteral.One){ // prefix operation codeStream.generateConstant(expression.constant, this.implicitConversion); } else { expression.generateCode(currentScope, codeStream, true); } // perform the operation codeStream.sendOperator(operator, operationTypeID); // cast the value back to the array reference type codeStream.generateImplicitConversion(assignmentImplicitConversion); } // store the result back into the variable switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { fieldStore(currentScope, codeStream, codegenField, writeAccessor, this.actualReceiverType, this.delegateThis == null /* implicit this */, valueRequired); } else { // current stack is: // field receiver value if (valueRequired) { switch (codegenField.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2_x2(); break; default: codeStream.dup_x2(); break; } } // current stack is: // value field receiver value codeStream.generateEmulatedWriteAccessForField(codegenField); } return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (valueRequired) { switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.store(localBinding, false); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/StackMapFrameCodeStream.java
public void generateOuterAccess(Object[] mappingSequence, ASTNode invocationSite, Binding target, Scope scope) { int currentPosition = this.position; super.generateOuterAccess(mappingSequence, invocationSite, target, scope); if (currentPosition == this.position) { // no code has been generate during outer access => no enclosing instance is available throw new AbortMethod(scope.referenceCompilationUnit().compilationResult, null); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/CodeStream.java
protected void writePosition(BranchLabel label) { int offset = label.position - this.position + 1; if (Math.abs(offset) > 0x7FFF && !this.wideMode) { throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE, null); } this.writeSignedShort(offset); int[] forwardRefs = label.forwardReferences(); for (int i = 0, max = label.forwardReferenceCount(); i < max; i++) { this.writePosition(label, forwardRefs[i]); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/CodeStream.java
protected void writePosition(BranchLabel label, int forwardReference) { final int offset = label.position - forwardReference + 1; if (Math.abs(offset) > 0x7FFF && !this.wideMode) { throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE, null); } if (this.wideMode) { if ((label.tagBits & BranchLabel.WIDE) != 0) { this.writeSignedWord(forwardReference, offset); } else { this.writeSignedShort(forwardReference, offset); } } else { this.writeSignedShort(forwardReference, offset); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
private void internalGenerateCode(ClassScope classScope, ClassFile classFile) { classFile.generateMethodInfoHeader(this.binding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttributes(this.binding); if ((!this.binding.isNative()) && (!this.binding.isAbstract())) { TypeDeclaration declaringType = classScope.referenceContext; int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); // initialize local positions - including initializer scope. ReferenceBinding declaringClass = this.binding.declaringClass; int enumOffset = declaringClass.isEnum() ? 2 : 0; // String name, int ordinal int argSlotSize = 1 + enumOffset; // this==aload0 if (declaringClass.isNestedType()){ this.scope.extraSyntheticArguments = declaringClass.syntheticOuterLocalVariables(); this.scope.computeLocalVariablePositions(// consider synthetic arguments if any declaringClass.getEnclosingInstancesSlotSize() + 1 + enumOffset, codeStream); argSlotSize += declaringClass.getEnclosingInstancesSlotSize(); argSlotSize += declaringClass.getOuterLocalVariablesSlotSize(); } else { this.scope.computeLocalVariablePositions(1 + enumOffset, codeStream); } if (this.arguments != null) { for (int i = 0, max = this.arguments.length; i < max; i++) { // arguments initialization for local variable debug attributes LocalVariableBinding argBinding; codeStream.addVisibleLocalVariable(argBinding = this.arguments[i].binding); argBinding.recordInitializationStartPC(0); switch(argBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : argSlotSize += 2; break; default : argSlotSize++; break; } } } MethodScope initializerScope = declaringType.initializerScope; initializerScope.computeLocalVariablePositions(argSlotSize, codeStream); // offset by the argument size (since not linked to method scope) boolean needFieldInitializations = this.constructorCall == null || this.constructorCall.accessMode != ExplicitConstructorCall.This; // post 1.4 target level, synthetic initializations occur prior to explicit constructor call boolean preInitSyntheticFields = this.scope.compilerOptions().targetJDK >= ClassFileConstants.JDK1_4; if (needFieldInitializations && preInitSyntheticFields){ generateSyntheticFieldInitializationsIfNecessary(this.scope, codeStream, declaringClass); codeStream.recordPositionsFrom(0, this.bodyStart); } // generate constructor call if (this.constructorCall != null) { this.constructorCall.generateCode(this.scope, codeStream); } // generate field initialization - only if not invoking another constructor call of the same class if (needFieldInitializations) { if (!preInitSyntheticFields){ generateSyntheticFieldInitializationsIfNecessary(this.scope, codeStream, declaringClass); } // generate user field initialization if (declaringType.fields != null) { for (int i = 0, max = declaringType.fields.length; i < max; i++) { FieldDeclaration fieldDecl; if (!(fieldDecl = declaringType.fields[i]).isStatic()) { fieldDecl.generateCode(initializerScope, codeStream); } } } } // generate statements if (this.statements != null) { for (int i = 0, max = this.statements.length; i < max; i++) { this.statements[i].generateCode(this.scope, codeStream); } } // if a problem got reported during code gen, then trigger problem method creation if (this.ignoreFurtherInvestigation) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } if ((this.bits & ASTNode.NeedFreeReturn) != 0) { codeStream.return_(); } // local variable attributes codeStream.exitUserScope(this.scope); codeStream.recordPositionsFrom(0, this.bodyEnd); try { classFile.completeCodeAttribute(codeAttributeOffset); } catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } attributeNumber++; if ((codeStream instanceof StackMapFrameCodeStream) && needFieldInitializations && declaringType.fields != null) { ((StackMapFrameCodeStream) codeStream).resetSecretLocals(); } } classFile.completeMethodInfo(this.binding, methodAttributeOffset, attributeNumber); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void generateCode(ClassFile classFile) { classFile.generateMethodInfoHeader(this.binding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttributes(this.binding); if ((!this.binding.isNative()) && (!this.binding.isAbstract())) { int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); // initialize local positions this.scope.computeLocalVariablePositions(this.binding.isStatic() ? 0 : 1, codeStream); // arguments initialization for local variable debug attributes if (this.arguments != null) { for (int i = 0, max = this.arguments.length; i < max; i++) { LocalVariableBinding argBinding; codeStream.addVisibleLocalVariable(argBinding = this.arguments[i].binding); argBinding.recordInitializationStartPC(0); } } if (this.statements != null) { for (int i = 0, max = this.statements.length; i < max; i++) this.statements[i].generateCode(this.scope, codeStream); } // if a problem got reported during code gen, then trigger problem method creation if (this.ignoreFurtherInvestigation) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } if ((this.bits & ASTNode.NeedFreeReturn) != 0) { codeStream.return_(); } // local variable attributes codeStream.exitUserScope(this.scope); codeStream.recordPositionsFrom(0, this.declarationSourceEnd); try { classFile.completeCodeAttribute(codeAttributeOffset); } catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } attributeNumber++; } else { checkArgumentsSize(); } classFile.completeMethodInfo(this.binding, methodAttributeOffset, attributeNumber); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; if (this.constant != Constant.NotAConstant) { if (valueRequired) { codeStream.generateConstant(this.constant, this.implicitConversion); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } else { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); Constant fieldConstant = codegenField.constant(); if (fieldConstant != Constant.NotAConstant) { // directly use inlined value for constant fields if (valueRequired) { codeStream.generateConstant(fieldConstant, this.implicitConversion); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (codegenField.isStatic()) { if (!valueRequired // if no valueRequired, still need possible side-effects of <clinit> invocation, if field belongs to different class && ((FieldBinding)this.binding).original().declaringClass == this.actualReceiverType.erasure() && ((this.implicitConversion & TypeIds.UNBOXING) == 0) && this.genericCast == null) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // managing private access if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if (!valueRequired && (this.implicitConversion & TypeIds.UNBOXING) == 0 && this.genericCast == null) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // managing enclosing instance access if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } // managing private access if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } break; case Binding.LOCAL : // reading a local LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (!valueRequired && (this.implicitConversion & TypeIds.UNBOXING) == 0) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // outer local? if ((this.bits & ASTNode.DepthMASK) != 0) { // outer local can be reached either through a synthetic arg or a synthetic field VariableBinding[] path = currentScope.getEmulationPath(localBinding); codeStream.generateOuterAccess(path, this, localBinding, currentScope); } else { // regular local variable read codeStream.load(localBinding); } break; default: // type codeStream.recordPositionsFrom(pc, this.sourceStart); return; } } // required cast must occur even if no value is required if (this.genericCast != null) codeStream.checkcast(this.genericCast); if (valueRequired) { codeStream.generateImplicitConversion(this.implicitConversion); } else { boolean isUnboxing = (this.implicitConversion & TypeIds.UNBOXING) != 0; // conversion only generated if unboxing if (isUnboxing) codeStream.generateImplicitConversion(this.implicitConversion); switch (isUnboxing ? postConversionType(currentScope).id : this.resolvedType.id) { case T_long : case T_double : codeStream.pop2(); break; default : codeStream.pop(); } } codeStream.recordPositionsFrom(pc, this.sourceStart); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.isStatic()) { if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { codeStream.aload_0(); } codeStream.dup(); if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } break; case Binding.LOCAL : // assigning to a local variable (cannot assign to outer local) LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // using incr bytecode if possible Constant assignConstant; switch (localBinding.type.id) { case T_JavaLangString : codeStream.generateStringConcatenationAppend(currentScope, this, expression); if (valueRequired) { codeStream.dup(); } codeStream.store(localBinding, false); return; case T_int : assignConstant = expression.constant; if (localBinding.resolvedPosition == -1) { if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } if ((assignConstant != Constant.NotAConstant) && (assignConstant.typeID() != TypeIds.T_float) // only for integral types && (assignConstant.typeID() != TypeIds.T_double)) { // TODO (philippe) is this test needed ? switch (operator) { case PLUS : int increment = assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; case MINUS : increment = -assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; } } //$FALL-THROUGH$ default : if (localBinding.resolvedPosition == -1) { assignConstant = expression.constant; if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } codeStream.load(localBinding); } } // perform the actual compound operation int operationTypeID; switch(operationTypeID = (this.implicitConversion & TypeIds.IMPLICIT_CONVERSION_MASK) >> 4) { case T_JavaLangString : case T_JavaLangObject : case T_undefined : // we enter here if the single name reference is a field of type java.lang.String or if the type of the // operation is java.lang.Object // For example: o = o + ""; // where the compiled type of o is java.lang.Object. codeStream.generateStringConcatenationAppend(currentScope, null, expression); // no need for generic cast on previous #getfield since using Object string buffer methods. break; default : // promote the array reference to the suitable operation type if (this.genericCast != null) codeStream.checkcast(this.genericCast); codeStream.generateImplicitConversion(this.implicitConversion); // generate the increment value (will by itself be promoted to the operation value) if (expression == IntLiteral.One){ // prefix operation codeStream.generateConstant(expression.constant, this.implicitConversion); } else { expression.generateCode(currentScope, codeStream, true); } // perform the operation codeStream.sendOperator(operator, operationTypeID); // cast the value back to the array reference type codeStream.generateImplicitConversion(assignmentImplicitConversion); } // store the result back into the variable switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); fieldStore(currentScope, codeStream, codegenField, writeAccessor, this.actualReceiverType, true /* implicit this*/, valueRequired); // no need for generic cast as value got dupped return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (valueRequired) { switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.store(localBinding, false); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding fieldBinding = (FieldBinding)this.binding; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185682 // check if postIncrement is the only usage of a private field reportOnlyUselesslyReadPrivateField(currentScope, fieldBinding, valueRequired); FieldBinding codegenField = fieldBinding.original(); if (codegenField.isStatic()) { if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { codeStream.aload_0(); } codeStream.dup(); if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } TypeBinding operandType; if (this.genericCast != null) { codeStream.checkcast(this.genericCast); operandType = this.genericCast; } else { operandType = codegenField.type; } if (valueRequired) { if (codegenField.isStatic()) { switch (operandType.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value] switch (operandType.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2_x1(); break; default: codeStream.dup_x1(); break; } } } codeStream.generateImplicitConversion(this.implicitConversion); codeStream.generateConstant(postIncrement.expression.constant, this.implicitConversion); codeStream.sendOperator(postIncrement.operator, this.implicitConversion & TypeIds.COMPILE_TYPE_MASK); codeStream.generateImplicitConversion(postIncrement.preAssignImplicitConversion); fieldStore(currentScope, codeStream, codegenField, this.syntheticAccessors == null ? null : this.syntheticAccessors[SingleNameReference.WRITE], this.actualReceiverType, true /*implicit this*/, false); // no need for generic cast return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185682 // check if postIncrement is the only usage of this local Reference.reportOnlyUselesslyReadLocal(currentScope, localBinding, valueRequired); if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } return; } // using incr bytecode if possible if (localBinding.type == TypeBinding.INT) { if (valueRequired) { codeStream.load(localBinding); } if (postIncrement.operator == OperatorIds.PLUS) { codeStream.iinc(localBinding.resolvedPosition, 1); } else { codeStream.iinc(localBinding.resolvedPosition, -1); } } else { codeStream.load(localBinding); if (valueRequired){ switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.generateImplicitConversion(this.implicitConversion); codeStream.generateConstant(postIncrement.expression.constant, this.implicitConversion); codeStream.sendOperator(postIncrement.operator, this.implicitConversion & TypeIds.COMPILE_TYPE_MASK); codeStream.generateImplicitConversion(postIncrement.preAssignImplicitConversion); codeStream.store(localBinding, false); } } }
2
              
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
0
(Domain) AssertionFailedException 31
              
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
public static IClasspathEntry elementDecode(Element element, IJavaProject project, Map unknownElements) { IPath projectPath = project.getProject().getFullPath(); NamedNodeMap attributes = element.getAttributes(); NodeList children = element.getChildNodes(); boolean[] foundChildren = new boolean[children.getLength()]; String kindAttr = removeAttribute(TAG_KIND, attributes); String pathAttr = removeAttribute(TAG_PATH, attributes); // ensure path is absolute IPath path = new Path(pathAttr); int kind = kindFromString(kindAttr); if (kind != IClasspathEntry.CPE_VARIABLE && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) { if (!(path.segmentCount() > 0 && path.segment(0).equals(ClasspathEntry.DOT_DOT))) { path = projectPath.append(path); } } // source attachment info (optional) IPath sourceAttachmentPath = element.hasAttribute(TAG_SOURCEPATH) ? new Path(removeAttribute(TAG_SOURCEPATH, attributes)) : null; if (kind != IClasspathEntry.CPE_VARIABLE && sourceAttachmentPath != null && !sourceAttachmentPath.isAbsolute()) { sourceAttachmentPath = projectPath.append(sourceAttachmentPath); } IPath sourceAttachmentRootPath = element.hasAttribute(TAG_ROOTPATH) ? new Path(removeAttribute(TAG_ROOTPATH, attributes)) : null; // exported flag (optional) boolean isExported = removeAttribute(TAG_EXPORTED, attributes).equals("true"); //$NON-NLS-1$ // inclusion patterns (optional) IPath[] inclusionPatterns = decodePatterns(attributes, TAG_INCLUDING); if (inclusionPatterns == null) inclusionPatterns = INCLUDE_ALL; // exclusion patterns (optional) IPath[] exclusionPatterns = decodePatterns(attributes, TAG_EXCLUDING); if (exclusionPatterns == null) exclusionPatterns = EXCLUDE_NONE; // access rules (optional) NodeList attributeList = getChildAttributes(TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = decodeAccessRules(attributeList); // backward compatibility if (accessRules == null) { accessRules = getAccessRules(inclusionPatterns, exclusionPatterns); } // combine access rules (optional) boolean combineAccessRestrictions = !removeAttribute(TAG_COMBINE_ACCESS_RULES, attributes).equals("false"); //$NON-NLS-1$ // extra attributes (optional) attributeList = getChildAttributes(TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = decodeExtraAttributes(attributeList); // custom output location IPath outputLocation = element.hasAttribute(TAG_OUTPUT) ? projectPath.append(removeAttribute(TAG_OUTPUT, attributes)) : null; String[] unknownAttributes = null; ArrayList unknownChildren = null; if (unknownElements != null) { // unknown attributes int unknownAttributeLength = attributes.getLength(); if (unknownAttributeLength != 0) { unknownAttributes = new String[unknownAttributeLength*2]; for (int i = 0; i < unknownAttributeLength; i++) { Node attribute = attributes.item(i); unknownAttributes[i*2] = attribute.getNodeName(); unknownAttributes[i*2 + 1] = attribute.getNodeValue(); } } // unknown children for (int i = 0, length = foundChildren.length; i < length; i++) { if (!foundChildren[i]) { Node node = children.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; if (unknownChildren == null) unknownChildren = new ArrayList(); StringBuffer buffer = new StringBuffer(); decodeUnknownNode(node, buffer, project); unknownChildren.add(buffer.toString()); } } } // recreate the CP entry IClasspathEntry entry = null; switch (kind) { case IClasspathEntry.CPE_PROJECT : entry = new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, combineAccessRestrictions, extraAttributes); break; case IClasspathEntry.CPE_LIBRARY : entry = JavaCore.newLibraryEntry( path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules, extraAttributes, isExported); break; case IClasspathEntry.CPE_SOURCE : // must be an entry in this project or specify another project String projSegment = path.segment(0); if (projSegment != null && projSegment.equals(project.getElementName())) { // this project entry = JavaCore.newSourceEntry( path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes); } else { if (path.segmentCount() == 1) { // another project entry = JavaCore.newProjectEntry( path, accessRules, combineAccessRestrictions, extraAttributes, isExported); } else { // an invalid source folder entry = JavaCore.newSourceEntry( path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes); } } break; case IClasspathEntry.CPE_VARIABLE : entry = JavaCore.newVariableEntry( path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules, extraAttributes, isExported); break; case IClasspathEntry.CPE_CONTAINER : entry = JavaCore.newContainerEntry( path, accessRules, extraAttributes, isExported); break; case ClasspathEntry.K_OUTPUT : if (!path.isAbsolute()) return null; entry = new ClasspathEntry( ClasspathEntry.K_OUTPUT, IClasspathEntry.CPE_LIBRARY, path, INCLUDE_ALL, EXCLUDE_NONE, null, // source attachment null, // source attachment root null, // custom output location false, null, // no access rules false, // no accessible files to combine NO_EXTRA_ATTRIBUTES); break; default : throw new AssertionFailedException(Messages.bind(Messages.classpath_unknownKind, kindAttr)); } if (unknownAttributes != null || unknownChildren != null) { UnknownXmlElements unknownXmlElements = new UnknownXmlElements(); unknownXmlElements.attributes = unknownAttributes; unknownXmlElements.children = unknownChildren; unknownElements.put(path, unknownXmlElements); } return entry; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newContainerEntry( IPath containerPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (containerPath == null) { throw new ClasspathEntry.AssertionFailedException("Container path cannot be null"); //$NON-NLS-1$ } else if (containerPath.segmentCount() < 1) { throw new ClasspathEntry.AssertionFailedException("Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$ } if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_CONTAINER, containerPath, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, true, // combine access rules extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newLibraryEntry( IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (path == null) throw new ClasspathEntry.AssertionFailedException("Library path cannot be null"); //$NON-NLS-1$ if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } boolean hasDotDot = ClasspathEntry.hasDotDot(path); if (!hasDotDot && !path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute: " + path); //$NON-NLS-1$ if (sourceAttachmentPath != null) { if (sourceAttachmentPath.isEmpty()) { sourceAttachmentPath = null; // treat empty path as none } else if (!sourceAttachmentPath.isAbsolute()) { throw new ClasspathEntry.AssertionFailedException("Source attachment path '" //$NON-NLS-1$ + sourceAttachmentPath + "' for IClasspathEntry must be absolute"); //$NON-NLS-1$ } } return new ClasspathEntry( IPackageFragmentRoot.K_BINARY, IClasspathEntry.CPE_LIBRARY, hasDotDot ? path : JavaProject.canonicalizedPath(path), ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns sourceAttachmentPath, sourceAttachmentRootPath, null, // specific output folder isExported, accessRules, false, // no access rules to combine extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) { if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ return newProjectEntry( path, ClasspathEntry.NO_ACCESS_RULES, true, ClasspathEntry.NO_EXTRA_ATTRIBUTES, isExported); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newProjectEntry( IPath path, IAccessRule[] accessRules, boolean combineAccessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, combineAccessRules, extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns, IPath specificOutputLocation, IClasspathAttribute[] extraAttributes) { if (path == null) throw new ClasspathEntry.AssertionFailedException("Source path cannot be null"); //$NON-NLS-1$ if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ if (exclusionPatterns == null) { exclusionPatterns = ClasspathEntry.EXCLUDE_NONE; } if (inclusionPatterns == null) { inclusionPatterns = ClasspathEntry.INCLUDE_ALL; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_SOURCE, path, inclusionPatterns, exclusionPatterns, null, // source attachment null, // source attachment root specificOutputLocation, // custom output location false, null, false, // no access rules to combine extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newVariableEntry( IPath variablePath, IPath variableSourceAttachmentPath, IPath variableSourceAttachmentRootPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (variablePath == null) throw new ClasspathEntry.AssertionFailedException("Variable path cannot be null"); //$NON-NLS-1$ if (variablePath.segmentCount() < 1) { throw new ClasspathEntry.AssertionFailedException("Illegal classpath variable path: \'" + variablePath.makeRelative().toString() + "\', must have at least one segment"); //$NON-NLS-1$//$NON-NLS-2$ } if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_VARIABLE, variablePath, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns variableSourceAttachmentPath, // source attachment variableSourceAttachmentRootPath, // source attachment root null, // specific output folder isExported, accessRules, false, // no access rules to combine extraAttributes); }
// 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, 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 compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
private FlowInfo addInfoFrom(FlowInfo inits, boolean handleInits) { if (this == DEAD_END) return this; if (inits == DEAD_END) return this; UnconditionalFlowInfo otherInits = inits.unconditionalInits(); if (handleInits) { // union of definitely assigned variables, this.definiteInits |= otherInits.definiteInits; // union of potentially set ones this.potentialInits |= otherInits.potentialInits; } // combine null information boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0, otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0; long a1, a2, a3, a4, na1, na2, na3, na4, b1, b2, b3, b4, nb1, nb2, nb3, nb4; if (otherHasNulls) { if (!thisHadNulls) { this.nullBit1 = otherInits.nullBit1; this.nullBit2 = otherInits.nullBit2; this.nullBit3 = otherInits.nullBit3; this.nullBit4 = otherInits.nullBit4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 1) { this.nullBit4 = ~0; } } } else { this.nullBit1 = (b1 = otherInits.nullBit1) | (a1 = this.nullBit1) & ((a3 = this.nullBit3) & (a4 = this.nullBit4) & (nb2 = ~(b2 = otherInits.nullBit2)) & (nb4 = ~(b4 = otherInits.nullBit4)) | ((na4 = ~a4) | (na3 = ~a3)) & ((na2 = ~(a2 = this.nullBit2)) & nb2 | a2 & (nb3 = ~(b3 = otherInits.nullBit3)) & nb4)); this.nullBit2 = b2 & (nb4 | nb3) | na3 & na4 & b2 | a2 & (nb3 & nb4 | (nb1 = ~b1) & (na3 | (na1 = ~a1)) | a1 & b2); this.nullBit3 = b3 & (nb1 & (b2 | a2 | na1) | b1 & (b4 | nb2 | a1 & a3) | na1 & na2 & na4) | a3 & nb2 & nb4 | nb1 & ((na2 & a4 | na1) & a3 | a1 & na2 & na4 & b2); this.nullBit4 = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2) | a1 & (a3 & nb2 & b4 | a2 & b2 & (b4 | a3 & na4 & nb3))) | b1 & (a3 & a4 & b4 | na2 & na4 & nb3 & b4 | a2 & ((b3 | a4) & b4 | na3 & a4 & b2 & b3) | na1 & (b4 | (a4 | a2) & b2 & b3)) | (na1 & (na3 & nb3 | na2 & nb2) | a1 & (nb2 & nb3 | a2 & a3)) & b4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 2) { this.nullBit4 = ~0; } } } this.tagBits |= NULL_FLAG_MASK; // in all cases - avoid forgetting extras } // treating extra storage if (this.extra != null || otherInits.extra != null) { int mergeLimit = 0, copyLimit = 0; if (this.extra != null) { if (otherInits.extra != null) { // both sides have extra storage int length, otherLength; if ((length = this.extra[0].length) < (otherLength = otherInits.extra[0].length)) { // current storage is shorter -> grow current for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, length); } mergeLimit = length; copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 3) { throw new AssertionFailedException("COVERAGE 3"); //$NON-NLS-1$ } } } else { // current storage is longer mergeLimit = otherLength; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 4) { throw new AssertionFailedException("COVERAGE 4"); //$NON-NLS-1$ } } } } } else if (otherInits.extra != null) { // no storage here, but other has extra storage. // shortcut regular copy because array copy is better int otherLength; this.extra = new long[extraLength][]; System.arraycopy(otherInits.extra[0], 0, (this.extra[0] = new long[otherLength = otherInits.extra[0].length]), 0, otherLength); System.arraycopy(otherInits.extra[1], 0, (this.extra[1] = new long[otherLength]), 0, otherLength); if (otherHasNulls) { for (int j = 2; j < extraLength; j++) { System.arraycopy(otherInits.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, otherLength); } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 5) { this.extra[5][otherLength - 1] = ~0; } } } else { for (int j = 2; j < extraLength; j++) { this.extra[j] = new long[otherLength]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 6) { throw new AssertionFailedException("COVERAGE 6"); //$NON-NLS-1$ } } } } int i; if (handleInits) { // manage definite assignment info for (i = 0; i < mergeLimit; i++) { this.extra[0][i] |= otherInits.extra[0][i]; this.extra[1][i] |= otherInits.extra[1][i]; } for (; i < copyLimit; i++) { this.extra[0][i] = otherInits.extra[0][i]; this.extra[1][i] = otherInits.extra[1][i]; } } // tweak limits for nulls if (!thisHadNulls) { if (copyLimit < mergeLimit) { copyLimit = mergeLimit; } mergeLimit = 0; } if (!otherHasNulls) { copyLimit = 0; mergeLimit = 0; } for (i = 0; i < mergeLimit; i++) { this.extra[1 + 1][i] = (b1 = otherInits.extra[1 + 1][i]) | (a1 = this.extra[1 + 1][i]) & ((a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & (nb2 = ~(b2 = otherInits.extra[2 + 1][i])) & (nb4 = ~(b4 = otherInits.extra[4 + 1][i])) | ((na4 = ~a4) | (na3 = ~a3)) & ((na2 = ~(a2 = this.extra[2 + 1][i])) & nb2 | a2 & (nb3 = ~(b3 = otherInits.extra[3 + 1][i])) & nb4)); this.extra[2 + 1][i] = b2 & (nb4 | nb3) | na3 & na4 & b2 | a2 & (nb3 & nb4 | (nb1 = ~b1) & (na3 | (na1 = ~a1)) | a1 & b2); this.extra[3 + 1][i] = b3 & (nb1 & (b2 | a2 | na1) | b1 & (b4 | nb2 | a1 & a3) | na1 & na2 & na4) | a3 & nb2 & nb4 | nb1 & ((na2 & a4 | na1) & a3 | a1 & na2 & na4 & b2); this.extra[4 + 1][i] = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2) | a1 & (a3 & nb2 & b4 | a2 & b2 & (b4 | a3 & na4 & nb3))) | b1 & (a3 & a4 & b4 | na2 & na4 & nb3 & b4 | a2 & ((b3 | a4) & b4 | na3 & a4 & b2 & b3) | na1 & (b4 | (a4 | a2) & b2 & b3)) | (na1 & (na3 & nb3 | na2 & nb2) | a1 & (nb2 & nb3 | a2 & a3)) & b4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 7) { this.extra[5][i] = ~0; } } } for (; i < copyLimit; i++) { for (int j = 2; j < extraLength; j++) { this.extra[j][i] = otherInits.extra[j][i]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 8) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); return this; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public UnconditionalFlowInfo addPotentialNullInfoFrom( UnconditionalFlowInfo otherInits) { if ((this.tagBits & UNREACHABLE) != 0 || (otherInits.tagBits & UNREACHABLE) != 0 || (otherInits.tagBits & NULL_FLAG_MASK) == 0) { return this; } // if we get here, otherInits has some null info boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0, thisHasNulls = false; long a1, a2, a3, a4, na1, na2, na3, na4, b1, b2, b3, b4, nb1, nb2, nb3, nb4; if (thisHadNulls) { this.nullBit1 = (a1 = this.nullBit1) & ((a3 = this.nullBit3) & (a4 = this.nullBit4) & ((nb2 = ~(b2 = otherInits.nullBit2)) & (nb4 = ~(b4 = otherInits.nullBit4)) | (b1 = otherInits.nullBit1) & (b3 = otherInits.nullBit3)) | (na2 = ~(a2 = this.nullBit2)) & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2) | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2))); this.nullBit2 = b2 & (nb3 | (nb1 = ~b1)) | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1)); this.nullBit3 = b3 & (nb1 & b2 | a2 & (nb2 | a3) | na1 & nb2 | a1 & na2 & na4 & b1) | a3 & (nb2 & nb4 | na2 & a4 | na1) | a1 & na2 & na4 & b2; this.nullBit4 = na3 & (nb1 & nb3 & b4 | a4 & (nb3 | b1 & b2)) | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4)) | a3 & (a4 & (nb2 | b1 & b3) | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3)); if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 9) { this.nullBit4 = ~0; } } if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant thisHasNulls = true; } } else { this.nullBit1 = 0; this.nullBit2 = (b2 = otherInits.nullBit2) & ((nb3 = ~(b3 = otherInits.nullBit3)) | (nb1 = ~(b1 = otherInits.nullBit1))); this.nullBit3 = b3 & (nb1 | (nb2 = ~b2)); this.nullBit4 = ~b1 & ~b3 & (b4 = otherInits.nullBit4) | ~b2 & (b1 & ~b3 | ~b1 & b4); if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 10) { this.nullBit4 = ~0; } } if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant thisHasNulls = true; } } // extra storage management if (otherInits.extra != null) { int mergeLimit = 0, copyLimit = otherInits.extra[0].length; if (this.extra == null) { this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[copyLimit]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 11) { throw new AssertionFailedException("COVERAGE 11"); //$NON-NLS-1$ } } } else { mergeLimit = copyLimit; if (mergeLimit > this.extra[0].length) { mergeLimit = this.extra[0].length; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, this.extra[j] = new long[copyLimit], 0, mergeLimit); } if (! thisHadNulls) { mergeLimit = 0; // will do with a copy -- caveat: only valid because definite assignment bits copied above if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 12) { throw new AssertionFailedException("COVERAGE 12"); //$NON-NLS-1$ } } } } } // PREMATURE skip operations for fields int i; for (i = 0 ; i < mergeLimit ; i++) { this.extra[1 + 1][i] = (a1 = this.extra[1 + 1][i]) & ((a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & ((nb2 = ~(b2 = otherInits.extra[2 + 1][i])) & (nb4 = ~(b4 = otherInits.extra[4 + 1][i])) | (b1 = otherInits.extra[1 + 1][i]) & (b3 = otherInits.extra[3 + 1][i])) | (na2 = ~(a2 = this.extra[2 + 1][i])) & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2) | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2))); this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1)) | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1)); this.extra[3 + 1][i] = b3 & (nb1 & b2 | a2 & (nb2 | a3) | na1 & nb2 | a1 & na2 & na4 & b1) | a3 & (nb2 & nb4 | na2 & a4 | na1) | a1 & na2 & na4 & b2; this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4 | a4 & (nb3 | b1 & b2)) | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4)) | a3 & (a4 & (nb2 | b1 & b3) | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3)); if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant thisHasNulls = true; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 13) { this.nullBit4 = ~0; } } } for (; i < copyLimit; i++) { this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i]) & ((nb3 = ~(b3 = otherInits.extra[3 + 1][i])) | (nb1 = ~(b1 = otherInits.extra[1 + 1][i]))); this.extra[3 + 1][i] = b3 & (nb1 | (nb2 = ~b2)); this.extra[4 + 1][i] = ~b1 & ~b3 & (b4 = otherInits.extra[4 + 1][i]) | ~b2 & (b1 & ~b3 | ~b1 & b4); if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant thisHasNulls = true; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 14) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); if (thisHasNulls) { this.tagBits |= NULL_FLAG_MASK; } else { this.tagBits &= NULL_FLAG_MASK; } return this; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
protected static boolean isTrue(boolean expression, String message) { if (!expression) throw new AssertionFailedException("assertion failed: " + message); //$NON-NLS-1$ return expression; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public void markAsComparedEqualToNonNull(LocalVariableBinding local) { // protected from non-object locals in calling methods if (this != DEAD_END) { this.tagBits |= NULL_FLAG_MASK; int position; long mask; long a1, a2, a3, a4, na2; // position is zero-based if ((position = local.id + this.maxFieldCount) < BitCacheSize) { // use bits if (((mask = 1L << position) & (a1 = this.nullBit1) & (na2 = ~(a2 = this.nullBit2)) & ~(a3 = this.nullBit3) & (a4 = this.nullBit4)) != 0) { this.nullBit4 &= ~mask; } else if ((mask & a1 & na2 & a3) == 0) { this.nullBit4 |= mask; if ((mask & a1) == 0) { if ((mask & a2 & (a3 ^ a4)) != 0) { this.nullBit2 &= ~mask; } else if ((mask & (a2 | a3 | a4)) == 0) { this.nullBit2 |= mask; } } } this.nullBit1 |= mask; this.nullBit3 |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 15) { this.nullBit4 = ~0; } } } else { // use extra vector int vectorIndex = (position / BitCacheSize) - 1; if (this.extra == null) { int length = vectorIndex + 1; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[length]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 16) { throw new AssertionFailedException("COVERAGE 16"); //$NON-NLS-1$ } } } else { int oldLength; if (vectorIndex >= (oldLength = this.extra[0].length)) { int newLength = vectorIndex + 1; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[newLength]), 0, oldLength); } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 17) { throw new AssertionFailedException("COVERAGE 17"); //$NON-NLS-1$ } } } } // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][vectorIndex]/gc if (((mask = 1L << (position % BitCacheSize)) & (a1 = this.extra[1 + 1][vectorIndex]) & (na2 = ~(a2 = this.extra[2 + 1][vectorIndex])) & ~(a3 = this.extra[3 + 1][vectorIndex]) & (a4 = this.extra[4 + 1][vectorIndex])) != 0) { this.extra[4 + 1][vectorIndex] &= ~mask; } else if ((mask & a1 & na2 & a3) == 0) { this.extra[4 + 1][vectorIndex] |= mask; if ((mask & a1) == 0) { if ((mask & a2 & (a3 ^ a4)) != 0) { this.extra[2 + 1][vectorIndex] &= ~mask; } else if ((mask & (a2 | a3 | a4)) == 0) { this.extra[2 + 1][vectorIndex] |= mask; } } } this.extra[1 + 1][vectorIndex] |= mask; this.extra[3 + 1][vectorIndex] |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 18) { this.extra[5][vectorIndex] = ~0; } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public void markAsComparedEqualToNull(LocalVariableBinding local) { // protected from non-object locals in calling methods if (this != DEAD_END) { this.tagBits |= NULL_FLAG_MASK; int position; long mask; // position is zero-based if ((position = local.id + this.maxFieldCount) < BitCacheSize) { // use bits if (((mask = 1L << position) & this.nullBit1) != 0) { if ((mask & (~this.nullBit2 | this.nullBit3 | ~this.nullBit4)) != 0) { this.nullBit4 &= ~mask; } } else if ((mask & this.nullBit4) != 0) { this.nullBit3 &= ~mask; } else { if ((mask & this.nullBit2) != 0) { this.nullBit3 &= ~mask; this.nullBit4 |= mask; } else { this.nullBit3 |= mask; } } this.nullBit1 |= mask; this.nullBit2 |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 19) { this.nullBit4 = ~0; } } } else { // use extra vector int vectorIndex = (position / BitCacheSize) - 1; mask = 1L << (position % BitCacheSize); if (this.extra == null) { int length = vectorIndex + 1; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[length ]; } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 20) { throw new AssertionFailedException("COVERAGE 20"); //$NON-NLS-1$ } } } else { int oldLength; if (vectorIndex >= (oldLength = this.extra[0].length)) { int newLength = vectorIndex + 1; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[newLength]), 0, oldLength); } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 21) { throw new AssertionFailedException("COVERAGE 21"); //$NON-NLS-1$ } } } } if ((mask & this.extra[1 + 1][vectorIndex]) != 0) { if ((mask & (~this.extra[2 + 1][vectorIndex] | this.extra[3 + 1][vectorIndex] | ~this.extra[4 + 1][vectorIndex])) != 0) { this.extra[4 + 1][vectorIndex] &= ~mask; } } else if ((mask & this.extra[4 + 1][vectorIndex]) != 0) { this.extra[3 + 1][vectorIndex] &= ~mask; } else { if ((mask & this.extra[2 + 1][vectorIndex]) != 0) { this.extra[3 + 1][vectorIndex] &= ~mask; this.extra[4 + 1][vectorIndex] |= mask; } else { this.extra[3 + 1][vectorIndex] |= mask; } } this.extra[1 + 1][vectorIndex] |= mask; this.extra[2 + 1][vectorIndex] |= mask; } } }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) { if ((otherInits.tagBits & UNREACHABLE_OR_DEAD) != 0 && this != DEAD_END) { if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 28) { throw new AssertionFailedException("COVERAGE 28"); //$NON-NLS-1$ } } combineNullStatusChangeInAssertInfo(otherInits); return this; } if ((this.tagBits & UNREACHABLE_OR_DEAD) != 0) { if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 29) { throw new AssertionFailedException("COVERAGE 29"); //$NON-NLS-1$ } } otherInits.combineNullStatusChangeInAssertInfo(this); return (UnconditionalFlowInfo) otherInits.copy(); // make sure otherInits won't be affected } // intersection of definitely assigned variables, this.definiteInits &= otherInits.definiteInits; // union of potentially set ones this.potentialInits |= otherInits.potentialInits; // null combinations boolean thisHasNulls = (this.tagBits & NULL_FLAG_MASK) != 0, otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0, thisHadNulls = thisHasNulls; long a1, a2, a3, a4, na1, na2, na3, na4, nb1, nb2, nb3, nb4, b1, b2, b3, b4; if ((otherInits.tagBits & FlowInfo.UNREACHABLE_BY_NULLANALYSIS) != 0) { otherHasNulls = false; // skip merging, otherInits is unreachable by null analysis } else if ((this.tagBits & FlowInfo.UNREACHABLE_BY_NULLANALYSIS) != 0) { // directly copy if this is unreachable by null analysis this.nullBit1 = otherInits.nullBit1; this.nullBit2 = otherInits.nullBit2; this.nullBit3 = otherInits.nullBit3; this.nullBit4 = otherInits.nullBit4; thisHadNulls = false; thisHasNulls = otherHasNulls; this.tagBits = otherInits.tagBits; } else if (thisHadNulls) { if (otherHasNulls) { this.nullBit1 = (a2 = this.nullBit2) & (a3 = this.nullBit3) & (a4 = this.nullBit4) & (b1 = otherInits.nullBit1) & (nb2 = ~(b2 = otherInits.nullBit2)) | (a1 = this.nullBit1) & (b1 & (a3 & a4 & (b3 = otherInits.nullBit3) & (b4 = otherInits.nullBit4) | (na2 = ~a2) & nb2 & ((nb4 = ~b4) | (na4 = ~a4) | (na3 = ~a3) & (nb3 = ~b3)) | a2 & b2 & ((na4 | na3) & (nb4 | nb3))) | na2 & b2 & b3 & b4); this.nullBit2 = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4) | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1); this.nullBit3 = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4)) | a3 & (na2 & a4 | na1) | (a2 | na1) & b1 & nb2 & nb4 | a1 & na2 & na4 & (b2 | nb1); this.nullBit4 = na3 & (nb1 & nb3 & b4 | b1 & (nb2 & nb3 | a4 & b2 & nb4) | na1 & a4 & (nb3 | b1 & b2)) | a3 & a4 & (b3 & b4 | b1 & nb2) | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2 | a1 & (na3 & (nb3 & b4 | b1 & b2 & b3 & nb4 | na2 & (nb3 | nb2)) | na2 & b3 & b4 | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3); // the above formulae do not handle the state 0111, do it now explicitly: long ax = ~a1 & a2 & a3 & a4; long bx = ~b1 & b2 & b3 & b4; long x = ax|bx; if (x != 0) { // restore state 0111 for all variable ids in x: this.nullBit1 &= ~x; this.nullBit2 |= x; this.nullBit3 |= x; this.nullBit4 |= x; } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 30) { this.nullBit4 = ~0; } } } else { // other has no null info a1 = this.nullBit1; this.nullBit1 = 0; this.nullBit2 = (a2 = this.nullBit2) & (na3 = ~(a3 = this.nullBit3) | (na1 = ~a1)); this.nullBit3 = a3 & ((na2 = ~a2) & (a4 = this.nullBit4) | na1) | a1 & na2 & ~a4; this.nullBit4 = (na3 | na2) & na1 & a4 | a1 & na3 & na2; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 31) { this.nullBit4 = ~0; } } } } else if (otherHasNulls) { // only other had nulls this.nullBit1 = 0; this.nullBit2 = (b2 = otherInits.nullBit2) & (nb3 = ~(b3 = otherInits.nullBit3) | (nb1 = ~(b1 = otherInits.nullBit1))); this.nullBit3 = b3 & ((nb2 = ~b2) & (b4 = otherInits.nullBit4) | nb1) | b1 & nb2 & ~b4; this.nullBit4 = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 32) { this.nullBit4 = ~0; } } thisHasNulls = // redundant with the three following ones this.nullBit2 != 0 || this.nullBit3 != 0 || this.nullBit4 != 0; } // treating extra storage if (this.extra != null || otherInits.extra != null) { int mergeLimit = 0, copyLimit = 0, resetLimit = 0; int i; if (this.extra != null) { if (otherInits.extra != null) { // both sides have extra storage int length, otherLength; if ((length = this.extra[0].length) < (otherLength = otherInits.extra[0].length)) { // current storage is shorter -> grow current for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, length); } mergeLimit = length; copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 33) { throw new AssertionFailedException("COVERAGE 33"); //$NON-NLS-1$ } } } else { // current storage is longer mergeLimit = otherLength; resetLimit = length; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 34) { throw new AssertionFailedException("COVERAGE 34"); //$NON-NLS-1$ } } } } else { resetLimit = this.extra[0].length; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 35) { throw new AssertionFailedException("COVERAGE 35"); //$NON-NLS-1$ } } } } else if (otherInits.extra != null) { // no storage here, but other has extra storage. int otherLength = otherInits.extra[0].length; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[otherLength]; } System.arraycopy(otherInits.extra[1], 0, this.extra[1], 0, otherLength); copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 36) { throw new AssertionFailedException("COVERAGE 36"); //$NON-NLS-1$ } } } // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][i]/g // manage definite assignment for (i = 0; i < mergeLimit; i++) { this.extra[0][i] &= otherInits.extra[0][i]; this.extra[1][i] |= otherInits.extra[1][i]; } for (; i < copyLimit; i++) { this.extra[1][i] = otherInits.extra[1][i]; } for (; i < resetLimit; i++) { this.extra[0][i] = 0; } // refine null bits requirements if (!otherHasNulls) { if (resetLimit < mergeLimit) { resetLimit = mergeLimit; } copyLimit = 0; // no need to carry inexisting nulls mergeLimit = 0; } if (!thisHadNulls) { resetLimit = 0; // no need to reset anything } // compose nulls for (i = 0; i < mergeLimit; i++) { this.extra[1 + 1][i] = (a2 = this.extra[2 + 1][i]) & (a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & (b1 = otherInits.extra[1 + 1][i]) & (nb2 = ~(b2 = otherInits.extra[2 + 1][i])) | (a1 = this.extra[1 + 1][i]) & (b1 & (a3 & a4 & (b3 = otherInits.extra[3 + 1][i]) & (b4 = otherInits.extra[4 + 1][i]) | (na2 = ~a2) & nb2 & ((nb4 = ~b4) | (na4 = ~a4) | (na3 = ~a3) & (nb3 = ~b3)) | a2 & b2 & ((na4 | na3) & (nb4 | nb3))) | na2 & b2 & b3 & b4); this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4) | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1); this.extra[3 + 1][i] = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4)) | a3 & (na2 & a4 | na1) | (a2 | na1) & b1 & nb2 & nb4 | a1 & na2 & na4 & (b2 | nb1); this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4 | b1 & (nb2 & nb3 | a4 & b2 & nb4) | na1 & a4 & (nb3 | b1 & b2)) | a3 & a4 & (b3 & b4 | b1 & nb2) | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2 | a1 & (na3 & (nb3 & b4 | b1 & b2 & b3 & nb4 | na2 & (nb3 | nb2)) | na2 & b3 & b4 | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3); // the above formulae do not handle the state 0111, do it now explicitly: long ax = ~a1 & a2 & a3 & a4; long bx = ~b1 & b2 & b3 & b4; long x = ax|bx; if (x != 0) { // restore state 0111 for all variable ids in x: this.extra[2][i] &= ~x; this.extra[3][i] |= x; this.extra[4][i] |= x; this.extra[5][i] |= x; } thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0 ; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 37) { this.extra[5][i] = ~0; } } } for (; i < copyLimit; i++) { this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i]) & (nb3 = ~(b3 = otherInits.extra[3 + 1][i]) | (nb1 = ~(b1 = otherInits.extra[1 + 1][i]))); this.extra[3 + 1][i] = b3 & ((nb2 = ~b2) & (b4 = otherInits.extra[4 + 1][i]) | nb1) | b1 & nb2 & ~b4; this.extra[4 + 1][i] = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2; thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 38) { this.extra[5][i] = ~0; } } } for (; i < resetLimit; i++) { a1 = this.extra[1 + 1][i]; this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (a2 = this.extra[2 + 1][i]) & (na3 = ~(a3 = this.extra[3 + 1][i]) | (na1 = ~a1)); this.extra[3 + 1][i] = a3 & ((na2 = ~a2) & (a4 = this.extra[4 + 1][i]) | na1) | a1 & na2 & ~a4; this.extra[4 + 1][i] = (na3 | na2) & na1 & a4 | a1 & na3 & na2; thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 39) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); if (thisHasNulls) { this.tagBits |= NULL_FLAG_MASK; } else { this.tagBits &= ~NULL_FLAG_MASK; } return this; }
0 2
              
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
(Lib) CoreException 15
              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void verifyArchiveContent(IPath path) throws CoreException { if (isInvalidArchive(path)) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); } ZipFile file = getZipFile(path); closeZipFile(file); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public ZipFile getZipFile(IPath path) throws CoreException { if (isInvalidArchive(path)) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); ZipCache zipCache; ZipFile zipFile; if ((zipCache = (ZipCache)this.zipFiles.get()) != null && (zipFile = zipCache.getCache(path)) != null) { return zipFile; } File localFile = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource file = root.findMember(path); if (file != null) { // internal resource URI location; if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } localFile = Util.toLocalFile(location, null/*no progress availaible*/); if (localFile == null) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } else { // external resource -> it is ok to use toFile() localFile= path.toFile(); } try { if (ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile ); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile = new ZipFile(localFile); if (zipCache != null) { zipCache.setCache(path, zipFile); } return zipFile; } catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveBuiltState(PerProjectInfo info) throws CoreException { if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_saveStateProgress, info.project.getName())); File file = getSerializationFile(info.project); if (file == null) return; long t = System.currentTimeMillis(); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { out.writeUTF(JavaCore.PLUGIN_ID); out.writeUTF("STATE"); //$NON-NLS-1$ if (info.savedState == null) { out.writeBoolean(false); } else { out.writeBoolean(true); JavaBuilder.writeState(info.savedState, out); } } finally { out.close(); } } catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } if (JavaBuilder.DEBUG) { t = System.currentTimeMillis() - t; System.out.println(Messages.bind(Messages.build_saveStateComplete, String.valueOf(t))); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathListCache(String cacheName) throws CoreException { File file = getClasspathListFile(cacheName); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Set pathCache = getClasspathListCache(cacheName); synchronized (pathCache) { out.writeInt(pathCache.size()); Iterator entries = pathCache.iterator(); while (entries.hasNext()) { IPath path = (IPath) entries.next(); out.writeUTF(path.toPortableString()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariablesAndContainers(ISaveContext context) throws CoreException { File file = getVariableAndContainersFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeInt(VARIABLES_AND_CONTAINERS_FILE_VERSION); new VariablesAndContainersSaveHelper(out).save(context); } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void saving(ISaveContext context) throws CoreException { long start = -1; if (VERBOSE) start = System.currentTimeMillis(); // save variable and container values on snapshot/full save saveVariablesAndContainers(context); if (VERBOSE) traceVariableAndContainers("Saved", start); //$NON-NLS-1$ switch(context.getKind()) { case ISaveContext.FULL_SAVE : { // save non-chaining jar and invalid jar caches on full save saveClasspathListCache(NON_CHAINING_JARS_CACHE); saveClasspathListCache(INVALID_ARCHIVES_CACHE); // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) context.needDelta(); // clean up indexes on workspace full save // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) IndexManager manager = this.indexManager; if (manager != null // don't force initialization of workspace scope as we could be shutting down // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93941) && this.workspaceScope != null) { manager.cleanUpIndexes(); } } //$FALL-THROUGH$ case ISaveContext.SNAPSHOT : { // clean up external folders on full save or snapshot this.externalFoldersManager.cleanUp(null); } } IProject savedProject = context.getProject(); if (savedProject != null) { if (!JavaProject.hasJavaNature(savedProject)) return; // ignore PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); saveState(info, context); return; } ArrayList vStats= null; // lazy initialized ArrayList values = null; synchronized(this.perProjectInfos) { values = new ArrayList(this.perProjectInfos.values()); } Iterator iterator = values.iterator(); while (iterator.hasNext()) { try { PerProjectInfo info = (PerProjectInfo) iterator.next(); saveState(info, context); } catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); } } if (vStats != null) { IStatus[] stats= new IStatus[vStats.size()]; vStats.toArray(stats); throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Messages.build_cannotSaveStates, null)); } // save external libs timestamps this.deltaState.saveExternalLibTimeStamps(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void saveExternalLibTimeStamps() throws CoreException { if (this.externalTimeStamps == null) return; // cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 ) HashSet toRemove = new HashSet(); if (this.roots != null) { Enumeration keys = this.externalTimeStamps.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (this.roots.get(key) == null) { toRemove.add(key); } } } File timestamps = getTimeStampsFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps))); out.writeInt(this.externalTimeStamps.size() - toRemove.size()); Iterator entries = this.externalTimeStamps.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IPath key = (IPath) entry.getKey(); if (!toRemove.contains(key)) { out.writeUTF(key.toPortableString()); Long timestamp = (Long) entry.getValue(); out.writeLong(timestamp.longValue()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// 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 dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(boolean ignoreComments) throws CoreException { int curr= 0; do { try { curr= this.scanner.getNextToken(); if (curr == TerminalTokens.TokenNameEOF) { throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$ } } catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); } } while (ignoreComments && isComment(curr)); return curr; }
8
              
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
174
              
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { if (VERBOSE) { Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$ Util.verbose(scope.toString()); } if (participants == null) { if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$ return; } /* initialize progress monitor */ int length = participants.length; if (monitor != null) monitor.beginTask(Messages.engine_searching, 100 * length); IndexManager indexManager = JavaModelManager.getIndexManager(); requestor.beginReporting(); for (int i = 0; i < length; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); SearchParticipant participant = participants[i]; try { if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()})); participant.beginSearching(); requestor.enterParticipant(participant); PathCollector pathCollector = new PathCollector(); indexManager.performConcurrentJob( new PatternSearchJob(pattern, participant, scope, pathCollector), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor==null ? null : new SubProgressMonitor(monitor, 50)); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // locate index matches if any (note that all search matches could have been issued during index querying) if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()})); String[] indexMatchPaths = pathCollector.getPaths(); if (indexMatchPaths != null) { pathCollector = null; // release int indexMatchLength = indexMatchPaths.length; SearchDocument[] indexMatches = new SearchDocument[indexMatchLength]; for (int j = 0; j < indexMatchLength; j++) { indexMatches[j] = participant.getDocument(indexMatchPaths[j]); } SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant); participant.locateMatches(matches, pattern, scope, requestor, monitor==null ? null : new SubProgressMonitor(monitor, 50)); } } finally { requestor.exitParticipant(participant); participant.doneSearching(); } } } finally { requestor.endReporting(); if (monitor != null) monitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (VERBOSE) { Util.verbose("BasicSearchEngine.search(SearchPattern, SearchParticipant[], IJavaSearchScope, SearchRequestor, IProgressMonitor)"); //$NON-NLS-1$ } findMatches(pattern, participants, scope, requestor, monitor); }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchParticipant.java
public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { MatchLocator matchLocator = new MatchLocator( pattern, requestor, scope, monitor ); /* eliminating false matches and locating them */ if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); matchLocator.locateMatches(indexMatches); }
// in search/org/eclipse/jdt/internal/core/search/matching/ClassFileMatchLocator.java
public void locateMatches(MatchLocator locator, ClassFile classFile, IBinaryType info) throws CoreException { SearchPattern pattern = locator.pattern; // check annotations references matchAnnotations(pattern, locator, classFile, info); // check class definition BinaryType binaryType = (BinaryType) classFile.getType(); if (matchBinary(pattern, info, null)) { binaryType = new ResolvedBinaryType((JavaElement) binaryType.getParent(), binaryType.getElementName(), binaryType.getKey()); locator.reportBinaryMemberDeclaration(null, binaryType, null, info, SearchMatch.A_ACCURATE); return; } // Define arrays to store methods/fields from binary type if necessary IBinaryMethod[] binaryMethods = info.getMethods(); int bMethodsLength = binaryMethods == null ? 0 : binaryMethods.length; IBinaryMethod[] unresolvedMethods = null; char[][] binaryMethodSignatures = null; boolean hasUnresolvedMethods = false; // Get fields from binary type info IBinaryField[] binaryFields = info.getFields(); int bFieldsLength = binaryFields == null ? 0 : binaryFields.length; IBinaryField[] unresolvedFields = null; boolean hasUnresolvedFields = false; // Report as many accurate matches as possible int accuracy = SearchMatch.A_ACCURATE; boolean mustResolve = pattern.mustResolve; if (mustResolve) { BinaryTypeBinding binding = locator.cacheBinaryType(binaryType, info); if (binding != null) { // filter out element not in hierarchy scope if (!locator.typeInHierarchy(binding)) return; // Search matches on resolved methods MethodBinding[] availableMethods = binding.availableMethods(); int aMethodsLength = availableMethods == null ? 0 : availableMethods.length; hasUnresolvedMethods = bMethodsLength != aMethodsLength; for (int i = 0; i < aMethodsLength; i++) { MethodBinding method = availableMethods[i]; char[] methodSignature = method.genericSignature(); if (methodSignature == null) methodSignature = method.signature(); // Report the match if possible int level = locator.patternLocator.resolveLevel(method); if (level != PatternLocator.IMPOSSIBLE_MATCH) { IMethod methodHandle = binaryType.getMethod( new String(method.isConstructor() ? binding.compoundName[binding.compoundName.length-1] : method.selector), CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(methodSignature)))); accuracy = level == PatternLocator.ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE; locator.reportBinaryMemberDeclaration(null, methodHandle, method, info, accuracy); } // Remove method from unresolved list if (hasUnresolvedMethods) { if (binaryMethodSignatures == null) { // Store binary method signatures to avoid multiple computation binaryMethodSignatures = new char[bMethodsLength][]; for (int j=0; j<bMethodsLength; j++) { IBinaryMethod binaryMethod = binaryMethods[j]; char[] signature = binaryMethod.getGenericSignature(); if (signature == null) signature = binaryMethod.getMethodDescriptor(); binaryMethodSignatures[j] = signature; } } for (int j=0; j<bMethodsLength; j++) { if (CharOperation.equals(binaryMethods[j].getSelector(), method.selector) && CharOperation.equals(binaryMethodSignatures[j], methodSignature)) { if (unresolvedMethods == null) { System.arraycopy(binaryMethods, 0, unresolvedMethods = new IBinaryMethod[bMethodsLength], 0, bMethodsLength); } unresolvedMethods[j] = null; break; } } } } // Search matches on resolved fields FieldBinding[] availableFields = binding.availableFields(); int aFieldsLength = availableFields == null ? 0 : availableFields.length; hasUnresolvedFields = bFieldsLength != aFieldsLength; for (int i = 0; i < aFieldsLength; i++) { FieldBinding field = availableFields[i]; // Report the match if possible int level = locator.patternLocator.resolveLevel(field); if (level != PatternLocator.IMPOSSIBLE_MATCH) { IField fieldHandle = binaryType.getField(new String(field.name)); accuracy = level == PatternLocator.ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE; locator.reportBinaryMemberDeclaration(null, fieldHandle, field, info, accuracy); } // Remove the field from unresolved list if (hasUnresolvedFields) { for (int j=0; j<bFieldsLength; j++) { if ( CharOperation.equals(binaryFields[j].getName(), field.name)) { if (unresolvedFields == null) { System.arraycopy(binaryFields, 0, unresolvedFields = new IBinaryField[bFieldsLength], 0, bFieldsLength); } unresolvedFields[j] = null; break; } } } } // If all methods/fields were accurate then returns now if (!hasUnresolvedMethods && !hasUnresolvedFields) { return; } } accuracy = SearchMatch.A_INACCURATE; } // Report inaccurate methods if (mustResolve) binaryMethods = unresolvedMethods; bMethodsLength = binaryMethods == null ? 0 : binaryMethods.length; for (int i=0; i < bMethodsLength; i++) { IBinaryMethod method = binaryMethods[i]; if (method == null) continue; // impossible match or already reported as accurate if (matchBinary(pattern, method, info)) { char[] name; if (method.isConstructor()) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=329727 // We don't need the enclosing type name for the constructor name name = info.getSourceName(); } else { name = method.getSelector(); } String selector = new String(name); char[] methodSignature = binaryMethodSignatures == null ? null : binaryMethodSignatures[i]; if (methodSignature == null) { methodSignature = method.getGenericSignature(); if (methodSignature == null) methodSignature = method.getMethodDescriptor(); } String[] parameterTypes = CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(methodSignature))); IMethod methodHandle = binaryType.getMethod(selector, parameterTypes); methodHandle = new ResolvedBinaryMethod(binaryType, selector, parameterTypes, methodHandle.getKey()); locator.reportBinaryMemberDeclaration(null, methodHandle, null, info, accuracy); } } // Report inaccurate fields if (mustResolve) binaryFields = unresolvedFields; bFieldsLength = binaryFields == null ? 0 : binaryFields.length; for (int i=0; i<bFieldsLength; i++) { IBinaryField field = binaryFields[i]; if (field == null) continue; // impossible match or already reported as accurate if (matchBinary(pattern, field, info)) { String fieldName = new String(field.getName()); IField fieldHandle = binaryType.getField(fieldName); fieldHandle = new ResolvedBinaryField(binaryType, fieldName, fieldHandle.getKey()); locator.reportBinaryMemberDeclaration(null, fieldHandle, null, info, accuracy); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/ClassFileMatchLocator.java
private void matchAnnotations(SearchPattern pattern, MatchLocator locator, ClassFile classFile, IBinaryType binaryType) throws CoreException { // Only process TypeReference patterns switch (pattern.kind) { case TYPE_REF_PATTERN: break; case OR_PATTERN: SearchPattern[] patterns = ((OrPattern) pattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { matchAnnotations(patterns[i], locator, classFile, binaryType); } // $FALL-THROUGH$ - fall through default to return default: return; } TypeReferencePattern typeReferencePattern = (TypeReferencePattern) pattern; // Look for references in class annotations IBinaryAnnotation[] annotations = binaryType.getAnnotations(); BinaryType classFileBinaryType = (BinaryType) classFile.getType(); BinaryTypeBinding binaryTypeBinding = null; if (checkAnnotations(typeReferencePattern, annotations, binaryType.getTagBits())) { classFileBinaryType = new ResolvedBinaryType((JavaElement) classFileBinaryType.getParent(), classFileBinaryType.getElementName(), classFileBinaryType.getKey()); TypeReferenceMatch match = new TypeReferenceMatch(classFileBinaryType, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } // Look for references in methods annotations MethodInfo[] methods = (MethodInfo[]) binaryType.getMethods(); if (methods != null) { for (int i = 0, max = methods.length; i < max; i++) { MethodInfo method = methods[i]; if (checkAnnotations(typeReferencePattern, method.getAnnotations(), method.getTagBits())) { binaryTypeBinding = locator.cacheBinaryType(classFileBinaryType, binaryType); IMethod methodHandle = classFileBinaryType.getMethod( new String(method.isConstructor() ? binaryTypeBinding.compoundName[binaryTypeBinding.compoundName.length-1] : method.getSelector()), CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(method.getMethodDescriptor())))); TypeReferenceMatch match = new TypeReferenceMatch(methodHandle, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } } } // Look for references in fields annotations FieldInfo[] fields = (FieldInfo[]) binaryType.getFields(); if (fields != null) { for (int i = 0, max = fields.length; i < max; i++) { FieldInfo field = fields[i]; if (checkAnnotations(typeReferencePattern, field.getAnnotations(), field.getTagBits())) { IField fieldHandle = classFileBinaryType.getField(new String(field.getName())); TypeReferenceMatch match = new TypeReferenceMatch(fieldHandle, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { PatternLocator weakestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { int newLevel = this.patternLocators[i].matchLevel(importRef); if (newLevel == IMPOSSIBLE_MATCH) return; if (weakestPattern == null || newLevel < level) { weakestPattern = this.patternLocators[i]; level = newLevel; } } weakestPattern.matchReportImportRef(importRef, binding, element, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { PatternLocator weakestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { if (this.patternLocators[i].referenceType() == 0) return; // impossible match int newLevel = this.patternLocators[i].resolveLevel(reference); if (newLevel == IMPOSSIBLE_MATCH) return; if (weakestPattern == null || newLevel < level) { weakestPattern = this.patternLocators[i]; level = newLevel; } } weakestPattern.matchReportReference(reference, element, localElement, otherElements, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected IBinaryType getBinaryInfo(ClassFile classFile, IResource resource) throws CoreException { BinaryType binaryType = (BinaryType) classFile.getType(); if (classFile.isOpen()) return (IBinaryType) binaryType.getElementInfo(); // reuse the info from the java model cache // create a temporary info IBinaryType info; try { PackageFragment pkg = (PackageFragment) classFile.getParent(); PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent(); if (root.isArchive()) { // class file in a jar String classFileName = classFile.getElementName(); String classFilePath = Util.concatWith(pkg.names, classFileName, '/'); ZipFile zipFile = null; try { zipFile = ((JarPackageFragmentRoot) root).getJar(); info = ClassFileReader.read(zipFile, classFilePath); } finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } } else { // class file in a directory info = Util.newClassFileReader(resource); } if (info == null) throw binaryType.newNotPresentException(); return info; } catch (ClassFormatException e) { //e.printStackTrace(); return null; } catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMatches, int start, int length) throws CoreException { initialize(javaProject, length); // create and resolve binding (equivalent to beginCompilation() in Compiler) boolean mustResolvePattern = this.pattern.mustResolve; boolean mustResolve = mustResolvePattern; this.patternLocator.mayBeGeneric = this.options.sourceLevel >= ClassFileConstants.JDK1_5; boolean bindingsWereCreated = mustResolve; try { for (int i = start, maxUnits = start + length; i < maxUnits; i++) { PossibleMatch possibleMatch = possibleMatches[i]; try { if (!parseAndBuildBindings(possibleMatch, mustResolvePattern)) continue; // Currently we only need to resolve over pattern flag if there's potential parameterized types if (this.patternLocator.mayBeGeneric) { // If pattern does not resolve then rely on possible match node set resolution // which may have been modified while locator was adding possible matches to it if (!mustResolvePattern && !mustResolve) { mustResolve = possibleMatch.nodeSet.mustResolve; bindingsWereCreated = mustResolve; } } else { // Reset matching node resolution with pattern one if there's no potential parameterized type // to minimize side effect on previous search behavior possibleMatch.nodeSet.mustResolve = mustResolvePattern; } // possible match node resolution has been merged with pattern one, so rely on it to know // whether we need to process compilation unit now or later if (!possibleMatch.nodeSet.mustResolve) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } process(possibleMatch, bindingsWereCreated); if (this.numberOfMatches>0 && this.matchesToProcess[this.numberOfMatches-1] == possibleMatch) { // forget last possible match as it was processed this.numberOfMatches--; } } } finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); } } if (mustResolve) this.lookupEnvironment.completeTypeBindings(); // create hierarchy resolver if needed IType focusType = getFocusType(); if (focusType == null) { this.hierarchyResolver = null; } else if (!createHierarchyResolver(focusType, possibleMatches)) { // focus type is not visible, use the super type names instead of the bindings if (computeSuperTypeNames(focusType) == null) return; } } catch (AbortCompilation e) { bindingsWereCreated = false; } if (!mustResolve) { return; } // possible match resolution for (int i = 0; i < this.numberOfMatches; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); PossibleMatch possibleMatch = this.matchesToProcess[i]; this.matchesToProcess[i] = null; // release reference to processed possible match try { process(possibleMatch, bindingsWereCreated); } catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatchSet matchSet, int expected) throws CoreException { PossibleMatch[] possibleMatches = matchSet.getPossibleMatches(javaProject.getPackageFragmentRoots()); int length = possibleMatches.length; // increase progress from duplicate matches not stored in matchSet while adding... if (this.progressMonitor != null && expected>length) { this.progressWorked += expected-length; this.progressMonitor.worked( expected-length); } // locate matches (processed matches are limited to avoid problem while using VM default memory heap size) for (int index = 0; index < length;) { int max = Math.min(MAX_AT_ONCE, length - index); locateMatches(javaProject, possibleMatches, index, max); index += max; } this.patternLocator.clear(); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public void locateMatches(SearchDocument[] searchDocuments) throws CoreException { if (this.patternLocator == null) return; int docsLength = searchDocuments.length; int progressLength = docsLength; if (BasicSearchEngine.VERBOSE) { System.out.println("Locating matches in documents ["); //$NON-NLS-1$ for (int i = 0; i < docsLength; i++) System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$ System.out.println("]"); //$NON-NLS-1$ } IJavaProject[] javaModelProjects = null; if (this.searchPackageDeclaration) { javaModelProjects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); progressLength += javaModelProjects.length; } // init infos for progress increasing int n = progressLength<1000 ? Math.min(Math.max(progressLength/200+1, 2),4) : 5 *(progressLength/1000); this.progressStep = progressLength < n ? 1 : progressLength / n; // step should not be 0 this.progressWorked = 0; // extract working copies ArrayList copies = new ArrayList(); for (int i = 0; i < docsLength; i++) { SearchDocument document = searchDocuments[i]; if (document instanceof WorkingCopyDocument) { copies.add(((WorkingCopyDocument)document).workingCopy); } } int copiesLength = copies.size(); this.workingCopies = new org.eclipse.jdt.core.ICompilationUnit[copiesLength]; copies.toArray(this.workingCopies); JavaModelManager manager = JavaModelManager.getJavaModelManager(); this.bindings = new SimpleLookupTable(); try { // optimize access to zip files during search operation manager.cacheZipFiles(this); // initialize handle factory (used as a cache of handles so as to optimize space) if (this.handleFactory == null) this.handleFactory = new HandleFactory(); if (this.progressMonitor != null) { this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$ } // initialize pattern for polymorphic search (i.e. method reference pattern) this.patternLocator.initializePolymorphicSearch(this); JavaProject previousJavaProject = null; PossibleMatchSet matchSet = new PossibleMatchSet(); Util.sort(searchDocuments, new Util.Comparer() { public int compare(Object a, Object b) { return ((SearchDocument)a).getPath().compareTo(((SearchDocument)b).getPath()); } }); int displayed = 0; // progress worked displayed String previousPath = null; SearchParticipant searchParticipant = null; for (int i = 0; i < docsLength; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // skip duplicate paths SearchDocument searchDocument = searchDocuments[i]; if (searchParticipant == null) { searchParticipant = searchDocument.getParticipant(); } searchDocuments[i] = null; // free current document String pathString = searchDocument.getPath(); if (i > 0 && pathString.equals(previousPath)) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; } previousPath = pathString; Openable openable; org.eclipse.jdt.core.ICompilationUnit workingCopy = null; if (searchDocument instanceof WorkingCopyDocument) { workingCopy = ((WorkingCopyDocument)searchDocument).workingCopy; openable = (Openable) workingCopy; } else { openable = this.handleFactory.createOpenable(pathString, this.scope); } if (openable == null) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; // match is outside classpath } // create new parser and lookup environment if this is a new project IResource resource = null; JavaProject javaProject = (JavaProject) openable.getJavaProject(); resource = workingCopy != null ? workingCopy.getResource() : openable.getResource(); if (resource == null) resource = javaProject.getProject(); // case of a file in an external jar or external folder if (!javaProject.equals(previousJavaProject)) { // locate matches in previous project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, i-displayed); displayed = i; } catch (JavaModelException e) { // problem with classpath in this project -> skip it } matchSet.reset(); } previousJavaProject = javaProject; } matchSet.add(new PossibleMatch(this, resource, openable, searchDocument,this.pattern.mustResolve)); } // last project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, docsLength-displayed); } catch (JavaModelException e) { // problem with classpath in last project -> ignore } } if (this.searchPackageDeclaration) { locatePackageDeclarations(searchParticipant, javaModelProjects); } } finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchParticipant participant, IJavaProject[] projects) throws CoreException { locatePackageDeclarations(this.pattern, participant, projects); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); try { if (BasicSearchEngine.VERBOSE) System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.parser.nodeSet = possibleMatch.nodeSet; CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult); if (parsedUnit != null) { if (!parsedUnit.isEmpty()) { if (mustResolve) { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } if (hasAlreadyDefinedType(parsedUnit)) return false; // skip type has it is hidden so not visible getMethodBodies(parsedUnit, possibleMatch.nodeSet); if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) { // special case: possible match node set force resolution although pattern does not // => we need to build types for this compilation unit this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } } // add the possibleMatch with its parsedUnit to matchesToProcess possibleMatch.parsedUnit = parsedUnit; int size = this.matchesToProcess.length; if (this.numberOfMatches == size) System.arraycopy(this.matchesToProcess, 0, this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0, this.numberOfMatches); this.matchesToProcess[this.numberOfMatches++] = possibleMatch; } } finally { this.parser.nodeSet = null; } return true; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void process(PossibleMatch possibleMatch, boolean bindingsWereCreated) throws CoreException { this.currentPossibleMatch = possibleMatch; CompilationUnitDeclaration unit = possibleMatch.parsedUnit; try { if (unit.isEmpty()) { if (this.currentPossibleMatch.openable instanceof ClassFile) { ClassFile classFile = (ClassFile) this.currentPossibleMatch.openable; IBinaryType info = null; try { info = getBinaryInfo(classFile, classFile.resource()); } catch (CoreException ce) { // Do nothing } if (info != null) { boolean mayBeGeneric = this.patternLocator.mayBeGeneric; this.patternLocator.mayBeGeneric = false; // there's no longer generic in class files try { new ClassFileMatchLocator().locateMatches(this, classFile, info); } finally { this.patternLocator.mayBeGeneric = mayBeGeneric; } } } return; } if (hasAlreadyDefinedType(unit)) return; // skip type has it is hidden so not visible // Move getMethodBodies to #parseAndBuildings(...) method to allow possible match resolution management //getMethodBodies(unit); boolean mustResolve = (this.pattern.mustResolve || possibleMatch.nodeSet.mustResolve); if (bindingsWereCreated && mustResolve) { if (unit.types != null) { if (BasicSearchEngine.VERBOSE) System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.lookupEnvironment.unitBeingCompleted = unit; reduceParseTree(unit); if (unit.scope != null) { // fault in fields & methods unit.scope.faultInTypes(); } unit.resolve(); } else if (unit.isPackageInfo()) { if (BasicSearchEngine.VERBOSE) System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ unit.resolve(); } } reportMatching(unit, mustResolve); } catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } } finally { this.lookupEnvironment.unitBeingCompleted = null; this.currentPossibleMatch = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void report(SearchMatch match) throws CoreException { if (match == null) { if (BasicSearchEngine.VERBOSE) { System.out.println("Cannot report a null match!!!"); //$NON-NLS-1$ } return; } if (filterEnum(match)){ if (BasicSearchEngine.VERBOSE) { System.out.println("Filtered package with name enum"); //$NON-NLS-1$ } return; } long start = -1; if (BasicSearchEngine.VERBOSE) { start = System.currentTimeMillis(); System.out.println("Reporting match"); //$NON-NLS-1$ System.out.println("\tResource: " + match.getResource());//$NON-NLS-1$ System.out.println("\tPositions: [offset=" + match.getOffset() + ", length=" + match.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { if (this.parser != null && match.getOffset() > 0 && match.getLength() > 0 && !(match.getElement() instanceof BinaryMember)) { String selection = new String(this.parser.scanner.source, match.getOffset(), match.getLength()); System.out.println("\tSelection: -->" + selection + "<--"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } try { JavaElement javaElement = (JavaElement)match.getElement(); System.out.println("\tJava element: "+ javaElement.toStringWithAncestors()); //$NON-NLS-1$ if (!javaElement.exists()) { System.out.println("\t\tWARNING: this element does NOT exist!"); //$NON-NLS-1$ } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } if (match instanceof ReferenceMatch) { try { ReferenceMatch refMatch = (ReferenceMatch) match; JavaElement local = (JavaElement) refMatch.getLocalElement(); if (local != null) { System.out.println("\tLocal element: "+ local.toStringWithAncestors()); //$NON-NLS-1$ } if (match instanceof TypeReferenceMatch) { IJavaElement[] others = ((TypeReferenceMatch) refMatch).getOtherElements(); if (others != null) { int length = others.length; if (length > 0) { System.out.println("\tOther elements:"); //$NON-NLS-1$ for (int i=0; i<length; i++) { JavaElement other = (JavaElement) others[i]; System.out.println("\t\t- "+ other.toStringWithAncestors()); //$NON-NLS-1$ } } } } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } } System.out.println(match.getAccuracy() == SearchMatch.A_ACCURATE ? "\tAccuracy: EXACT_MATCH" //$NON-NLS-1$ : "\tAccuracy: POTENTIAL_MATCH"); //$NON-NLS-1$ System.out.print("\tRule: "); //$NON-NLS-1$ if (match.isExact()) { System.out.print("EXACT"); //$NON-NLS-1$ } else if (match.isEquivalent()) { System.out.print("EQUIVALENT"); //$NON-NLS-1$ } else if (match.isErasure()) { System.out.print("ERASURE"); //$NON-NLS-1$ } else { System.out.print("INVALID RULE"); //$NON-NLS-1$ } if (match instanceof MethodReferenceMatch) { MethodReferenceMatch methodReferenceMatch = (MethodReferenceMatch) match; if (methodReferenceMatch.isSuperInvocation()) { System.out.print("+SUPER INVOCATION"); //$NON-NLS-1$ } if (methodReferenceMatch.isImplicit()) { System.out.print("+IMPLICIT"); //$NON-NLS-1$ } if (methodReferenceMatch.isSynthetic()) { System.out.print("+SYNTHETIC"); //$NON-NLS-1$ } } System.out.println("\n\tRaw: "+match.isRaw()); //$NON-NLS-1$ } this.requestor.acceptSearchMatch(match); if (BasicSearchEngine.VERBOSE) this.resultCollectorTime += System.currentTimeMillis()-start; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateTypeReference(SearchMatch match, ASTNode typeRef, char[] name) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; int sourceStart = typeRef.sourceStart; int sourceEnd = typeRef.sourceEnd; // Compute source positions of the qualified reference if (name != null) { Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); int token = -1; int currentPosition; do { currentPosition = scanner.currentPosition; try { token = scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } if (token == TerminalTokens.TokenNameIdentifier && this.pattern.matchesName(name, scanner.getCurrentTokenSource())) { int length = scanner.currentPosition-currentPosition; match.setOffset(currentPosition); match.setLength(length); report(match); return; } } while (token != TerminalTokens.TokenNameEOF); } // Report match match.setOffset(sourceStart); match.setLength(sourceEnd-sourceStart+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateParameterizedMethodReference(SearchMatch match, ASTNode statement, TypeReference[] typeArguments) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; // If there's type arguments, look for end (i.e. char '>') of last one. int start = match.getOffset(); if (typeArguments != null && typeArguments.length > 0) { boolean isErasureMatch= (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).isErasureMatch() : ((JavaSearchPattern)this.pattern).isErasureMatch(); if (!isErasureMatch) { // Initialize scanner Scanner scanner = this.parser.scanner; char[] source = this.currentPossibleMatch.getContents(); scanner.setSource(source); // Search previous opening '<' start = typeArguments[0].sourceStart; int end = statement.sourceEnd; scanner.resetTo(start, end); int lineStart = start; try { linesUp: while (true) { while (scanner.source[scanner.currentPosition] != '\n') { scanner.currentPosition--; if (scanner.currentPosition == 0) break linesUp; } lineStart = scanner.currentPosition+1; scanner.resetTo(lineStart, end); while (!scanner.atEnd()) { if (scanner.getNextToken() == TerminalTokens.TokenNameLESS) { start = scanner.getCurrentTokenStartPosition(); break linesUp; } } end = lineStart - 2; scanner.currentPosition = end; } } catch (InvalidInputException ex) { // give up } } } // Report match match.setOffset(start); match.setLength(statement.sourceEnd-start+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateParameterizedTypeReference(SearchMatch match, TypeReference typeRef, int index, TypeReference[] typeArguments) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; // If there's type arguments, look for end (i.e. char '>') of last one. int end = typeRef.sourceEnd; if (typeArguments != null) { boolean shouldMatchErasure= (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).isErasureMatch() : ((JavaSearchPattern)this.pattern).isErasureMatch(); boolean hasSignatures = (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).hasSignatures() : ((JavaSearchPattern)this.pattern).hasSignatures(); if (shouldMatchErasure || !hasSignatures) { // if pattern is erasure only, then select the end of the reference if (typeRef instanceof QualifiedTypeReference && index >= 0) { long[] positions = ((QualifiedTypeReference) typeRef).sourcePositions; end = (int) positions[index]; } else if (typeRef instanceof ArrayTypeReference) { end = ((ArrayTypeReference) typeRef).originalSourceEnd; } } else { // Initialize scanner Scanner scanner = this.parser.scanner; char[] source = this.currentPossibleMatch.getContents(); scanner.setSource(source); // Set scanner position at end of last type argument scanner.resetTo(end, source.length-1); int depth = 0; for (int i=typeArguments.length-1; i>=0; i--) { if (typeArguments[i] != null) { long lastTypeArgInfo = findLastTypeArgumentInfo(typeArguments[i]); depth = (int) (lastTypeArgInfo >>> 32)+1; scanner.resetTo(((int)lastTypeArgInfo)+1, scanner.eofPosition-1); break; } } // Now, scan to search next closing '>' while (depth-- > 0) { while (!scanner.atEnd()) { if (scanner.getNextChar() == '>') { end = scanner.currentPosition - 1; break; } } } } } // Report match match.setLength(end-match.getOffset()+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateEnumConstructorReference(SearchMatch match, FieldDeclaration field, AllocationExpression allocation) throws CoreException { // Verify that field declaration is really an enum constant if (allocation == null || allocation.enumConstant == null) { report(match); return; } // Get scan area int sourceStart = match.getOffset()+match.getLength(); if (allocation.arguments != null && allocation.arguments.length > 0) { sourceStart = allocation.arguments[allocation.arguments.length-1].sourceEnd+1; } int sourceEnd = field.declarationSourceEnd; if (allocation instanceof QualifiedAllocationExpression) { QualifiedAllocationExpression qualifiedAllocation = (QualifiedAllocationExpression) allocation; if (qualifiedAllocation.anonymousType != null) { sourceEnd = qualifiedAllocation.anonymousType.sourceStart - 1; } } // Scan to find last closing parenthesis Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); try { int token = scanner.getNextToken(); while (token != TerminalTokens.TokenNameEOF) { if (token == TerminalTokens.TokenNameRPAREN) { sourceEnd = scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException iie) { // give up } // Report match match.setLength(sourceEnd-match.getOffset()+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateFieldReference(SearchMatch[] matches, QualifiedNameReference qNameRef) throws CoreException { if (matches == null) return; // there's nothing to accurate in this case int matchesLength = matches.length; int sourceStart = qNameRef.sourceStart; int sourceEnd = qNameRef.sourceEnd; char[][] tokens = qNameRef.tokens; // compute source positions of the qualified reference Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); int sourceLength = sourceEnd-sourceStart+1; int refSourceStart = -1, refSourceEnd = -1; int length = tokens.length; int token = -1; int previousValid = -1; int i = 0; int index = 0; do { int currentPosition = scanner.currentPosition; // read token try { token = scanner.getNextToken(); } catch (InvalidInputException e) { //ignore } if (token != TerminalTokens.TokenNameEOF) { char[] currentTokenSource = scanner.getCurrentTokenSource(); boolean equals = false; while (i < length && !(equals = this.pattern.matchesName(tokens[i++], currentTokenSource))){/*empty*/} if (equals && (previousValid == -1 || previousValid == i - 2)) { previousValid = i - 1; if (refSourceStart == -1) refSourceStart = currentPosition; refSourceEnd = scanner.currentPosition - 1; } else { i = 0; refSourceStart = -1; previousValid = -1; } // read '.' try { token = scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } } SearchMatch match = matches[index]; if (match != null && match.getRule() != 0) { if (!encloses((IJavaElement)match.getElement())) return; // accept reference if (refSourceStart != -1) { match.setOffset(refSourceStart); match.setLength(refSourceEnd-refSourceStart+1); report(match); } else { match.setOffset(sourceStart); match.setLength(sourceLength); report(match); } i = 0; } refSourceStart = -1; previousValid = -1; if (index < matchesLength - 1) { index++; } } while (token != TerminalTokens.TokenNameEOF); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportBinaryMemberDeclaration(IResource resource, IMember binaryMember, Binding binaryMemberBinding, IBinaryType info, int accuracy) throws CoreException { ClassFile classFile = (ClassFile) binaryMember.getClassFile(); ISourceRange range = classFile.isOpen() ? binaryMember.getNameRange() : SourceMapper.UNKNOWN_RANGE; if (range.getOffset() == -1) { BinaryType type = (BinaryType) classFile.getType(); String sourceFileName = type.sourceFileName(info); if (sourceFileName != null) { SourceMapper mapper = classFile.getSourceMapper(); if (mapper != null) { char[] contents = mapper.findSource(type, sourceFileName); if (contents != null) range = mapper.mapSource(type, contents, info, binaryMember); } } } if (resource == null) resource = this.currentPossibleMatch.resource; SearchMatch match = newDeclarationMatch(binaryMember, binaryMemberBinding, accuracy, range.getOffset(), range.getLength(), getParticipant(), resource); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(AbstractMethodDeclaration method, TypeDeclaration type, IJavaElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException { IJavaElement enclosingElement = null; // report method declaration itself if (accuracy > -1) { enclosingElement = createHandle(method, parent); if (enclosingElement != null) { // skip if unable to find method // compute source positions of the selector Scanner scanner = this.parser.scanner; int nameSourceStart = method.sourceStart; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(nameSourceStart, method.sourceEnd); try { scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } if (encloses(enclosingElement)) { SearchMatch match = null; if (method.isDefaultConstructor()) { // Use type for match associated element as default constructor does not exist in source int offset = type.sourceStart; match = this.patternLocator.newDeclarationMatch(type, parent, type.binding, accuracy, type.sourceEnd-offset+1, this); } else { int length = scanner.currentPosition - nameSourceStart; match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.binding, accuracy, length, this); } if (match != null) { report(match); } } } } // handle nodes for the local type first if ((method.bits & ASTNode.HasLocalType) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } // Traverse method declaration to report matches both in local types declaration // and in local variables declaration ASTNode[] nodes = typeInHierarchy ? nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd) : null; boolean report = (this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0 && encloses(enclosingElement); MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, report ? nodes : null, nodeSet, this); try { method.traverse(declarationVisitor, (ClassScope) null); } catch (WrappedCoreException e) { throw e.coreException; } // Report all nodes and remove them if (nodes != null) { int length = nodes.length; for (int i = 0; i < length; i++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]); if (report && level != null) { this.patternLocator.matchReportReference(nodes[i], enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), method.binding, level.intValue(), this); } } } } // report the type parameters TypeParameter[] typeParameters = method.typeParameters(); if (typeParameters != null) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (enclosingElement != null) { reportMatching(typeParameters, enclosingElement, parent, method.binding, nodeSet); } } // report annotations if (method.annotations != null) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (enclosingElement != null) { reportMatching(method.annotations, enclosingElement, null, method.binding, nodeSet, true, true); } } // references in this method if (typeInHierarchy) { ASTNode[] nodes = nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd); if (nodes != null) { if ((this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (encloses(enclosingElement)) { if (this.pattern.mustResolve) { // Visit only if the pattern must resolve MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, nodes, nodeSet, this); method.traverse(declarationVisitor, (ClassScope) null); int length = nodes.length; for (int i = 0; i < length; i++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]); if (level != null) { // ensure that the reference has not been already reported while visiting this.patternLocator.matchReportReference(nodes[i], enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), method.binding, level.intValue(), this); } } } else { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (level != null) { // ensure that the reference has not been already reported while visiting this.patternLocator.matchReportReference(node, enclosingElement, null, null, method.binding, level.intValue(), this); } } } return; } } // Remove all remaining nodes for (int i = 0, l = nodes.length; i < l; i++) { nodeSet.matchingNodes.removeKey(nodes[i]); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(Annotation[] annotations, IJavaElement enclosingElement, IJavaElement[] otherElements, Binding elementBinding, MatchingNodeSet nodeSet, boolean matchedContainer, boolean enclosesElement) throws CoreException { for (int i=0, al=annotations.length; i<al; i++) { Annotation annotationType = annotations[i]; IJavaElement localAnnotation = null; IJavaElement[] otherAnnotations = null; int length = otherElements == null ? 0 : otherElements.length; boolean handlesCreated = false; // Look for annotation type ref TypeReference typeRef = annotationType.type; Integer level = (Integer) nodeSet.matchingNodes.removeKey(typeRef); if (level != null && enclosesElement && matchedContainer) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; this.patternLocator.matchReportReference(typeRef, enclosingElement, localAnnotation, otherAnnotations, elementBinding, level.intValue(), this); } // Look for attribute ref MemberValuePair[] pairs = annotationType.memberValuePairs(); for (int j = 0, pl = pairs.length; j < pl; j++) { MemberValuePair pair = pairs[j]; level = (Integer) nodeSet.matchingNodes.removeKey(pair); if (level != null && enclosesElement) { ASTNode reference = (annotationType instanceof SingleMemberAnnotation) ? (ASTNode) annotationType: pair; if (!handlesCreated) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; } this.patternLocator.matchReportReference(reference, enclosingElement, localAnnotation, otherAnnotations, pair.binding, level.intValue(), this); } } // Look for reference inside annotation ASTNode[] nodes = nodeSet.matchingNodes(annotationType.sourceStart, annotationType.declarationSourceEnd); if (nodes != null) { if (!matchedContainer) { for (int j = 0, nl = nodes.length; j < nl; j++) { nodeSet.matchingNodes.removeKey(nodes[j]); } } else { for (int j = 0, nl = nodes.length; j < nl; j++) { ASTNode node = nodes[j]; level = (Integer) nodeSet.matchingNodes.removeKey(node); if (enclosesElement) { if (!handlesCreated) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; } this.patternLocator.matchReportReference(node, enclosingElement, localAnnotation, otherAnnotations, elementBinding, level.intValue(), this); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(CompilationUnitDeclaration unit, boolean mustResolve) throws CoreException { MatchingNodeSet nodeSet = this.currentPossibleMatch.nodeSet; boolean locatorMustResolve = this.patternLocator.mustResolve; if (nodeSet.mustResolve) this.patternLocator.mustResolve = true; if (BasicSearchEngine.VERBOSE) { System.out.println("Report matching: "); //$NON-NLS-1$ int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize; System.out.print(" - node set: accurate="+ size); //$NON-NLS-1$ size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize; System.out.println(", possible="+size); //$NON-NLS-1$ System.out.print(" - must resolve: "+mustResolve); //$NON-NLS-1$ System.out.print(" (locator: "+this.patternLocator.mustResolve); //$NON-NLS-1$ System.out.println(", nodeSet: "+nodeSet.mustResolve+')'); //$NON-NLS-1$ System.out.println(" - fine grain flags="+ JavaSearchPattern.getFineGrainFlagString(this.patternLocator.fineGrain())); //$NON-NLS-1$ } if (mustResolve) { this.unitScope= unit.scope.compilationUnitScope(); // move the possible matching nodes that exactly match the search pattern to the matching nodes set Object[] nodes = nodeSet.possibleMatchingNodesSet.values; for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = (ASTNode) nodes[i]; if (node == null) continue; if (node instanceof ImportReference) { // special case for import refs: they don't know their binding // import ref cannot be in the hierarchy of a type if (this.hierarchyResolver != null) continue; ImportReference importRef = (ImportReference) node; Binding binding = (importRef.bits & ASTNode.OnDemand) != 0 ? this.unitScope.getImport(CharOperation.subarray(importRef.tokens, 0, importRef.tokens.length), true, importRef.isStatic()) : this.unitScope.getImport(importRef.tokens, false, importRef.isStatic()); this.patternLocator.matchLevelAndReportImportRef(importRef, binding, this); } else { nodeSet.addMatch(node, this.patternLocator.resolveLevel(node)); } } nodeSet.possibleMatchingNodesSet = new SimpleSet(3); if (BasicSearchEngine.VERBOSE) { int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize; System.out.print(" - node set: accurate="+size); //$NON-NLS-1$ size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize; System.out.println(", possible="+size); //$NON-NLS-1$ } } else { this.unitScope = null; } if (nodeSet.matchingNodes.elementSize == 0) return; // no matching nodes were found this.methodHandles = new HashSet(); boolean matchedUnitContainer = (this.matchContainer & PatternLocator.COMPILATION_UNIT_CONTAINER) != 0; // report references in javadoc if (unit.javadoc != null) { ASTNode[] nodes = nodeSet.matchingNodes(unit.javadoc.sourceStart, unit.javadoc.sourceEnd); if (nodes != null) { if (!matchedUnitContainer) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { IJavaElement element = createPackageDeclarationHandle(unit); for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (encloses(element)) { this.patternLocator.matchReportReference(node, element, null, null, null/*no binding*/, level.intValue(), this); } } } } } if (matchedUnitContainer) { ImportReference pkg = unit.currentPackage; if (pkg != null && pkg.annotations != null) { IJavaElement element = createPackageDeclarationHandle(unit); if (element != null) { reportMatching(pkg.annotations, element, null, null, nodeSet, true, encloses(element)); } } ImportReference[] imports = unit.imports; if (imports != null) { for (int i = 0, l = imports.length; i < l; i++) { ImportReference importRef = imports[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(importRef); if (level != null) { this.patternLocator.matchReportImportRef(importRef, null /*no binding*/, createImportHandle(importRef), level.intValue(), this); } } } } TypeDeclaration[] types = unit.types; if (types != null) { for (int i = 0, l = types.length; i < l; i++) { if (nodeSet.matchingNodes.elementSize == 0) return; // reported all the matching nodes TypeDeclaration type = types[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(type); int accuracy = (level != null && matchedUnitContainer) ? level.intValue() : -1; reportMatching(type, null, accuracy, nodeSet, 1); } } // Clear handle cache this.methodHandles = null; this.bindings.removeKey(this.pattern); this.patternLocator.mustResolve = locatorMustResolve; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(FieldDeclaration field, FieldDeclaration[] otherFields, TypeDeclaration type, IJavaElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException { IJavaElement enclosingElement = null; if (accuracy > -1) { enclosingElement = createHandle(field, type, parent); if (encloses(enclosingElement)) { int offset = field.sourceStart; SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset, field.sourceEnd-offset+1); if (field.initialization instanceof AllocationExpression) { reportAccurateEnumConstructorReference(match, field, (AllocationExpression) field.initialization); } else { report(match); } } } // handle the nodes for the local type first if ((field.bits & ASTNode.HasLocalType) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } // Traverse field declaration(s) to report matches both in local types declaration // and in local variables declaration int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position; ASTNode[] nodes = typeInHierarchy ? nodeSet.matchingNodes(field.sourceStart, fieldEnd) : null; boolean report = (this.matchContainer & PatternLocator.FIELD_CONTAINER) != 0 && encloses(enclosingElement); MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, report ? nodes : null, nodeSet, this); try { field.traverse(declarationVisitor, (MethodScope) null); } catch (WrappedCoreException e) { throw e.coreException; } // Report all nodes and remove them if (nodes != null) { int length = nodes.length; for (int i = 0; i < length; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (report && level != null) { if (node instanceof TypeDeclaration) { // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174) AllocationExpression allocation = ((TypeDeclaration)node).allocation; if (allocation != null && allocation.enumConstant != null) { node = field; } } this.patternLocator.matchReportReference(node, enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), field.binding, level.intValue(), this); } } } } // report annotations IJavaElement[] otherElements = null; if (field.annotations != null) { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } if (otherFields != null) { otherElements = createHandles(otherFields, type, parent); } reportMatching(field.annotations, enclosingElement, otherElements, field.binding, nodeSet, true, true); } if (typeInHierarchy) { // Look at field declaration if (field.endPart1Position != 0) { // not necessary if field is an initializer ASTNode[] nodes = nodeSet.matchingNodes(field.declarationSourceStart, field.endPart1Position); if (nodes != null) { if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { if (enclosingElement == null) enclosingElement = createHandle(field, type, parent); if (encloses(enclosingElement)) { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (otherFields != null && otherElements == null) { otherElements = createHandles(otherFields, type, parent); } this.patternLocator.matchReportReference(node, enclosingElement, null, otherElements, field.binding, level.intValue(), this); } } } } } // Look in initializer int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position; ASTNode[] nodes = nodeSet.matchingNodes(field.sourceStart, fieldEnd); if (nodes != null) { if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) { nodeSet.matchingNodes.removeKey(nodes[i]); } } else { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } if (encloses(enclosingElement)) { MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, nodes, nodeSet, this); field.traverse(declarationVisitor, (MethodScope) null); int length = nodes.length; for (int i = 0; i < length; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (level != null) { // ensure that the reference has not been already reported while visiting if (node instanceof TypeDeclaration) { // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174) AllocationExpression allocation = ((TypeDeclaration)node).allocation; if (allocation != null && allocation.enumConstant != null) { node = field; } } this.patternLocator.matchReportReference(node, enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), field.binding, level.intValue(), this); } } return; } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(TypeDeclaration type, IJavaElement parent, int accuracy, MatchingNodeSet nodeSet, int occurrenceCount) throws CoreException { // create type handle IJavaElement enclosingElement = parent; if (enclosingElement == null) { enclosingElement = createTypeHandle(new String(type.name)); } else if (enclosingElement instanceof IType) { enclosingElement = ((IType) parent).getType(new String(type.name)); } else if (enclosingElement instanceof IMember) { IMember member = (IMember) parent; if (member.isBinary()) { enclosingElement = ((IClassFile)this.currentPossibleMatch.openable).getType(); } else { enclosingElement = member.getType(new String(type.name), occurrenceCount); } } if (enclosingElement == null) return; boolean enclosesElement = encloses(enclosingElement); // report the type declaration if (accuracy > -1 && enclosesElement) { int offset = type.sourceStart; SearchMatch match = this.patternLocator.newDeclarationMatch(type, enclosingElement, type.binding, accuracy, type.sourceEnd-offset+1, this); report(match); } boolean matchedClassContainer = (this.matchContainer & PatternLocator.CLASS_CONTAINER) != 0; // report the type parameters if (type.typeParameters != null) { reportMatching(type.typeParameters, enclosingElement, parent, type.binding, nodeSet); } // report annotations if (type.annotations != null) { reportMatching(type.annotations, enclosingElement, null, type.binding, nodeSet, matchedClassContainer, enclosesElement); } // report references in javadoc if (type.javadoc != null) { ASTNode[] nodes = nodeSet.matchingNodes(type.declarationSourceStart, type.sourceStart); if (nodes != null) { if (!matchedClassContainer) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (enclosesElement) { this.patternLocator.matchReportReference(node, enclosingElement, null, null, type.binding, level.intValue(), this); } } } } } // super types if ((type.bits & ASTNode.IsAnonymousType) != 0) { TypeReference superType = type.allocation.type; if (superType != null) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(superType); if (level != null && matchedClassContainer) this.patternLocator.matchReportReference(superType, enclosingElement, null, null, type.binding, level.intValue(), this); } } else { TypeReference superClass = type.superclass; if (superClass != null) { reportMatchingSuper(superClass, enclosingElement, type.binding, nodeSet, matchedClassContainer); } TypeReference[] superInterfaces = type.superInterfaces; if (superInterfaces != null) { for (int i = 0, l = superInterfaces.length; i < l; i++) { reportMatchingSuper(superInterfaces[i], enclosingElement, type.binding, nodeSet, matchedClassContainer); } } } // filter out element not in hierarchy scope boolean typeInHierarchy = type.binding == null || typeInHierarchy(type.binding); matchedClassContainer = matchedClassContainer && typeInHierarchy; // Visit fields FieldDeclaration[] fields = type.fields; if (fields != null) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported FieldDeclaration[] otherFields = null; int first = -1; int length = fields.length; for (int i = 0; i < length; i++) { FieldDeclaration field = fields[i]; boolean last = field.endPart2Position == 0 || field.declarationEnd == field.endPart2Position; // Store first index of multiple field declaration if (!last) { if (first == -1) { first = i; } } if (first >= 0) { // Store all multiple fields but first one for other elements if (i > first) { if (otherFields == null) { otherFields = new FieldDeclaration[length-i]; } otherFields[i-1-first] = field; } // On last field, report match with all other elements if (last) { for (int j=first; j<=i; j++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(fields[j]); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(fields[j], otherFields, type, enclosingElement, value, typeInHierarchy, nodeSet); } first = -1; otherFields = null; } } else { // Single field, report normally Integer level = (Integer) nodeSet.matchingNodes.removeKey(field); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(field, null, type, enclosingElement, value, typeInHierarchy, nodeSet); } } } // Visit methods AbstractMethodDeclaration[] methods = type.methods; if (methods != null) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported for (int i = 0, l = methods.length; i < l; i++) { AbstractMethodDeclaration method = methods[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(method); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(method, type, enclosingElement, value, typeInHierarchy, nodeSet); } } // Visit types TypeDeclaration[] memberTypes = type.memberTypes; if (memberTypes != null) { for (int i = 0, l = memberTypes.length; i < l; i++) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported TypeDeclaration memberType = memberTypes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(memberType); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(memberType, enclosingElement, value, nodeSet, 1); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(TypeParameter[] typeParameters, IJavaElement enclosingElement, IJavaElement parent, Binding binding, MatchingNodeSet nodeSet) throws CoreException { if (typeParameters == null) return; for (int i=0, l=typeParameters.length; i<l; i++) { TypeParameter typeParameter = typeParameters[i]; if (typeParameter != null) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(typeParameter); if (level != null) { if (level.intValue() > -1 && encloses(enclosingElement)) { int offset = typeParameter.sourceStart; SearchMatch match = this.patternLocator.newDeclarationMatch(typeParameter, enclosingElement, binding, level.intValue(), typeParameter.sourceEnd-offset+1, this); report(match); } } if (typeParameter.type != null) { level = (Integer) nodeSet.matchingNodes.removeKey(typeParameter.type); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeParameter.type, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeParameter.type instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference paramSTR = (ParameterizedSingleTypeReference) typeParameter.type; if (paramSTR.typeArguments != null) { int length = paramSTR.typeArguments.length; for (int k=0; k<length; k++) { TypeReference typeArgument = paramSTR.typeArguments[k]; level = (Integer) nodeSet.matchingNodes.removeKey(typeArgument); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeArgument, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeArgument instanceof Wildcard) { TypeReference wildcardBound = ((Wildcard) typeArgument).bound; if (wildcardBound != null) { level = (Integer) nodeSet.matchingNodes.removeKey(wildcardBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(wildcardBound, enclosingElement, localElement, null, binding, level.intValue(), this); } } } } } } } if (typeParameter.bounds != null) { for (int j=0, b=typeParameter.bounds.length; j<b; j++) { TypeReference typeParameterBound = typeParameter.bounds[j]; level = (Integer) nodeSet.matchingNodes.removeKey(typeParameterBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeParameterBound, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeParameterBound instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference paramSTR = (ParameterizedSingleTypeReference) typeParameterBound; if (paramSTR.typeArguments != null) { int length = paramSTR.typeArguments.length; for (int k=0; k<length; k++) { TypeReference typeArgument = paramSTR.typeArguments[k]; level = (Integer) nodeSet.matchingNodes.removeKey(typeArgument); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeArgument, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeArgument instanceof Wildcard) { TypeReference wildcardBound = ((Wildcard) typeArgument).bound; if (wildcardBound != null) { level = (Integer) nodeSet.matchingNodes.removeKey(wildcardBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(wildcardBound, enclosingElement, localElement, null, binding, level.intValue(), this); } } } } } } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatchingSuper(TypeReference superReference, IJavaElement enclosingElement, Binding elementBinding, MatchingNodeSet nodeSet, boolean matchedClassContainer) throws CoreException { ASTNode[] nodes = null; if (superReference instanceof ParameterizedSingleTypeReference || superReference instanceof ParameterizedQualifiedTypeReference) { long lastTypeArgumentInfo = findLastTypeArgumentInfo(superReference); nodes = nodeSet.matchingNodes(superReference.sourceStart, (int)lastTypeArgumentInfo); } if (nodes != null) { if ((this.matchContainer & PatternLocator.CLASS_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { if (encloses(enclosingElement)) for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); this.patternLocator.matchReportReference(node, enclosingElement, null, null, elementBinding, level.intValue(), this); } } } else if (encloses(enclosingElement)) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(superReference); if (level != null && matchedClassContainer) this.patternLocator.matchReportReference(superReference, enclosingElement, null, null, elementBinding, level.intValue(), this); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { int level = resolveLevel(binding); if (level >= INACCURATE_MATCH) { matchReportImportRef( importRef, binding, locator.createImportHandle(importRef), level == ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (locator.encloses(element)) { // default is to report a match as a regular ref. this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { this.match = null; int referenceType = referenceType(); int offset = reference.sourceStart; switch (referenceType) { case IJavaElement.PACKAGE_FRAGMENT: this.match = locator.newPackageReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.TYPE: this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.FIELD: this.match = locator.newFieldReferenceMatch(element, null, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.LOCAL_VARIABLE: this.match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.TYPE_PARAMETER: this.match = locator.newTypeParameterReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; } if (this.match != null) { locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { if (importRef.isStatic() && binding instanceof MethodBinding) { super.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { MethodBinding methodBinding = (reference instanceof MessageSend) ? ((MessageSend)reference).binding: ((elementBinding instanceof MethodBinding) ? (MethodBinding) elementBinding : null); if (this.isDeclarationOfReferencedMethodsPattern) { if (methodBinding == null) return; // need exact match to be able to open on type ref if (accuracy != SearchMatch.A_ACCURATE) return; // element that references the method must be included in the enclosing element DeclarationOfReferencedMethodsPattern declPattern = (DeclarationOfReferencedMethodsPattern) this.pattern; while (element != null && !declPattern.enclosingElement.equals(element)) element = element.getParent(); if (element != null) { reportDeclaration(methodBinding, locator, declPattern.knownMethods); } } else { MethodReferenceMatch methodReferenceMatch = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, false /*not constructor*/, false/*not synthetic*/, reference); methodReferenceMatch.setLocalElement(localElement); this.match = methodReferenceMatch; if (this.pattern.findReferences && reference instanceof MessageSend) { IJavaElement focus = this.pattern.focus; // verify closest match if pattern was bound // (see bug 70827) if (focus != null && focus.getElementType() == IJavaElement.METHOD) { if (methodBinding != null && methodBinding.declaringClass != null) { boolean isPrivate = Flags.isPrivate(((IMethod) focus).getFlags()); if (isPrivate && !CharOperation.equals(methodBinding.declaringClass.sourceName, focus.getParent().getElementName().toCharArray())) { return; // finally the match was not possible } } } matchReportReference((MessageSend)reference, locator, ((MessageSend)reference).binding); } else { if (reference instanceof SingleMemberAnnotation) { reference = ((SingleMemberAnnotation)reference).memberValuePairs()[0]; this.match.setImplicit(true); } int offset = reference.sourceStart; int length = reference.sourceEnd - offset + 1; this.match.setOffset(offset); this.match.setLength(length); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
void matchReportReference(MessageSend messageSend, MatchLocator locator, MethodBinding methodBinding) throws CoreException { // Look if there's a need to special report for parameterized type boolean isParameterized = false; if (methodBinding instanceof ParameterizedGenericMethodBinding) { // parameterized generic method isParameterized = true; // Update match regarding method type arguments ParameterizedGenericMethodBinding parameterizedMethodBinding = (ParameterizedGenericMethodBinding) methodBinding; this.match.setRaw(parameterizedMethodBinding.isRaw); TypeBinding[] typeArguments = /*parameterizedMethodBinding.isRaw ? null :*/ parameterizedMethodBinding.typeArguments; updateMatch(typeArguments, locator, this.pattern.methodArguments, this.pattern.hasMethodParameters()); // Update match regarding declaring class type arguments if (methodBinding.declaringClass.isParameterizedType() || methodBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)methodBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasMethodArguments() || parameterizedBinding.isParameterizedWithOwnVariables()) { // special case for pattern which defines method arguments but not its declaring type // in this case, we do not refine accuracy using declaring type arguments...! } else { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding method parameters // TODO ? (frederic) // Update match regarding method return type // TODO ? (frederic) // Special case for errors if (this.match.getRule() != 0 && messageSend.resolvedType == null) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } } else if (methodBinding instanceof ParameterizedMethodBinding) { isParameterized = true; if (methodBinding.declaringClass.isParameterizedType() || methodBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)methodBinding.declaringClass; if (!parameterizedBinding.isParameterizedWithOwnVariables()) { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding method parameters // TODO ? (frederic) // Update match regarding method return type // TODO ? (frederic) // Special case for errors if (this.match.getRule() != 0 && messageSend.resolvedType == null) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } } else if (this.pattern.hasMethodArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Report match int offset = (int) (messageSend.nameSourcePosition >>> 32); this.match.setOffset(offset); this.match.setLength(messageSend.sourceEnd - offset + 1); if (isParameterized && this.pattern.hasMethodArguments()) { locator.reportAccurateParameterizedMethodReference(this.match, messageSend, messageSend.typeArguments); } else { locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void reportDeclaration(MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods) throws CoreException { ReferenceBinding declaringClass = methodBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type // Report match for binary if (type.isBinary()) { IMethod method = null; TypeBinding[] parameters = methodBinding.original().parameters; int parameterLength = parameters.length; char[][] parameterTypes = new char[parameterLength][]; for (int i = 0; i<parameterLength; i++) { char[] typeName = parameters[i].qualifiedSourceName(); for (int j=0, dim=parameters[i].dimensions(); j<dim; j++) { typeName = CharOperation.concat(typeName, new char[] {'[', ']'}); } parameterTypes[i] = typeName; } method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; IResource resource = type.getResource(); if (resource == null) resource = type.getJavaProject().getProject(); IBinaryType info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile)type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, method, methodBinding, info, SearchMatch.A_ACCURATE); return; } // When source is available, report match if method is found in the declaring type IResource resource = type.getResource(); if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(methodBinding.original()); if (methodDecl != null) { // Create method handle from method declaration String methodName = new String(methodBinding.selector); Argument[] arguments = methodDecl.arguments; int length = arguments == null ? 0 : arguments.length; String[] parameterTypes = new String[length]; for (int i = 0; i < length; i++) { char[][] typeName = arguments[i].type.getParameterizedTypeName(); parameterTypes[i] = Signature.createTypeSignature(CharOperation.concatWith(typeName, '.'), false); } IMethod method = type.getMethod(methodName, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; // Create and report corresponding match int offset = methodDecl.sourceStart; this.match = new MethodDeclarationMatch(method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields Binding refBinding = binding; if (importRef.isStatic()) { if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } } // Look for closest pattern PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { PatternLocator patternLocator = this.patternLocators[i]; int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(refBinding); if (newLevel > level) { closestPattern = patternLocator; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) { closestPattern.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { int newLevel = this.patternLocators[i].matchLevel(importRef); if (newLevel > level) { closestPattern = this.patternLocators[i]; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) closestPattern.matchReportImportRef(importRef, binding, element, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { PatternLocator patternLocator = this.patternLocators[i]; int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference); if (newLevel > level) { closestPattern = patternLocator; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) closestPattern.matchReportReference(reference, element, localElement, otherElements, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { Binding refBinding = binding; if (importRef.isStatic()) { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } } super.matchLevelAndReportImportRef(importRef, refBinding, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (binding == null) { this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator); } else { if (locator.encloses(element)) { long[] positions = importRef.sourcePositions; int last = positions.length - 1; if (binding instanceof ProblemReferenceBinding) binding = ((ProblemReferenceBinding) binding).closestMatch(); if (binding instanceof ReferenceBinding) { PackageBinding pkgBinding = ((ReferenceBinding) binding).fPackage; if (pkgBinding != null) last = pkgBinding.compoundName.length; } if (binding instanceof PackageBinding) last = ((PackageBinding) binding).compoundName.length; int start = (int) (positions[0] >>> 32); int end = (int) positions[last - 1]; this.match = locator.newPackageReferenceMatch(element, accuracy, start, end-start+1, importRef); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { long[] positions = null; int last = -1; if (reference instanceof ImportReference) { ImportReference importRef = (ImportReference) reference; positions = importRef.sourcePositions; last = (importRef.bits & ASTNode.OnDemand) != 0 ? positions.length : positions.length - 1; } else { TypeBinding typeBinding = null; if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; positions = qNameRef.sourcePositions; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; break; case Binding.TYPE : //=============only type ============== if (qNameRef.binding instanceof TypeBinding) typeBinding = (TypeBinding) qNameRef.binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : Binding binding = qNameRef.binding; if (binding instanceof TypeBinding) { typeBinding = (TypeBinding) binding; } else if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; last = qNameRef.tokens.length - (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2); } else if (binding instanceof ProblemBinding) { ProblemBinding pbBinding = (ProblemBinding) binding; typeBinding = pbBinding.searchType; last = CharOperation.occurencesOf('.', pbBinding.name); } break; } } else if (reference instanceof QualifiedTypeReference) { QualifiedTypeReference qTypeRef = (QualifiedTypeReference) reference; positions = qTypeRef.sourcePositions; typeBinding = qTypeRef.resolvedType; } else if (reference instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference jsTypeRef = (JavadocSingleTypeReference) reference; positions = new long[1]; positions[0] = (((long)jsTypeRef.sourceStart) << 32) + jsTypeRef.sourceEnd; typeBinding = jsTypeRef.resolvedType; } if (positions == null) return; if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding instanceof ProblemReferenceBinding) typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch(); if (typeBinding instanceof ReferenceBinding) { PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage; if (pkgBinding != null) last = pkgBinding.compoundName.length; } // Do not report qualified references which are only enclosing type // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=91078) ReferenceBinding enclosingType = typeBinding == null ? null: typeBinding.enclosingType(); if (enclosingType != null) { int length = positions.length; while (enclosingType != null && length > 0) { length--; enclosingType = enclosingType.enclosingType(); } if (length <= 1) return; } } if (last == -1) { last = this.pattern.segments.length; } if (last == 0) return; if (last > positions.length) last = positions.length; int sourceStart = (int) (positions[0] >>> 32); int sourceEnd = ((int) positions[last - 1]); PackageReferenceMatch packageReferenceMatch = locator.newPackageReferenceMatch(element, accuracy, sourceStart, sourceEnd-sourceStart+1, reference); packageReferenceMatch.setLocalElement(localElement); this.match = packageReferenceMatch; locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/matching/LocalVariableLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { int offset = -1; int length = -1; if (reference instanceof SingleNameReference) { offset = reference.sourceStart; length = reference.sourceEnd-offset+1; } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; long sourcePosition = qNameRef.sourcePositions[0]; offset = (int) (sourcePosition >>> 32); length = ((int) sourcePosition) - offset +1; } else if (reference instanceof LocalDeclaration) { LocalVariable localVariable = getLocalVariable(); offset = localVariable.nameStart; length = localVariable.nameEnd-offset+1; element = localVariable; this.match = locator.newDeclarationMatch(element, null, accuracy, offset, length); locator.report(this.match); return; } if (offset >= 0) { this.match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, length, reference); locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (elementBinding instanceof ReferenceBinding) { ReferenceBinding referenceBinding = (ReferenceBinding) elementBinding; if (referenceBinding.isClass() && this.pattern.typeSuffix == IIndexConstants.INTERFACE_SUFFIX) { // do not report class if expected types are only interfaces return; } if (referenceBinding.isInterface() && this.pattern.typeSuffix == IIndexConstants.CLASS_SUFFIX) { // do not report interface if expected types are only classes return; } } super.matchReportReference(reference, element, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { if (importRef.isStatic() && binding instanceof FieldBinding) { super.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements,Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfAccessedFieldsPattern) { // need exact match to be able to open on type ref if (accuracy != SearchMatch.A_ACCURATE) return; // element that references the field must be included in the enclosing element DeclarationOfAccessedFieldsPattern declPattern = (DeclarationOfAccessedFieldsPattern) this.pattern; while (element != null && !declPattern.enclosingElement.equals(element)) element = element.getParent(); if (element != null) { if (reference instanceof FieldReference) { reportDeclaration(((FieldReference) reference).binding, locator, declPattern.knownFields); } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; Binding nameBinding = qNameRef.binding; if (nameBinding instanceof FieldBinding) reportDeclaration((FieldBinding)nameBinding, locator, declPattern.knownFields); int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length; for (int i = 0; i < otherMax; i++) reportDeclaration(qNameRef.otherBindings[i], locator, declPattern.knownFields); } else if (reference instanceof SingleNameReference) { reportDeclaration((FieldBinding)((SingleNameReference) reference).binding, locator, declPattern.knownFields); } } } else if (reference instanceof ImportReference) { ImportReference importRef = (ImportReference) reference; long[] positions = importRef.sourcePositions; int lastIndex = importRef.tokens.length - 1; int start = (int) ((positions[lastIndex]) >>> 32); int end = (int) positions[lastIndex]; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start, end-start+1, importRef); locator.report(this.match); } else if (reference instanceof FieldReference) { FieldReference fieldReference = (FieldReference) reference; long position = fieldReference.nameSourcePosition; int start = (int) (position >>> 32); int end = (int) position; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start, end-start+1, fieldReference); locator.report(this.match); } else if (reference instanceof SingleNameReference) { int offset = reference.sourceStart; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); locator.report(this.match); } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; int length = qNameRef.tokens.length; SearchMatch[] matches = new SearchMatch[length]; Binding nameBinding = qNameRef.binding; int indexOfFirstFieldBinding = qNameRef.indexOfFirstFieldBinding > 0 ? qNameRef.indexOfFirstFieldBinding-1 : 0; // first token if (matchesName(this.pattern.name, qNameRef.tokens[indexOfFirstFieldBinding]) && !(nameBinding instanceof LocalVariableBinding)) { FieldBinding fieldBinding = nameBinding instanceof FieldBinding ? (FieldBinding) nameBinding : null; if (fieldBinding == null) { matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, -1, -1, reference); } else { switch (matchField(fieldBinding, false)) { case ACCURATE_MATCH: matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference); break; case INACCURATE_MATCH: this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference); if (fieldBinding.type != null && fieldBinding.type.isParameterizedType() && this.pattern.hasTypeArguments()) { updateMatch((ParameterizedTypeBinding) fieldBinding.type, this.pattern.getTypeArguments(), locator); } matches[indexOfFirstFieldBinding] = this.match; break; } } } // other tokens for (int i = indexOfFirstFieldBinding+1; i < length; i++) { char[] token = qNameRef.tokens[i]; if (matchesName(this.pattern.name, token)) { FieldBinding otherBinding = qNameRef.otherBindings == null ? null : qNameRef.otherBindings[i-(indexOfFirstFieldBinding+1)]; if (otherBinding == null) { matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, -1, -1, reference); } else { switch (matchField(otherBinding, false)) { case ACCURATE_MATCH: matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference); break; case INACCURATE_MATCH: this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference); if (otherBinding.type != null && otherBinding.type.isParameterizedType() && this.pattern.hasTypeArguments()) { updateMatch((ParameterizedTypeBinding) otherBinding.type, this.pattern.getTypeArguments(), locator); } matches[i] = this.match; break; } } } } locator.reportAccurateFieldReference(matches, qNameRef); } }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields) throws CoreException { // ignore length field if (fieldBinding == ArrayBinding.ArrayLength) return; ReferenceBinding declaringClass = fieldBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type char[] bindingName = fieldBinding.name; IField field = type.getField(new String(bindingName)); if (knownFields.addIfNotIncluded(field) == null) return; IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null; if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE); } else { if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; FieldDeclaration fieldDecl = null; FieldDeclaration[] fieldDecls = typeDecl.fields; int length = fieldDecls == null ? 0 : fieldDecls.length; for (int i = 0; i < length; i++) { if (CharOperation.equals(bindingName, fieldDecls[i].name)) { fieldDecl = fieldDecls[i]; break; } } if (fieldDecl != null) { int offset = fieldDecl.sourceStart; this.match = new FieldDeclarationMatch(((JavaElement) field).resolved(fieldBinding), SearchMatch.A_ACCURATE, offset, fieldDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { Binding refBinding = binding; if (importRef.isStatic()) { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } // resolve and report int level = resolveLevel(refBinding); if (level >= INACCURATE_MATCH) { matchReportImportRef( importRef, binding, locator.createImportHandle(importRef), level == ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE, locator); } return; } super.matchLevelAndReportImportRef(importRef, refBinding, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfReferencedTypesPattern) { if ((element = findElement(element, accuracy)) != null) { SimpleSet knownTypes = ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes; while (binding instanceof ReferenceBinding) { ReferenceBinding typeBinding = (ReferenceBinding) binding; reportDeclaration(typeBinding, 1, locator, knownTypes); binding = typeBinding.enclosingType(); } } return; } // return if this is not necessary to report if (this.pattern.hasTypeArguments() && !this.isEquivalentMatch &&!this.isErasureMatch) { return; } // Return if fine grain is on and does not concern import reference if ((this.pattern.fineGrain != 0 && (this.pattern.fineGrain & IJavaSearchConstants.IMPORT_DECLARATION_TYPE_REFERENCE) == 0)) { return; } // Create search match this.match = locator.newTypeReferenceMatch(element, binding, accuracy, importRef); // set match raw flag and rule this.match.setRaw(true); if (this.pattern.hasTypeArguments()) { // binding is raw => only compatible erasure if pattern has type arguments this.match.setRule(this.match.getRule() & (~SearchPattern.R_FULL_MATCH)); } // Try to find best selection for match TypeBinding typeBinding = null; boolean lastButOne = false; if (binding instanceof ReferenceBinding) { typeBinding = (ReferenceBinding) binding; } else if (binding instanceof FieldBinding) { // may happen for static import typeBinding = ((FieldBinding)binding).declaringClass; lastButOne = importRef.isStatic() && ((importRef.bits & ASTNode.OnDemand) == 0); } else if (binding instanceof MethodBinding) { // may happen for static import typeBinding = ((MethodBinding)binding).declaringClass; lastButOne = importRef.isStatic() && ((importRef.bits & ASTNode.OnDemand) == 0); } if (typeBinding != null) { int lastIndex = importRef.tokens.length - 1; if (lastButOne) { // for field or method static import, use last but one token lastIndex--; } if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // try to match all enclosing types for which the token matches as well. while (typeBinding != null && lastIndex >= 0) { if (resolveLevelForType(typeBinding) != IMPOSSIBLE_MATCH) { if (locator.encloses(element)) { long[] positions = importRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; // report match this.match.setOffset(start); this.match.setLength(end-start+1); locator.report(this.match); } return; } lastIndex--; typeBinding = typeBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, importRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ArrayTypeReference arrayRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.pattern.simpleName == null) { // TODO (frederic) need to add a test for this case while searching generic types... if (locator.encloses(element)) { int offset = arrayRef.sourceStart; int length = arrayRef.sourceEnd-offset+1; if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, length, arrayRef); } else { this.match.setOffset(offset); this.match.setLength(length); } locator.report(this.match); return; } } this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, arrayRef); if (arrayRef.resolvedType != null) { matchReportReference(arrayRef, -1, arrayRef.resolvedType.leafComponentType(), locator); return; } locator.reportAccurateTypeReference(this.match, arrayRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfReferencedTypesPattern) { if ((element = findElement(element, accuracy)) != null) reportDeclaration(reference, element, locator, ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes); return; } // Create search match TypeReferenceMatch refMatch = locator.newTypeReferenceMatch(element, elementBinding, accuracy, reference); refMatch.setLocalElement(localElement); refMatch.setOtherElements(otherElements); this.match = refMatch; // Report match depending on reference type if (reference instanceof QualifiedNameReference) matchReportReference((QualifiedNameReference) reference, element, elementBinding, accuracy, locator); else if (reference instanceof QualifiedTypeReference) matchReportReference((QualifiedTypeReference) reference, element, elementBinding, accuracy, locator); else if (reference instanceof ArrayTypeReference) matchReportReference((ArrayTypeReference) reference, element, elementBinding, accuracy, locator); else { TypeBinding typeBinding = reference instanceof Expression ? ((Expression)reference).resolvedType : null; if (typeBinding != null) { matchReportReference((Expression)reference, -1, typeBinding, locator); return; } locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(QualifiedNameReference qNameRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { Binding binding = qNameRef.binding; TypeBinding typeBinding = null; int lastIndex = qNameRef.tokens.length - 1; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; break; case Binding.TYPE : //=============only type ============== if (binding instanceof TypeBinding) typeBinding = (TypeBinding) binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : if (binding instanceof ProblemReferenceBinding) { typeBinding = (TypeBinding) binding; } else if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; } else if (binding instanceof ProblemBinding) { typeBinding = ((ProblemBinding) binding).searchType; } break; } if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // Create search match to report if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qNameRef); } // try to match all enclosing types for which the token matches as well. if (typeBinding instanceof ReferenceBinding) { ReferenceBinding refBinding = (ReferenceBinding) typeBinding; while (refBinding != null && lastIndex >= 0) { if (resolveLevelForType(refBinding) == ACCURATE_MATCH) { if (locator.encloses(element)) { long[] positions = qNameRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; this.match.setOffset(start); this.match.setLength(end-start+1); // Look if there's a need to special report for parameterized type matchReportReference(qNameRef, lastIndex, refBinding, locator); } return; } lastIndex--; refBinding = refBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, qNameRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(QualifiedTypeReference qTypeRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { TypeBinding typeBinding = qTypeRef.resolvedType; int lastIndex = qTypeRef.tokens.length - 1; if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // Create search match to report if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qTypeRef); } // try to match all enclosing types for which the token matches as well if (typeBinding instanceof ReferenceBinding) { ReferenceBinding refBinding = (ReferenceBinding) typeBinding; while (refBinding != null && lastIndex >= 0) { if (resolveLevelForType(refBinding) != IMPOSSIBLE_MATCH) { if (locator.encloses(element)) { long[] positions = qTypeRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; this.match.setOffset(start); this.match.setLength(end-start+1); // Look if there's a need to special report for parameterized type matchReportReference(qTypeRef, lastIndex, refBinding, locator); } return; } lastIndex--; refBinding = refBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, qTypeRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
void matchReportReference(Expression expr, int lastIndex, TypeBinding refBinding, MatchLocator locator) throws CoreException { // Look if there's a need to special report for parameterized type if (refBinding.isParameterizedType() || refBinding.isRawType()) { // Try to refine accuracy ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)refBinding; updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Make a special report for parameterized types if necessary if (refBinding.isParameterizedType() && this.pattern.hasTypeArguments()) { TypeReference typeRef = null; TypeReference[] typeArguments = null; if (expr instanceof ParameterizedQualifiedTypeReference) { typeRef = (ParameterizedQualifiedTypeReference) expr; typeArguments = ((ParameterizedQualifiedTypeReference) expr).typeArguments[lastIndex]; } else if (expr instanceof ParameterizedSingleTypeReference) { typeRef = (ParameterizedSingleTypeReference) expr; typeArguments = ((ParameterizedSingleTypeReference) expr).typeArguments; } if (typeRef != null) { locator.reportAccurateParameterizedTypeReference(this.match, typeRef, lastIndex, typeArguments); return; } } } else if (this.pattern.hasTypeArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Report match if (expr instanceof ArrayTypeReference) { locator.reportAccurateTypeReference(this.match, expr, this.pattern.simpleName); return; } if (refBinding.isLocalType()) { // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=82673 LocalTypeBinding local = (LocalTypeBinding) refBinding.erasure(); IJavaElement focus = this.pattern.focus; if (focus != null && local.enclosingMethod != null && focus.getParent().getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) focus.getParent(); if (!CharOperation.equals(local.enclosingMethod.selector, method.getElementName().toCharArray())) { return; } } } if (this.pattern.simpleName == null) { this.match.setOffset(expr.sourceStart); this.match.setLength(expr.sourceEnd-expr.sourceStart+1); } locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void reportDeclaration(ASTNode reference, IJavaElement element, MatchLocator locator, SimpleSet knownTypes) throws CoreException { int maxType = -1; TypeBinding typeBinding = null; if (reference instanceof TypeReference) { typeBinding = ((TypeReference) reference).resolvedType; maxType = Integer.MAX_VALUE; } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; Binding binding = qNameRef.binding; maxType = qNameRef.tokens.length - 1; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; break; case Binding.TYPE : //=============only type ============== if (binding instanceof TypeBinding) typeBinding = (TypeBinding) binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; } else if (binding instanceof ProblemBinding) { ProblemBinding pbBinding = (ProblemBinding) binding; typeBinding = pbBinding.searchType; // second chance with recorded type so far char[] partialQualifiedName = pbBinding.name; maxType = CharOperation.occurencesOf('.', partialQualifiedName) - 1; // index of last bound token is one before the pb token if (typeBinding == null || maxType < 0) return; } break; } } else if (reference instanceof SingleNameReference) { typeBinding = (TypeBinding) ((SingleNameReference) reference).binding; maxType = 1; } if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding == null || typeBinding instanceof BaseTypeBinding) return; if (typeBinding instanceof ProblemReferenceBinding) { TypeBinding original = typeBinding.closestMatch(); if (original == null) return; // original may not be set (bug 71279) typeBinding = original; } typeBinding = typeBinding.erasure(); reportDeclaration((ReferenceBinding) typeBinding, maxType, locator, knownTypes); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void reportDeclaration(ReferenceBinding typeBinding, int maxType, MatchLocator locator, SimpleSet knownTypes) throws CoreException { IType type = locator.lookupType(typeBinding); if (type == null) return; // case of a secondary type IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null; if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); } while (maxType >= 0 && type != null) { if (!knownTypes.includes(type)) { if (isBinary) { locator.reportBinaryMemberDeclaration(resource, type, typeBinding, info, SearchMatch.A_ACCURATE); } else { if (typeBinding instanceof ParameterizedTypeBinding) typeBinding = ((ParameterizedTypeBinding) typeBinding).genericType(); ClassScope scope = ((SourceTypeBinding) typeBinding).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; int offset = typeDecl.sourceStart; this.match = new TypeDeclarationMatch(((JavaElement) type).resolved(typeBinding), SearchMatch.A_ACCURATE, offset, typeDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } knownTypes.add(type); } typeBinding = typeBinding.enclosingType(); IJavaElement parent = type.getParent(); if (parent instanceof IType) { type = (IType)parent; } else { type = null; } maxType--; } }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { MethodBinding constructorBinding = null; boolean isSynthetic = false; if (reference instanceof ExplicitConstructorCall) { ExplicitConstructorCall call = (ExplicitConstructorCall) reference; isSynthetic = call.isImplicitSuper(); constructorBinding = call.binding; } else if (reference instanceof AllocationExpression) { AllocationExpression alloc = (AllocationExpression) reference; constructorBinding = alloc.binding; } else if (reference instanceof TypeDeclaration || reference instanceof FieldDeclaration) { super.matchReportReference(reference, element, elementBinding, accuracy, locator); if (this.match != null) return; } // Create search match this.match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, true, isSynthetic, reference); // Look to refine accuracy if (constructorBinding instanceof ParameterizedGenericMethodBinding) { // parameterized generic method // Update match regarding constructor type arguments ParameterizedGenericMethodBinding parameterizedMethodBinding = (ParameterizedGenericMethodBinding) constructorBinding; this.match.setRaw(parameterizedMethodBinding.isRaw); TypeBinding[] typeBindings = parameterizedMethodBinding.isRaw ? null : parameterizedMethodBinding.typeArguments; updateMatch(typeBindings, locator, this.pattern.constructorArguments, this.pattern.hasConstructorParameters()); // Update match regarding declaring class type arguments if (constructorBinding.declaringClass.isParameterizedType() || constructorBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)constructorBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasConstructorArguments() || parameterizedBinding.isParameterizedWithOwnVariables()) { // special case for constructor pattern which defines arguments but no type // in this case, we only use refined accuracy for constructor } else if (this.pattern.hasTypeArguments() && !this.pattern.hasConstructorArguments()) { // special case for constructor pattern which defines no constructor arguments but has type ones // in this case, we do not use refined accuracy updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } else { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding constructor parameters // TODO ? (frederic) } else if (constructorBinding instanceof ParameterizedMethodBinding) { // Update match regarding declaring class type arguments if (constructorBinding.declaringClass.isParameterizedType() || constructorBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)constructorBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasConstructorArguments()) { // special case for constructor pattern which defines arguments but no type updateMatch(parameterizedBinding, new char[][][] {this.pattern.constructorArguments}, this.pattern.hasTypeParameters(), 0, locator); } else if (!parameterizedBinding.isParameterizedWithOwnVariables()) { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding constructor parameters // TODO ? (frederic) } else if (this.pattern.hasConstructorArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Report match int offset = reference.sourceStart; this.match.setOffset(offset); this.match.setLength(reference.sourceEnd - offset + 1); if (reference instanceof FieldDeclaration) { // enum declaration FieldDeclaration enumConstant = (FieldDeclaration) reference; if (enumConstant.initialization instanceof QualifiedAllocationExpression) { locator.reportAccurateEnumConstructorReference(this.match, enumConstant, (QualifiedAllocationExpression) enumConstant.initialization); return; } } locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
public boolean execute(IProgressMonitor progressMonitor) { if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; if (!this.folder.isAccessible()) return true; // nothing to do Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index == null) return true; ReadWriteMonitor monitor = index.monitor; if (monitor == null) return true; // index got deleted since acquired try { monitor.enterRead(); // ask permission to read String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ int max = paths == null ? 0 : paths.length; final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max==0 ? 33 : max+11); final String OK = "OK"; //$NON-NLS-1$ final String DELETED = "DELETED"; //$NON-NLS-1$ if (paths == null) { this.folder.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, file); } return false; } return true; } }, IResource.NONE); } else { for (int i = 0; i < max; i++) { indexedFileNames.put(paths[i], DELETED); } final long indexLastModified = index.getIndexFile().lastModified(); this.folder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location != null) { String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, indexedFileNames.get(containerRelativePath) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } } return false; } return true; } }, IResource.NONE ); } Object[] names = indexedFileNames.keyTable; Object[] values = indexedFileNames.valueTable; for (int i = 0, length = names.length; i < length; i++) { String name = (String) names[i]; if (name != null) { if (this.isCancelled) return false; Object value = values[i]; if (value != OK) { if (value == DELETED) this.manager.remove(name, this.containerPath); else { this.manager.addBinary((IFile) value, this.containerPath); } } } } // request to save index when all class files have been indexed... also sets state to SAVED_STATE this.manager.request(new SaveIndex(this.containerPath, this.manager)); }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location != null) { String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, indexedFileNames.get(containerRelativePath) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } } return false; } return true; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
public boolean execute(IProgressMonitor progressMonitor) { if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; if (!this.project.isAccessible()) return true; // nothing to do ReadWriteMonitor monitor = null; try { // Get source folder entries. Libraries are done as a separate job JavaProject javaProject = (JavaProject)JavaCore.create(this.project); // Do not create marker while getting raw classpath (see bug 41859) IClasspathEntry[] entries = javaProject.getRawClasspath(); int length = entries.length; IClasspathEntry[] sourceEntries = new IClasspathEntry[length]; int sourceEntriesNumber = 0; for (int i = 0; i < length; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) sourceEntries[sourceEntriesNumber++] = entry; } if (sourceEntriesNumber == 0) { IPath projectPath = javaProject.getPath(); for (int i = 0; i < length; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(projectPath)) { // the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815) // ensure a job exists to index it as a binary folder this.manager.indexLibrary(projectPath, this.project); return true; } } // nothing to index but want to save an empty index file so its not 'rebuilt' when part of a search request Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index != null) this.manager.saveIndex(index); return true; } if (sourceEntriesNumber != length) System.arraycopy(sourceEntries, 0, sourceEntries = new IClasspathEntry[sourceEntriesNumber], 0, sourceEntriesNumber); Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index == null) return true; monitor = index.monitor; if (monitor == null) return true; // index got deleted since acquired monitor.enterRead(); // ask permission to read String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ int max = paths == null ? 0 : paths.length; final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11); final String OK = "OK"; //$NON-NLS-1$ final String DELETED = "DELETED"; //$NON-NLS-1$ if (paths != null) { for (int i = 0; i < max; i++) indexedFileNames.put(paths[i], DELETED); } final long indexLastModified = max == 0 ? 0L : index.getIndexFile().lastModified(); IWorkspaceRoot root = this.project.getWorkspace().getRoot(); for (int i = 0; i < sourceEntriesNumber; i++) { if (this.isCancelled) return false; IClasspathEntry entry = sourceEntries[i]; IResource sourceFolder = root.findMember(entry.getPath()); if (sourceFolder != null) { // collect output locations if source is project (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32041) final HashSet outputs = new HashSet(); if (sourceFolder.getType() == IResource.PROJECT) { // Do not create marker while getting output location (see bug 41859) outputs.add(javaProject.getOutputLocation()); for (int j = 0; j < sourceEntriesNumber; j++) { IPath output = sourceEntries[j].getOutputLocation(); if (output != null) { outputs.add(output); } } } final boolean hasOutputs = !outputs.isEmpty(); final char[][] inclusionPatterns = ((ClasspathEntry) entry).fullInclusionPatternChars(); final char[][] exclusionPatterns = ((ClasspathEntry) entry).fullExclusionPatternChars(); if (max == 0) { sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; indexedFileNames.put(Util.relativePath(file.getFullPath(), 1/*remove project segment*/), file); } return false; case IResource.FOLDER : if (exclusionPatterns != null && inclusionPatterns == null) { // if there are inclusion patterns then we must walk the children if (Util.isExcluded(proxy.requestFullPath(), inclusionPatterns, exclusionPatterns, true)) return false; } if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; } }, IResource.NONE ); } else { sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location == null) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; String relativePathString = Util.relativePath(file.getFullPath(), 1/*remove project segment*/); indexedFileNames.put(relativePathString, indexedFileNames.get(relativePathString) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } return false; case IResource.FOLDER : if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns)) return false; if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; } }, IResource.NONE ); } } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location == null) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; String relativePathString = Util.relativePath(file.getFullPath(), 1/*remove project segment*/); indexedFileNames.put(relativePathString, indexedFileNames.get(relativePathString) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } return false; case IResource.FOLDER : if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns)) return false; if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void acceptSearchMatch(SearchMatch match) throws CoreException { this.resultCollector.accept( match.getResource(), match.getOffset(), match.getOffset() + match.getLength(), (IJavaElement) match.getElement(), match.getAccuracy() ); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { this.basicEngine.search(pattern, participants, scope, requestor, monitor); }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// 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
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; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
protected void touchProjects(final IProject[] projectsToTouch, IProgressMonitor progressMonitor) throws CoreException { for (int i = 0; i < projectsToTouch.length; i++) { IProgressMonitor monitor = progressMonitor == null ? null: new SubProgressMonitor(progressMonitor, 1); 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(monitor); } }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
public void run(IProgressMonitor monitor) throws CoreException { JavaModelManager manager = JavaModelManager.getJavaModelManager(); DeltaProcessor deltaProcessor = manager.getDeltaProcessor(); int previousDeltaCount = deltaProcessor.javaModelDeltas.size(); try { this.progressMonitor = monitor; pushOperation(this); try { if (canModifyRoots()) { // computes the root infos before executing the operation // noop if aready initialized JavaModelManager.getDeltaState().initializeRoots(false/*not initiAfterLoad*/); } executeOperation(); } finally { if (isTopLevelOperation()) { runPostActions(); } } } finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } } }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
public InputStream getContents() throws CoreException { ZipFile zipFile = null; try { zipFile = getZipFile(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } String entryName = getEntryName(); ZipEntry zipEntry = zipFile.getEntry(entryName); if (zipEntry == null){ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entryName)); } byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); return new ByteArrayInputStream(contents); } catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } }
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
public InputStream getContents() throws CoreException { if (this.resource instanceof IFile) return ((IFile) this.resource).getContents(); return null; }
// in model/org/eclipse/jdt/internal/core/JarEntryDirectory.java
public InputStream getContents() throws CoreException { return new ByteArrayInputStream(new byte[0]); }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void verifyArchiveContent(IPath path) throws CoreException { if (isInvalidArchive(path)) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); } ZipFile file = getZipFile(path); closeZipFile(file); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public ZipFile getZipFile(IPath path) throws CoreException { if (isInvalidArchive(path)) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); ZipCache zipCache; ZipFile zipFile; if ((zipCache = (ZipCache)this.zipFiles.get()) != null && (zipFile = zipCache.getCache(path)) != null) { return zipFile; } File localFile = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource file = root.findMember(path); if (file != null) { // internal resource URI location; if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } localFile = Util.toLocalFile(location, null/*no progress availaible*/); if (localFile == null) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } else { // external resource -> it is ok to use toFile() localFile= path.toFile(); } try { if (ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile ); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile = new ZipFile(localFile); if (zipCache != null) { zipCache.setCache(path, zipFile); } return zipFile; } catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); } }
// 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
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(); } }
// 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 void initialize(IPath path, IJavaProject javaProject) throws CoreException { // not used }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private Set getNonChainingJarsCache() throws CoreException { // Even if there is one entry in the cache, just return it. It may not be // the complete cache, but avoid going through all the projects to populate the cache. if (this.nonChainingJars != null && this.nonChainingJars.size() > 0) { return this.nonChainingJars; } Set result = new HashSet(); IJavaProject[] projects = getJavaModel().getJavaProjects(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; IClasspathEntry[] classpath = ((JavaProject) javaProject).getResolvedClasspath(); for (int j = 0, length2 = classpath.length; j < length2; j++) { IClasspathEntry entry = classpath[j]; IPath path; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && !result.contains(path = entry.getPath()) && ClasspathEntry.resolvedChainedLibraries(path).length == 0) { result.add(path); } } } this.nonChainingJars = Collections.synchronizedSet(result); return this.nonChainingJars; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private Set getClasspathListCache(String cacheName) throws CoreException { if (cacheName == NON_CHAINING_JARS_CACHE) return getNonChainingJarsCache(); else if (cacheName == INVALID_ARCHIVES_CACHE) return this.invalidArchives; else return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void loadVariablesAndContainers() throws CoreException { // backward compatibility, consider persistent property QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "variables"); //$NON-NLS-1$ String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); try { if (xmlString != null){ StringReader reader = new StringReader(xmlString); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch(SAXException e) { return; } catch(ParserConfigurationException e){ return; } finally { reader.close(); } if (cpElement == null) return; if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$ return; } NodeList list= cpElement.getChildNodes(); int length= list.getLength(); for (int i= 0; i < length; ++i) { Node node= list.item(i); short type= node.getNodeType(); if (type == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$ variablePut( element.getAttribute("name"), //$NON-NLS-1$ new Path(element.getAttribute("path"))); //$NON-NLS-1$ } } } } } catch(IOException e){ // problem loading xml file: nothing we can do } finally { if (xmlString != null){ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one } } // backward compatibility, load variables and containers from preferences into cache loadVariablesAndContainers(getDefaultPreferences()); loadVariablesAndContainers(getInstancePreferences()); // load variables and containers from saved file into cache File file = getVariableAndContainersFile(); DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); switch (in.readInt()) { case 2 : new VariablesAndContainersLoadHelper(in).load(); break; case 1 : // backward compatibility, load old format // variables int size = in.readInt(); while (size-- > 0) { String varName = in.readUTF(); String pathString = in.readUTF(); if (CP_ENTRY_IGNORE.equals(pathString)) continue; IPath varPath = Path.fromPortableString(pathString); this.variables.put(varName, varPath); this.previousSessionVariables.put(varName, varPath); } // containers IJavaModel model = getJavaModel(); int projectSize = in.readInt(); while (projectSize-- > 0) { String projectName = in.readUTF(); IJavaProject project = model.getJavaProject(projectName); int containerSize = in.readInt(); while (containerSize-- > 0) { IPath containerPath = Path.fromPortableString(in.readUTF()); int length = in.readInt(); byte[] containerString = new byte[length]; in.readFully(containerString); recreatePersistedContainer(project, containerPath, new String(containerString), true/*add to container values*/); } } break; } } catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ } catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ } finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } } // override persisted values for variables which have a registered initializer String[] registeredVariables = getRegisteredVariableNames(); for (int i = 0; i < registeredVariables.length; i++) { String varName = registeredVariables[i]; this.variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names. } // override persisted values for containers which have a registered initializer containersReset(getRegisteredContainerIDs()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException { // passed this point, save actions are non trivial if (context.getKind() == ISaveContext.SNAPSHOT) return; // save built state if (info.triedRead) saveBuiltState(info); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveBuiltState(PerProjectInfo info) throws CoreException { if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_saveStateProgress, info.project.getName())); File file = getSerializationFile(info.project); if (file == null) return; long t = System.currentTimeMillis(); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { out.writeUTF(JavaCore.PLUGIN_ID); out.writeUTF("STATE"); //$NON-NLS-1$ if (info.savedState == null) { out.writeBoolean(false); } else { out.writeBoolean(true); JavaBuilder.writeState(info.savedState, out); } } finally { out.close(); } } catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } if (JavaBuilder.DEBUG) { t = System.currentTimeMillis() - t; System.out.println(Messages.bind(Messages.build_saveStateComplete, String.valueOf(t))); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathListCache(String cacheName) throws CoreException { File file = getClasspathListFile(cacheName); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Set pathCache = getClasspathListCache(cacheName); synchronized (pathCache) { out.writeInt(pathCache.size()); Iterator entries = pathCache.iterator(); while (entries.hasNext()) { IPath path = (IPath) entries.next(); out.writeUTF(path.toPortableString()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariablesAndContainers(ISaveContext context) throws CoreException { File file = getVariableAndContainersFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeInt(VARIABLES_AND_CONTAINERS_FILE_VERSION); new VariablesAndContainersSaveHelper(out).save(context); } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void saving(ISaveContext context) throws CoreException { long start = -1; if (VERBOSE) start = System.currentTimeMillis(); // save variable and container values on snapshot/full save saveVariablesAndContainers(context); if (VERBOSE) traceVariableAndContainers("Saved", start); //$NON-NLS-1$ switch(context.getKind()) { case ISaveContext.FULL_SAVE : { // save non-chaining jar and invalid jar caches on full save saveClasspathListCache(NON_CHAINING_JARS_CACHE); saveClasspathListCache(INVALID_ARCHIVES_CACHE); // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) context.needDelta(); // clean up indexes on workspace full save // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) IndexManager manager = this.indexManager; if (manager != null // don't force initialization of workspace scope as we could be shutting down // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93941) && this.workspaceScope != null) { manager.cleanUpIndexes(); } } //$FALL-THROUGH$ case ISaveContext.SNAPSHOT : { // clean up external folders on full save or snapshot this.externalFoldersManager.cleanUp(null); } } IProject savedProject = context.getProject(); if (savedProject != null) { if (!JavaProject.hasJavaNature(savedProject)) return; // ignore PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); saveState(info, context); return; } ArrayList vStats= null; // lazy initialized ArrayList values = null; synchronized(this.perProjectInfos) { values = new ArrayList(this.perProjectInfos.values()); } Iterator iterator = values.iterator(); while (iterator.hasNext()) { try { PerProjectInfo info = (PerProjectInfo) iterator.next(); saveState(info, context); } catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); } } if (vStats != null) { IStatus[] stats= new IStatus[vStats.size()]; vStats.toArray(stats); throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Messages.build_cannotSaveStates, null)); } // save external libs timestamps this.deltaState.saveExternalLibTimeStamps(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void startup() throws CoreException { try { configurePluginDebugOptions(); // initialize Java model cache this.cache = new JavaModelCache(); // request state folder creation (workaround 19885) JavaCore.getPlugin().getStateLocation(); // Initialize eclipse preferences initializePreferences(); // Listen to preference changes this.propertyListener = new IEclipsePreferences.IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { JavaModelManager.this.optionsCache = null; } }; InstanceScope.INSTANCE.getNode(JavaCore.PLUGIN_ID).addPreferenceChangeListener(this.propertyListener); // listen for encoding changes (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=255501 ) this.resourcesPropertyListener = new IEclipsePreferences.IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { if (ResourcesPlugin.PREF_ENCODING.equals(event.getKey())) { JavaModelManager.this.optionsCache = null; } } }; String resourcesPluginId = ResourcesPlugin.getPlugin().getBundle().getSymbolicName(); InstanceScope.INSTANCE.getNode(resourcesPluginId).addPreferenceChangeListener(this.resourcesPropertyListener); // Listen to content-type changes Platform.getContentTypeManager().addContentTypeChangeListener(this); // retrieve variable values long start = -1; if (VERBOSE) start = System.currentTimeMillis(); loadVariablesAndContainers(); if (VERBOSE) traceVariableAndContainers("Loaded", start); //$NON-NLS-1$ // listen for resource changes this.deltaState.initializeRootsWithPreviousSession(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.addResourceChangeListener( this.deltaState, /* update spec in JavaCore#addPreProcessingResourceChangedListener(...) if adding more event types */ IResourceChangeEvent.PRE_BUILD | IResourceChangeEvent.POST_BUILD | IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_REFRESH); startIndexing(); // process deltas since last activated in indexer thread so that indexes are up-to-date. // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 Job processSavedState = new Job(Messages.savedState_jobName) { protected IStatus run(IProgressMonitor monitor) { try { // add save participant and process delta atomically // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 workspace.run( new IWorkspaceRunnable() { public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } } }, monitor); } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; processSavedState.setSystem(true); processSavedState.setPriority(Job.SHORT); // process asap processSavedState.schedule(); } catch (RuntimeException e) { shutdown(); throw e; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected IStatus run(IProgressMonitor monitor) { try { // add save participant and process delta atomically // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 workspace.run( new IWorkspaceRunnable() { public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } } }, monitor); } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void computeClasspathLocations( IWorkspaceRoot root, JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject) throws CoreException { /* Update cycle marker */ IMarker cycleMarker = javaProject.getCycleMarker(); if (cycleMarker != null) { int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true)) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; if (severity != cycleMarker.getAttribute(IMarker.SEVERITY, severity)) cycleMarker.setAttribute(IMarker.SEVERITY, severity); } IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath(); ArrayList sLocations = new ArrayList(classpathEntries.length); ArrayList bLocations = new ArrayList(classpathEntries.length); nextEntry : for (int i = 0, l = classpathEntries.length; i < l; i++) { ClasspathEntry entry = (ClasspathEntry) classpathEntries[i]; IPath path = entry.getPath(); Object target = JavaModel.getTarget(path, true); if (target == null) continue nextEntry; switch(entry.getEntryKind()) { case IClasspathEntry.CPE_SOURCE : if (!(target instanceof IContainer)) continue nextEntry; IPath outputPath = entry.getOutputLocation() != null ? entry.getOutputLocation() : javaProject.getOutputLocation(); IContainer outputFolder; if (outputPath.segmentCount() == 1) { outputFolder = javaProject.getProject(); } else { outputFolder = root.getFolder(outputPath); if (!outputFolder.exists()) createOutputFolder(outputFolder); } sLocations.add( ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars())); continue nextEntry; case IClasspathEntry.CPE_PROJECT : if (!(target instanceof IProject)) continue nextEntry; IProject prereqProject = (IProject) target; if (!JavaProject.hasJavaNature(prereqProject)) continue nextEntry; // if project doesn't have java nature or is not accessible JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject); IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath(); ArrayList seen = new ArrayList(); nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) { IClasspathEntry prereqEntry = prereqClasspathEntries[j]; if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { Object prereqTarget = JavaModel.getTarget(prereqEntry.getPath(), true); if (!(prereqTarget instanceof IContainer)) continue nextPrereqEntry; IPath prereqOutputPath = prereqEntry.getOutputLocation() != null ? prereqEntry.getOutputLocation() : prereqJavaProject.getOutputLocation(); IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 ? (IContainer) prereqProject : (IContainer) root.getFolder(prereqOutputPath); if (binaryFolder.exists() && !seen.contains(binaryFolder)) { seen.add(binaryFolder); ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true, entry.getAccessRuleSet()); bLocations.add(bLocation); if (binaryLocationsPerProject != null) { // normal builder mode ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(prereqProject); if (existingLocations == null) { existingLocations = new ClasspathLocation[] {bLocation}; } else { int size = existingLocations.length; System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); existingLocations[size] = bLocation; } binaryLocationsPerProject.put(prereqProject, existingLocations); } } } } continue nextEntry; case IClasspathEntry.CPE_LIBRARY : if (target instanceof IResource) { IResource resource = (IResource) target; ClasspathLocation bLocation = null; if (resource instanceof IFile) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet); } else if (resource instanceof IContainer) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder } bLocations.add(bLocation); if (binaryLocationsPerProject != null) { // normal builder mode IProject p = resource.getProject(); // can be the project being built ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(p); if (existingLocations == null) { existingLocations = new ClasspathLocation[] {bLocation}; } else { int size = existingLocations.length; System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); existingLocations[size] = bLocation; } binaryLocationsPerProject.put(p, existingLocations); } } else if (target instanceof File) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet)); } continue nextEntry; } } // now split the classpath locations... place the output folders ahead of the other .class file folders & jars ArrayList outputFolders = new ArrayList(1); this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()]; if (!sLocations.isEmpty()) { sLocations.toArray(this.sourceLocations); // collect the output folders, skipping duplicates next : for (int i = 0, l = this.sourceLocations.length; i < l; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; IPath outputPath = md.binaryFolder.getFullPath(); for (int j = 0; j < i; j++) { // compare against previously walked source folders if (outputPath.equals(this.sourceLocations[j].binaryFolder.getFullPath())) { md.hasIndependentOutputFolder = this.sourceLocations[j].hasIndependentOutputFolder; continue next; } } outputFolders.add(md); // also tag each source folder whose output folder is an independent folder & is not also a source folder for (int j = 0, m = this.sourceLocations.length; j < m; j++) if (outputPath.equals(this.sourceLocations[j].sourceFolder.getFullPath())) continue next; md.hasIndependentOutputFolder = true; } } // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()]; int index = 0; for (int i = 0, l = outputFolders.size(); i < l; i++) this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i); for (int i = 0, l = bLocations.size(); i < l; i++) this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void createOutputFolder(IContainer outputFolder) throws CoreException { createParentFolder(outputFolder.getParent()); ((IFolder) outputFolder).create(IResource.FORCE | IResource.DERIVED, true, null); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void createParentFolder(IContainer parent) throws CoreException { if (!parent.exists()) { createParentFolder(parent.getParent()); ((IFolder) parent).create(true, true, null); } }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException { this.currentProject = getProject(); if (this.currentProject == null || !this.currentProject.isAccessible()) return new IProject[0]; if (DEBUG) System.out.println("\nStarting build of " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ this.notifier = new BuildNotifier(monitor, this.currentProject); this.notifier.begin(); boolean ok = false; try { this.notifier.checkCancel(); kind = initializeBuilder(kind, true); if (isWorthBuilding()) { if (kind == FULL_BUILD) { if (DEBUG) System.out.println("Performing full build as requested by user"); //$NON-NLS-1$ buildAll(); } else { if ((this.lastState = getLastState(this.currentProject)) == null) { if (DEBUG) System.out.println("Performing full build since last saved state was not found"); //$NON-NLS-1$ buildAll(); } else if (hasClasspathChanged()) { // if the output location changes, do not delete the binary files from old location // the user may be trying something if (DEBUG) System.out.println("Performing full build since classpath has changed"); //$NON-NLS-1$ buildAll(); } else if (this.nameEnvironment.sourceLocations.length > 0) { // if there is no source to compile & no classpath changes then we are done SimpleLookupTable deltas = findDeltas(); if (deltas == null) { if (DEBUG) System.out.println("Performing full build since deltas are missing after incremental request"); //$NON-NLS-1$ buildAll(); } else if (deltas.elementSize > 0) { buildDeltas(deltas); } else if (DEBUG) { System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$ } } else { if (hasStructuralDelta()) { // double check that a jar file didn't get replaced in a binary project if (DEBUG) System.out.println("Performing full build since there are structural deltas"); //$NON-NLS-1$ buildAll(); } else { if (DEBUG) System.out.println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$ this.lastState.tagAsNoopBuild(); } } } ok = true; } } catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); } catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); } catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); } finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); } IProject[] requiredProjects = getRequiredProjects(true); if (DEBUG) System.out.println("Finished build of " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ return requiredProjects; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
protected void clean(IProgressMonitor monitor) throws CoreException { this.currentProject = getProject(); if (this.currentProject == null || !this.currentProject.isAccessible()) return; if (DEBUG) System.out.println("\nCleaning " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ this.notifier = new BuildNotifier(monitor, this.currentProject); this.notifier.begin(); try { this.notifier.checkCancel(); initializeBuilder(CLEAN_BUILD, true); if (DEBUG) System.out.println("Clearing last state as part of clean : " + this.lastState); //$NON-NLS-1$ clearLastState(); removeProblemsAndTasksFor(this.currentProject); new BatchImageBuilder(this, false).cleanOutputFolders(false); } catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); } finally { this.notifier.done(); cleanup(); } if (DEBUG) System.out.println("Finished cleaning " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private void createInconsistentBuildMarker(CoreException coreException) throws CoreException { String message = null; IStatus status = coreException.getStatus(); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); if (children != null && children.length > 0) message = children[0].getMessage(); } if (message == null) message = coreException.getMessage(); IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_inconsistentProject, message), new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
boolean hasBuildpathErrors() throws CoreException { IMarker[] markers = this.currentProject.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); for (int i = 0, l = markers.length; i < l; i++) if (markers[i].getAttribute(IJavaModelMarker.CATEGORY_ID, -1) == CategorizedProblem.CAT_BUILDPATH) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean hasJavaBuilder(IProject project) throws CoreException { ICommand[] buildCommands = project.getDescription().getBuildSpec(); for (int i = 0, l = buildCommands.length; i < l; i++) if (buildCommands[i].getBuilderName().equals(JavaCore.BUILDER_ID)) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private int initializeBuilder(int kind, boolean forBuild) throws CoreException { // some calls just need the nameEnvironment initialized so skip the rest this.javaProject = (JavaProject) JavaCore.create(this.currentProject); this.workspaceRoot = this.currentProject.getWorkspace().getRoot(); if (forBuild) { // cache the known participants for this project this.participants = JavaModelManager.getJavaModelManager().compilationParticipants.getCompilationParticipants(this.javaProject); if (this.participants != null) for (int i = 0, l = this.participants.length; i < l; i++) if (this.participants[i].aboutToBuild(this.javaProject) == CompilationParticipant.NEEDS_FULL_BUILD) kind = FULL_BUILD; // Flush the existing external files cache if this is the beginning of a build cycle String projectName = this.currentProject.getName(); if (builtProjects == null || builtProjects.contains(projectName)) { JavaModel.flushExternalFileCache(); builtProjects = new ArrayList(); } builtProjects.add(projectName); } this.binaryLocationsPerProject = new SimpleLookupTable(3); this.nameEnvironment = new NameEnvironment(this.workspaceRoot, this.javaProject, this.binaryLocationsPerProject, this.notifier); if (forBuild) { String filterSequence = this.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true); char[][] filters = filterSequence != null && filterSequence.length() > 0 ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { this.extraResourceFileFilters = null; this.extraResourceFolderFilters = null; } else { int fileCount = 0, folderCount = 0; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') folderCount++; else fileCount++; } this.extraResourceFileFilters = new char[fileCount][]; this.extraResourceFolderFilters = new String[folderCount]; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') this.extraResourceFolderFilters[--folderCount] = new String(f, 0, f.length - 1); else this.extraResourceFileFilters[--fileCount] = f; } } } return kind; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p) throws CoreException { IMarker[] markers = p.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); for (int i = 0, l = markers.length; i < l; i++) if (markers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean isWorthBuilding() throws CoreException { boolean abortBuilds = JavaCore.ABORT.equals(this.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true)); if (!abortBuilds) return true; // Abort build only if there are classpath errors if (isClasspathBroken(this.javaProject.getRawClasspath(), this.currentProject)) { if (DEBUG) System.out.println("Aborted build because project has classpath errors (incomplete or involved in cycle)"); //$NON-NLS-1$ removeProblemsAndTasksFor(this.currentProject); // remove all compilation problems IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.build_abortDueToClasspathProblems, new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); return false; } if (JavaCore.WARNING.equals(this.javaProject.getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true))) return true; // make sure all prereq projects have valid build states... only when aborting builds since projects in cycles do not have build states // except for projects involved in a 'warning' cycle (see below) IProject[] requiredProjects = getRequiredProjects(false); for (int i = 0, l = requiredProjects.length; i < l; i++) { IProject p = requiredProjects[i]; if (getLastState(p) == null) { // The prereq project has no build state: if this prereq project has a 'warning' cycle marker then allow build (see bug id 23357) JavaProject prereq = (JavaProject) JavaCore.create(p); if (prereq.hasCycleMarker() && JavaCore.WARNING.equals(this.javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))) { if (DEBUG) System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$ + " was not built since its part of a cycle"); //$NON-NLS-1$ continue; } if (!hasJavaBuilder(p)) { if (DEBUG) System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$ + " is not built by JavaBuilder"); //$NON-NLS-1$ continue; } if (DEBUG) System.out.println("Aborted build because prereq project " + p.getName() //$NON-NLS-1$ + " was not built"); //$NON-NLS-1$ removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { isClasspathBroken(prereq.getRawClasspath(), p) ? Messages.bind(Messages.build_prereqProjectHasClasspathProblems, p.getName()) : Messages.bind(Messages.build_prereqProjectMustBeRebuilt, p.getName()), new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); return false; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean checkForClassFileChanges(IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { IResource resource = binaryDelta.getResource(); // remember that if inclusion & exclusion patterns change then a full build is done boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null) && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns); switch(resource.getType()) { case IResource.FOLDER : if (isExcluded && md.inclusionPatterns == null) return true; // no need to go further with this delta since its children cannot be included IResourceDelta[] children = binaryDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!checkForClassFileChanges(children[i], md, segmentCount)) return false; return true; case IResource.FILE : if (!isExcluded && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) { // perform full build if a managed class file has been changed IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); if (this.newState.isKnownType(typePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$ return false; } return true; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean findSourceFiles(IResourceDelta delta) throws CoreException { ArrayList visited = this.makeOutputFolderConsistent ? new ArrayList(this.sourceLocations.length) : null; for (int i = 0, l = this.sourceLocations.length; i < l; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; if (this.makeOutputFolderConsistent && md.hasIndependentOutputFolder && !visited.contains(md.binaryFolder)) { // even a project which acts as its own source folder can have an independent/nested output folder visited.add(md.binaryFolder); IResourceDelta binaryDelta = delta.findMember(md.binaryFolder.getProjectRelativePath()); if (binaryDelta != null) { int segmentCount = binaryDelta.getFullPath().segmentCount(); IResourceDelta[] children = binaryDelta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!checkForClassFileChanges(children[j], md, segmentCount)) return false; } } if (md.sourceFolder.equals(this.javaBuilder.currentProject)) { // skip nested source & output folders when the project is a source folder int segmentCount = delta.getFullPath().segmentCount(); IResourceDelta[] children = delta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!isExcludedFromProject(children[j].getFullPath())) if (!findSourceFiles(children[j], md, segmentCount)) return false; } else { IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath()); if (sourceDelta != null) { if (sourceDelta.getKind() == IResourceDelta.REMOVED) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$ return false; // removed source folder should not make it here, but handle anyways (ADDED is supported) } int segmentCount = sourceDelta.getFullPath().segmentCount(); IResourceDelta[] children = sourceDelta.getAffectedChildren(); try { for (int j = 0, m = children.length; j < m; j++) if (!findSourceFiles(children[j], md, segmentCount)) return false; } catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow } } } this.notifier.checkCancel(); } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean findSourceFiles(IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { // When a package becomes a type or vice versa, expect 2 deltas, // one on the folder & one on the source file IResource resource = sourceDelta.getResource(); // remember that if inclusion & exclusion patterns change then a full build is done boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null) && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns); switch(resource.getType()) { case IResource.FOLDER : if (isExcluded && md.inclusionPatterns == null) return true; // no need to go further with this delta since its children cannot be included switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (!isExcluded) { IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); createFolder(addedPackagePath, md.binaryFolder); // ensure package exists in the output folder // see if any known source file is from the same package... classpath already includes new package if (this.sourceLocations.length > 1 && this.newState.isKnownPackage(addedPackagePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("Skipped dependents of added package " + addedPackagePath); //$NON-NLS-1$ } else { if (JavaBuilder.DEBUG) System.out.println("Found added package " + addedPackagePath); //$NON-NLS-1$ addDependentsOf(addedPackagePath, true); } } //$FALL-THROUGH$ collect all the source files case IResourceDelta.CHANGED : IResourceDelta[] children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; case IResourceDelta.REMOVED : if (isExcluded) { // since this folder is excluded then there is nothing to delete (from this md), but must walk any included subfolders children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; } IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); if (this.sourceLocations.length > 1) { for (int i = 0, l = this.sourceLocations.length; i < l; i++) { if (this.sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) { // only a package fragment was removed, same as removing multiple source files createFolder(removedPackagePath, md.binaryFolder); // ensure package exists in the output folder IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren(); for (int j = 0, m = removedChildren.length; j < m; j++) if (!findSourceFiles(removedChildren[j], md, segmentCount)) return false; return true; } } } if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // same idea as moving a source file // see bug 163200 IResource movedFolder = this.javaBuilder.workspaceRoot.getFolder(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFolder); } IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath); if (removedPackageFolder.exists()) removedPackageFolder.delete(IResource.FORCE, null); // add dependents even when the package thinks it does not exist to be on the safe side if (JavaBuilder.DEBUG) System.out.println("Found removed package " + removedPackagePath); //$NON-NLS-1$ addDependentsOf(removedPackagePath, true); this.newState.removePackage(sourceDelta); } return true; case IResource.FILE : if (isExcluded) return true; String resourceName = resource.getName(); if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) { IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); String typeLocator = resource.getProjectRelativePath().toString(); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (JavaBuilder.DEBUG) System.out.println("Compile this added source file " + typeLocator); //$NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); String typeName = typePath.toString(); if (!this.newState.isDuplicateLocator(typeName, typeLocator)) { // adding dependents results in 2 duplicate errors if (JavaBuilder.DEBUG) System.out.println("Found added source file " + typeName); //$NON-NLS-1$ addDependentsOf(typePath, true); } return true; case IResourceDelta.REMOVED : char[][] definedTypeNames = this.newState.getDefinedTypeNamesFor(typeLocator); if (definedTypeNames == null) { // defined a single type matching typePath removeClassFile(typePath, md.binaryFolder); if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // remove problems and tasks for a compilation unit that is being moved (to another package or renamed) // if the target file is a compilation unit, the new cu will be recompiled // if the target file is a non-java resource, then markers are removed // see bug 2857 IResource movedFile = this.javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFile); } } else { if (JavaBuilder.DEBUG) System.out.println("Found removed source file " + typePath.toString()); //$NON-NLS-1$ addDependentsOf(typePath, true); // add dependents of the source file since it may be involved in a name collision if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type IPath packagePath = typePath.removeLastSegments(1); for (int i = 0, l = definedTypeNames.length; i < l; i++) removeClassFile(packagePath.append(new String(definedTypeNames[i])), md.binaryFolder); } } this.newState.removeLocator(typeLocator); return true; case IResourceDelta.CHANGED : if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (JavaBuilder.DEBUG) System.out.println("Compile this changed source file " + typeLocator); //$NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); } return true; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) { // perform full build if a managed class file has been changed if (this.makeOutputFolderConsistent) { IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); if (this.newState.isKnownType(typePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$ return false; } } return true; } else if (md.hasIndependentOutputFolder) { if (this.javaBuilder.filterExtraResource(resource)) return true; // copy all other resource deltas to the output folder IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount); IResource outputFile = md.binaryFolder.getFile(resourcePath); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying added file " + resourcePath); //$NON-NLS-1$ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); return true; case IResourceDelta.REMOVED : if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting removed file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } return true; case IResourceDelta.CHANGED : if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying changed file " + resourcePath); //$NON-NLS-1$ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); } return true; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void removeClassFile(IPath typePath, IContainer outputFolder) throws CoreException { if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type this.newState.removeQualifiedTypeName(typePath.toString()); // add dependents even when the type thinks it does not exist to be on the safe side if (JavaBuilder.DEBUG) System.out.println("Found removed type " + typePath); //$NON-NLS-1$ addDependentsOf(typePath, true); // when member types are removed, their enclosing type is structurally changed } IFile classFile = outputFolder.getFile(typePath.addFileExtension(SuffixConstants.EXTENSION_class)); if (classFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting class file of removed type " + typePath); //$NON-NLS-1$ classFile.delete(IResource.FORCE, null); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void removeSecondaryTypes() throws CoreException { if (this.secondaryTypesToRemove != null) { // delayed deleting secondary types until the end of the compile loop Object[] keyTable = this.secondaryTypesToRemove.keyTable; Object[] valueTable = this.secondaryTypesToRemove.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { IContainer outputFolder = (IContainer) keyTable[i]; if (outputFolder != null) { ArrayList paths = (ArrayList) valueTable[i]; for (int j = 0, m = paths.size(); j < m; j++) removeClassFile((IPath) paths.get(j), outputFolder); } } this.secondaryTypesToRemove = null; if (this.previousSourceFiles != null) this.previousSourceFiles = null; // cannot optimize recompile case when a secondary type is deleted, see 181269 } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { IMarker[] markers = JavaBuilder.getProblemsFor(sourceFile.resource); CategorizedProblem[] problems = result.getProblems(); if (problems == null && markers.length == 0) return; this.notifier.updateProblemCounts(markers, problems); JavaBuilder.removeProblemsFor(sourceFile.resource); storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { IMarker[] markers = JavaBuilder.getTasksFor(sourceFile.resource); CategorizedProblem[] tasks = result.getTasks(); if (tasks == null && markers.length == 0) return; JavaBuilder.removeTasksFor(sourceFile.resource); storeTasksFor(sourceFile, tasks); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void writeClassFileContents(ClassFile classfile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // Before writing out the class file, compare it to the previous file // If structural changes occurred then add dependent source files byte[] bytes = classfile.getBytes(); if (file.exists()) { if (writeClassFileCheck(file, qualifiedFileName, bytes) || compilationUnit.updateClassFile) { // see 46093 if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(new ByteArrayInputStream(bytes), true, false, null); } else if (JavaBuilder.DEBUG) { System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$ } } else { if (isTopLevelType) addDependentsOf(new Path(qualifiedFileName), true); // new type if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow } } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException { try { byte[] oldBytes = Util.getResourceContentsAsByteArray(file); notEqual : if (newBytes.length == oldBytes.length) { for (int i = newBytes.length; --i >= 0;) if (newBytes[i] != oldBytes[i]) break notEqual; return false; // bytes are identical so skip them } URI location = file.getLocationURI(); if (location == null) return false; // unable to determine location of this class file String filePath = location.getSchemeSpecificPart(); ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { if (JavaBuilder.DEBUG) System.out.println("Type has structural changes " + fileName); //$NON-NLS-1$ addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } } catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } return true; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void addAllSourceFiles(final ArrayList sourceFiles) throws CoreException { for (int i = 0, l = this.sourceLocations.length; i < l; i++) { final ClasspathMultiDirectory sourceLocation = this.sourceLocations[i]; final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; final char[][] inclusionPatterns = sourceLocation.inclusionPatterns; final boolean isAlsoProject = sourceLocation.sourceFolder.equals(this.javaBuilder.currentProject); final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); final IContainer outputFolder = sourceLocation.binaryFolder; final boolean isOutputFolder = sourceLocation.sourceFolder.equals(outputFolder); sourceLocation.sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; sourceFiles.add(new SourceFile((IFile) resource, sourceLocation)); } return false; case IResource.FOLDER : IPath folderPath = null; if (isAlsoProject) if (isExcludedFromProject(folderPath = proxy.requestFullPath())) return false; if (exclusionPatterns != null) { if (folderPath == null) folderPath = proxy.requestFullPath(); if (Util.isExcluded(folderPath, inclusionPatterns, exclusionPatterns, true)) { // must walk children if inclusionPatterns != null, can skip them if == null // but folder is excluded so do not create it in the output folder return inclusionPatterns != null; } } if (!isOutputFolder) { if (folderPath == null) folderPath = proxy.requestFullPath(); String packageName = folderPath.lastSegment(); if (packageName.length() > 0) { String sourceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaConventions.validatePackageName(packageName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR) createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); } } } return true; } }, IResource.NONE ); this.notifier.checkCancel(); } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; sourceFiles.add(new SourceFile((IFile) resource, sourceLocation)); } return false; case IResource.FOLDER : IPath folderPath = null; if (isAlsoProject) if (isExcludedFromProject(folderPath = proxy.requestFullPath())) return false; if (exclusionPatterns != null) { if (folderPath == null) folderPath = proxy.requestFullPath(); if (Util.isExcluded(folderPath, inclusionPatterns, exclusionPatterns, true)) { // must walk children if inclusionPatterns != null, can skip them if == null // but folder is excluded so do not create it in the output folder return inclusionPatterns != null; } } if (!isOutputFolder) { if (folderPath == null) folderPath = proxy.requestFullPath(); String packageName = folderPath.lastSegment(); if (packageName.length() > 0) { String sourceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaConventions.validatePackageName(packageName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR) createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); } } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void copyResource(IResource source, IResource destination) throws CoreException { IPath destPath = destination.getFullPath(); try { source.copy(destPath, IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; } Util.setReadOnly(destination, false); // just in case the original was read only }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected IContainer createFolder(IPath packagePath, IContainer outputFolder) throws CoreException { if (packagePath.isEmpty()) return outputFolder; IFolder folder = outputFolder.getFolder(packagePath); if (!folder.exists()) { createFolder(packagePath.removeLastSegments(1), outputFolder); folder.create(IResource.FORCE | IResource.DERIVED, true, null); } return folder; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException { if (sourceFile == null || problems == null || problems.length == 0) return; // once a classpath error is found, ignore all other problems for this project so the user can see the main error // but still try to compile as many source files as possible to help the case when the base libraries are in source if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file IResource resource = sourceFile.resource; HashSet managedMarkerTypes = JavaModelManager.getJavaModelManager().compilationParticipants.managedMarkerTypes(); for (int i = 0, l = problems.length; i < l; i++) { CategorizedProblem problem = problems[i]; int id = problem.getID(); // handle missing classfile situation if (id == IProblem.IsClassPathCorrect) { String missingClassfileName = problem.getArguments()[0]; if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_incompleteClassPath, missingClassfileName)); boolean isInvalidClasspathError = JavaCore.ERROR.equals(this.javaBuilder.javaProject.getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true)); // insert extra classpath problem, and make it the only problem for this project (optional) if (isInvalidClasspathError && JavaCore.ABORT.equals(this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true))) { JavaBuilder.removeProblemsAndTasksFor(this.javaBuilder.currentProject); // make this the only problem for this project this.keepStoringProblemMarkers = false; } IMarker marker = this.javaBuilder.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_incompleteClassPath, missingClassfileName), new Integer(isInvalidClasspathError ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); // even if we're not keeping more markers, still fall through rest of the problem reporting, so that offending // IsClassPathCorrect problem gets recorded since it may help locate the offending reference } String markerType = problem.getMarkerType(); boolean managedProblem = false; if (IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER.equals(markerType) || (managedProblem = managedMarkerTypes.contains(markerType))) { IMarker marker = resource.createMarker(markerType); String[] attributeNames = JAVA_PROBLEM_MARKER_ATTRIBUTE_NAMES; int standardLength = attributeNames.length; String[] allNames = attributeNames; int managedLength = managedProblem ? 0 : 1; String[] extraAttributeNames = problem.getExtraMarkerAttributeNames(); int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length; if (managedLength > 0 || extraLength > 0) { allNames = new String[standardLength + managedLength + extraLength]; System.arraycopy(attributeNames, 0, allNames, 0, standardLength); if (managedLength > 0) allNames[standardLength] = IMarker.SOURCE_ID; System.arraycopy(extraAttributeNames, 0, allNames, standardLength + managedLength, extraLength); } Object[] allValues = new Object[allNames.length]; // standard attributes int index = 0; allValues[index++] = problem.getMessage(); // message allValues[index++] = problem.isError() ? S_ERROR : S_WARNING; // severity allValues[index++] = new Integer(id); // ID allValues[index++] = new Integer(problem.getSourceStart()); // start int end = problem.getSourceEnd(); allValues[index++] = new Integer(end > 0 ? end + 1 : end); // end allValues[index++] = new Integer(problem.getSourceLineNumber()); // line allValues[index++] = Util.getProblemArgumentsForMarker(problem.getArguments()); // arguments allValues[index++] = new Integer(problem.getCategoryID()); // category ID // SOURCE_ID attribute for JDT problems if (managedLength > 0) allValues[index++] = JavaBuilder.SOURCE_ID; // optional extra attributes if (extraLength > 0) System.arraycopy(problem.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength); marker.setAttributes(allNames, allValues); if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file } } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void storeTasksFor(SourceFile sourceFile, CategorizedProblem[] tasks) throws CoreException { if (sourceFile == null || tasks == null || tasks.length == 0) return; IResource resource = sourceFile.resource; for (int i = 0, l = tasks.length; i < l; i++) { CategorizedProblem task = tasks[i]; if (task.getID() == IProblem.Task) { IMarker marker = resource.createMarker(IJavaModelMarker.TASK_MARKER); Integer priority = P_NORMAL; String compilerPriority = task.getArguments()[2]; if (JavaCore.COMPILER_TASK_PRIORITY_HIGH.equals(compilerPriority)) priority = P_HIGH; else if (JavaCore.COMPILER_TASK_PRIORITY_LOW.equals(compilerPriority)) priority = P_LOW; String[] attributeNames = JAVA_TASK_MARKER_ATTRIBUTE_NAMES; int standardLength = attributeNames.length; String[] allNames = attributeNames; String[] extraAttributeNames = task.getExtraMarkerAttributeNames(); int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length; if (extraLength > 0) { allNames = new String[standardLength + extraLength]; System.arraycopy(attributeNames, 0, allNames, 0, standardLength); System.arraycopy(extraAttributeNames, 0, allNames, standardLength, extraLength); } Object[] allValues = new Object[allNames.length]; // standard attributes int index = 0; allValues[index++] = task.getMessage(); allValues[index++] = priority; allValues[index++] = new Integer(task.getID()); allValues[index++] = new Integer(task.getSourceStart()); allValues[index++] = new Integer(task.getSourceEnd() + 1); allValues[index++] = new Integer(task.getSourceLineNumber()); allValues[index++] = Boolean.FALSE; allValues[index++] = JavaBuilder.SOURCE_ID; // optional extra attributes if (extraLength > 0) System.arraycopy(task.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength); marker.setAttributes(allNames, allValues); } } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { CategorizedProblem[] problems = result.getProblems(); if (problems == null || problems.length == 0) return; this.notifier.updateProblemCounts(problems); storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { CategorizedProblem[] tasks = result.getTasks(); if (tasks == null || tasks.length == 0) return; storeTasksFor(sourceFile, tasks); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected char[] writeClassFile(ClassFile classFile, SourceFile compilationUnit, boolean isTopLevelType) throws CoreException { String fileName = new String(classFile.fileName()); // the qualified type name "p1/p2/A" IPath filePath = new Path(fileName); IContainer outputFolder = compilationUnit.sourceLocation.binaryFolder; IContainer container = outputFolder; if (filePath.segmentCount() > 1) { container = createFolder(filePath.removeLastSegments(1), outputFolder); filePath = new Path(filePath.lastSegment()); } IFile file = container.getFile(filePath.addFileExtension(SuffixConstants.EXTENSION_class)); writeClassFileContents(classFile, file, fileName, isTopLevelType, compilationUnit); // answer the name of the class file as in Y or Y$M return filePath.lastSegment().toCharArray(); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void writeClassFileContents(ClassFile classFile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // InputStream input = new SequenceInputStream( // new ByteArrayInputStream(classFile.header, 0, classFile.headerOffset), // new ByteArrayInputStream(classFile.contents, 0, classFile.contentsOffset)); InputStream input = new ByteArrayInputStream(classFile.getBytes()); if (file.exists()) { // Deal with shared output folders... last one wins... no collision cases detected if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(input, true, false, null); } else { // Default implementation just writes out the bytes for the new class file... if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ file.create(input, IResource.FORCE | IResource.DERIVED, null); } }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void cleanOutputFolders(boolean copyBack) throws CoreException { boolean deleteAll = JavaCore.CLEAN.equals( this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, true)); if (deleteAll) { if (this.javaBuilder.participants != null) for (int i = 0, l = this.javaBuilder.participants.length; i < l; i++) this.javaBuilder.participants[i].cleanStarting(this.javaBuilder.javaProject); ArrayList visited = new ArrayList(this.sourceLocations.length); for (int i = 0, l = this.sourceLocations.length; i < l; i++) { this.notifier.subTask(Messages.bind(Messages.build_cleaningOutput, this.javaBuilder.currentProject.getName())); ClasspathMultiDirectory sourceLocation = this.sourceLocations[i]; if (sourceLocation.hasIndependentOutputFolder) { IContainer outputFolder = sourceLocation.binaryFolder; if (!visited.contains(outputFolder)) { visited.add(outputFolder); IResource[] members = outputFolder.members(); for (int j = 0, m = members.length; j < m; j++) { IResource member = members[j]; if (!member.isDerived()) { member.accept( new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { resource.setDerived(true, null); return resource.getType() != IResource.FILE; } } ); } member.delete(IResource.FORCE, null); } } this.notifier.checkCancel(); if (copyBack) copyExtraResourcesBack(sourceLocation, true); } else { boolean isOutputFolder = sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder); final char[][] exclusionPatterns = isOutputFolder ? sourceLocation.exclusionPatterns : null; // ignore exclusionPatterns if output folder == another source folder... not this one final char[][] inclusionPatterns = isOutputFolder ? sourceLocation.inclusionPatterns : null; // ignore inclusionPatterns if output folder == another source folder... not this one sourceLocation.binaryFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; if (!resource.isDerived()) resource.setDerived(true, null); resource.delete(IResource.FORCE, null); } return false; } if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(proxy.requestFullPath(), null, exclusionPatterns, true)) return false; BatchImageBuilder.this.notifier.checkCancel(); return true; } }, IResource.NONE ); this.notifier.checkCancel(); } this.notifier.checkCancel(); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResource resource) throws CoreException { resource.setDerived(true, null); return resource.getType() != IResource.FILE; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; if (!resource.isDerived()) resource.setDerived(true, null); resource.delete(IResource.FORCE, null); } return false; } if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(proxy.requestFullPath(), null, exclusionPatterns, true)) return false; BatchImageBuilder.this.notifier.checkCancel(); return true; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void copyExtraResourcesBack(ClasspathMultiDirectory sourceLocation, final boolean deletedAll) throws CoreException { // When, if ever, does a builder need to copy resources files (not .java or .class) into the output folder? // If we wipe the output folder at the beginning of the build then all 'extra' resources must be copied to the output folder. this.notifier.subTask(Messages.build_copyingResources); final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; final char[][] inclusionPatterns = sourceLocation.inclusionPatterns; final IContainer outputFolder = sourceLocation.binaryFolder; final boolean isAlsoProject = sourceLocation.sourceFolder.equals(this.javaBuilder.currentProject); sourceLocation.sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName()) || org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) return false; resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount); IResource copiedResource = outputFolder.getFile(partialPath); if (copiedResource.exists()) { if (deletedAll) { IResource originalResource = findOriginalResource(partialPath); String id = originalResource.getFullPath().removeFirstSegments(1).toString(); createProblemFor( resource, null, Messages.bind(Messages.build_duplicateResource, id), BatchImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true)); return false; } copiedResource.delete(IResource.FORCE, null); // last one wins } createFolder(partialPath.removeLastSegments(1), outputFolder); // ensure package folder exists copyResource(resource, copiedResource); return false; case IResource.FOLDER : resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (isAlsoProject && isExcludedFromProject(resource.getFullPath())) return false; // the sourceFolder == project if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(resource.getFullPath(), null, exclusionPatterns, true)) return false; } return true; } }, IResource.NONE ); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName()) || org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) return false; resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount); IResource copiedResource = outputFolder.getFile(partialPath); if (copiedResource.exists()) { if (deletedAll) { IResource originalResource = findOriginalResource(partialPath); String id = originalResource.getFullPath().removeFirstSegments(1).toString(); createProblemFor( resource, null, Messages.bind(Messages.build_duplicateResource, id), BatchImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true)); return false; } copiedResource.delete(IResource.FORCE, null); // last one wins } createFolder(partialPath.removeLastSegments(1), outputFolder); // ensure package folder exists copyResource(resource, copiedResource); return false; case IResource.FOLDER : resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (isAlsoProject && isExcludedFromProject(resource.getFullPath())) return false; // the sourceFolder == project if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(resource.getFullPath(), null, exclusionPatterns, true)) return false; } return true; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException { if (sourceFile == null || problems == null || problems.length == 0) return; for (int i = problems.length; --i >= 0;) { CategorizedProblem problem = problems[i]; if (problem != null && problem.getID() == IProblem.UndefinedType) { if (this.typeLocatorsWithUndefinedTypes == null) this.typeLocatorsWithUndefinedTypes = new StringSet(3); this.typeLocatorsWithUndefinedTypes.add(sourceFile.typeLocator()); break; } } super.storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public IFolder createLinkFolder(IPath externalFolderPath, boolean refreshIfExistAlready, IProgressMonitor monitor) throws CoreException { IProject externalFoldersProject = createExternalFoldersProject(monitor); // run outside synchronized as this can create a resource return createLinkFolder(externalFolderPath, refreshIfExistAlready, externalFoldersProject, monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private IFolder createLinkFolder(IPath externalFolderPath, boolean refreshIfExistAlready, IProject externalFoldersProject, IProgressMonitor monitor) throws CoreException { IFolder result = addFolder(externalFolderPath, externalFoldersProject, false); if (!result.exists()) result.createLink(externalFolderPath, IResource.ALLOW_MISSING_LOCAL, monitor); else if (refreshIfExistAlready) result.refreshLocal(IResource.DEPTH_INFINITE, monitor); return result; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public void cleanUp(IProgressMonitor monitor) throws CoreException { ArrayList toDelete = getFoldersToCleanUp(monitor); if (toDelete == null) return; for (Iterator iterator = toDelete.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); IFolder folder = (IFolder) entry.getValue(); folder.delete(true, monitor); IPath key = (IPath) entry.getKey(); this.folders.remove(key); } IProject project = getExternalFoldersProject(); if (project.isAccessible() && project.members().length == 1/*remaining member is .project*/) project.delete(true, monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private ArrayList getFoldersToCleanUp(IProgressMonitor monitor) throws CoreException { DeltaProcessingState state = JavaModelManager.getDeltaState(); HashMap roots = state.roots; HashMap sourceAttachments = state.sourceAttachments; if (roots == null && sourceAttachments == null) return null; Map knownFolders = getFolders(); ArrayList result = null; synchronized (knownFolders) { Iterator iterator = knownFolders.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); IPath path = (IPath) entry.getKey(); if ((roots != null && !roots.containsKey(path)) && (sourceAttachments != null && !sourceAttachments.containsKey(path))) { if (entry.getValue() != null) { if (result == null) result = new ArrayList(); result.add(entry); } } } } return result; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public IProject createExternalFoldersProject(IProgressMonitor monitor) throws CoreException { IProject project = getExternalFoldersProject(); if (!project.isAccessible()) { if (!project.exists()) { createExternalFoldersProject(project, monitor); } openExternalFoldersProject(project, monitor); } return project; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private void openExternalFoldersProject(IProject project, IProgressMonitor monitor) throws CoreException { try { project.open(monitor); } catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); } }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private void createExternalFoldersProject(IProject project, IProgressMonitor monitor) throws CoreException { IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName()); IPath stateLocation = JavaCore.getPlugin().getStateLocation(); desc.setLocation(stateLocation.append(EXTERNAL_PROJECT_NAME)); project.create(desc, IResource.HIDDEN, monitor); }
// in model/org/eclipse/jdt/internal/core/UserLibraryClasspathContainerInitializer.java
public void initialize(IPath containerPath, IJavaProject project) throws CoreException { if (isUserLibraryContainer(containerPath)) { String userLibName = containerPath.segment(1); UserLibrary userLibrary = JavaModelManager.getUserLibraryManager().getUserLibrary(userLibName); if (userLibrary != null) { UserLibraryClasspathContainer container = new UserLibraryClasspathContainer(userLibName); JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project }, new IClasspathContainer[] { container }, null); } else if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_no_user_library_found(project, userLibName); } } else if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_not_a_user_library(project, containerPath); } }
// in model/org/eclipse/jdt/internal/core/UserLibraryClasspathContainerInitializer.java
public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion) throws CoreException { if (isUserLibraryContainer(containerPath)) { String name = containerPath.segment(1); if (containerSuggestion != null) { JavaModelManager.getUserLibraryManager().setUserLibrary(name, containerSuggestion.getClasspathEntries(), containerSuggestion.getKind() == IClasspathContainer.K_SYSTEM); } else { JavaModelManager.getUserLibraryManager().removeUserLibrary(name); } // update of affected projects was done as a consequence of setUserLibrary() or removeUserLibrary() } }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
public ZipFile getJar() throws CoreException { return JavaModelManager.getJavaModelManager().getZipFile(getPath()); }
// 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/RegionBasedTypeHierarchy.java
protected void compute() throws JavaModelException, CoreException { HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this); builder.build(this.computeSubtypes); }
// in model/org/eclipse/jdt/internal/core/JarEntryResource.java
protected ZipFile getZipFile() throws CoreException { if (this.parent instanceof IPackageFragment) { JarPackageFragmentRoot root = (JarPackageFragmentRoot) ((IPackageFragment) this.parent).getParent(); return root.getJar(); } else if (this.parent instanceof JarPackageFragmentRoot) { return ((JarPackageFragmentRoot) this.parent).getJar(); } else return ((JarEntryDirectory) this.parent).getZipFile(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void saveExternalLibTimeStamps() throws CoreException { if (this.externalTimeStamps == null) return; // cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 ) HashSet toRemove = new HashSet(); if (this.roots != null) { Enumeration keys = this.externalTimeStamps.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (this.roots.get(key) == null) { toRemove.add(key); } } } File timestamps = getTimeStampsFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps))); out.writeInt(this.externalTimeStamps.size() - toRemove.size()); Iterator entries = this.externalTimeStamps.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IPath key = (IPath) entry.getKey(); if (!toRemove.contains(key)) { out.writeUTF(key.toPortableString()); Long timestamp = (Long) entry.getValue(); out.writeLong(timestamp.longValue()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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) // non local file system localFile= fileStore.toLocalFile(EFS.CACHE, monitor); return localFile; }
// 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/ProjectReferenceChange.java
public void run(IProgressMonitor monitor) throws CoreException { IProjectDescription description = projectResource.getDescription(); description.setDynamicReferences(requiredProjectArray); projectResource.setDescription(description, IResource.AVOID_NATURE_CONFIG, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected void addToBuildSpec(String builderID) throws CoreException { IProjectDescription description = this.project.getDescription(); int javaCommandIndex = getJavaCommandIndex(description.getBuildSpec()); if (javaCommandIndex == -1) { // Add a Java command to the build spec ICommand command = description.newCommand(); command.setBuilderName(builderID); setJavaCommand(description, command); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void configure() throws CoreException { // register Java builder addToBuildSpec(JavaCore.BUILDER_ID); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void deconfigure() throws CoreException { // deregister Java builder removeFromBuildSpec(JavaCore.BUILDER_ID); // remove .classpath file // getProject().getFile(ClasspathHelper.CLASSPATH_FILENAME).delete(false, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public String getSharedProperty(String key) throws CoreException { String property = null; IFile rscFile = this.project.getFile(key); if (rscFile.exists()) { byte[] bytes = Util.getResourceContentsAsByteArray(rscFile); try { property = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); } } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location != null) { File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file != null && file.exists()) { byte[] bytes; try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { return null; } try { property = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); } } } } return property; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected void removeFromBuildSpec(String builderID) throws CoreException { IProjectDescription description = this.project.getDescription(); ICommand[] commands = description.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { if (commands[i].getBuilderName().equals(builderID)) { ICommand[] newCommands = new ICommand[commands.length - 1]; System.arraycopy(commands, 0, newCommands, 0, i); System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1); description.setBuildSpec(newCommands); this.project.setDescription(description, null); return; } } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
private void setJavaCommand( IProjectDescription description, ICommand newCommand) throws CoreException { ICommand[] oldBuildSpec = description.getBuildSpec(); int oldJavaCommandIndex = getJavaCommandIndex(oldBuildSpec); ICommand[] newCommands; if (oldJavaCommandIndex == -1) { // Add a Java build spec before other builders (1FWJK7I) newCommands = new ICommand[oldBuildSpec.length + 1]; System.arraycopy(oldBuildSpec, 0, newCommands, 1, oldBuildSpec.length); newCommands[0] = newCommand; } else { oldBuildSpec[oldJavaCommandIndex] = newCommand; newCommands = oldBuildSpec; } // Commit the spec change into the project description.setBuildSpec(newCommands); this.project.setDescription(description, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setSharedProperty(String key, String value) throws CoreException { IFile rscFile = this.project.getFile(key); byte[] bytes = null; try { bytes = value.getBytes(org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); } InputStream inputStream = new ByteArrayInputStream(bytes); // update the resource content if (rscFile.exists()) { if (rscFile.isReadOnly()) { // provide opportunity to checkout read-only .classpath file (23984) ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, null); } rscFile.setContents(inputStream, IResource.FORCE, null); } else { rscFile.create(inputStream, IResource.FORCE, null); } }
// in model/org/eclipse/jdt/core/ClasspathContainerInitializer.java
public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion) throws CoreException { // By default, classpath container initializers do not accept updating containers }
// in model/org/eclipse/jdt/core/JavaCore.java
public void configureJavaElementMarker(IMarker marker, IJavaElement element) throws CoreException { if (element instanceof IMember) element = ((IMember) element).getClassFile(); if (marker != null && element != null) marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier()); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException { try { if (monitor != null) { monitor.beginTask(Messages.javamodel_initialization, 100); monitor.subTask(Messages.javamodel_configuring_classpath_containers); } // initialize all containers and variables JavaModelManager manager = JavaModelManager.getJavaModelManager(); SubProgressMonitor subMonitor = null; try { if (monitor != null) { subMonitor = new SubProgressMonitor(monitor, 50); // 50% of the time is spent in initializing containers and variables subMonitor.beginTask("", 100); //$NON-NLS-1$ subMonitor.worked(5); // give feedback to the user that something is happening manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(subMonitor); } if (manager.forceBatchInitializations(true/*initAfterLoad*/)) { // if no other thread has started the batch container initializations manager.getClasspathContainer(Path.EMPTY, null); // force the batch initialization } else { // else wait for the batch initialization to finish while (manager.batchContainerInitializations == JavaModelManager.BATCH_INITIALIZATION_IN_PROGRESS) { if (subMonitor != null) { subMonitor.subTask(manager.batchContainerInitializationsProgress.subTaskName); subMonitor.worked(manager.batchContainerInitializationsProgress.getWorked()); } synchronized(manager) { try { manager.wait(100); } catch (InterruptedException e) { // continue } } } } } finally { if (subMonitor != null) subMonitor.done(); manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(null); } // avoid leaking source attachment properties (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183413 ) // and recreate links for external folders if needed if (monitor != null) monitor.subTask(Messages.javamodel_resetting_source_attachment_properties); final IJavaProject[] projects = manager.getJavaModel().getJavaProjects(); HashSet visitedPaths = new HashSet(); ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager(); for (int i = 0, length = projects.length; i < length; i++) { JavaProject javaProject = (JavaProject) projects[i]; IClasspathEntry[] classpath; try { classpath = javaProject.getResolvedClasspath(); } catch (JavaModelException e) { // project no longer exist: ignore continue; } if (classpath != null) { for (int j = 0, length2 = classpath.length; j < length2; j++) { IClasspathEntry entry = classpath[j]; if (entry.getSourceAttachmentPath() != null) { IPath entryPath = entry.getPath(); if (visitedPaths.add(entryPath)) { Util.setSourceAttachmentProperty(entryPath, null); } } // else source might have been attached by IPackageFragmentRoot#attachSource(...), we keep it if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath entryPath = entry.getPath(); if (ExternalFoldersManager.isExternalFolderPath(entryPath) && externalFoldersManager.getFolder(entryPath) == null) { externalFoldersManager.addFolder(entryPath, true); } } } } } try { externalFoldersManager.createPendingFolders(monitor); } catch(JavaModelException jme) { // Creation of external folder project failed. Log it and continue; Util.log(jme, "Error while processing external folders"); //$NON-NLS-1$ } // initialize delta state if (monitor != null) monitor.subTask(Messages.javamodel_initializing_delta_state); manager.deltaState.rootsAreStale = true; // in case it was already initialized before we cleaned up the source attachment proprties manager.deltaState.initializeRoots(true/*initAfteLoad*/); // dummy query for waiting until the indexes are ready if (monitor != null) monitor.subTask(Messages.javamodel_configuring_searchengine); SearchEngine engine = new SearchEngine(); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); try { engine.searchAllTypeNames( null, SearchPattern.R_EXACT_MATCH, "!@$#!@".toCharArray(), //$NON-NLS-1$ SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.CLASS, scope, new TypeNameRequestor() { public void acceptType( int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { // no type to accept } }, // will not activate index query caches if indexes are not ready, since it would take to long // to wait until indexes are fully rebuild IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search ); } catch (JavaModelException e) { // /search failed: ignore } catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed } // check if the build state version number has changed since last session // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=98969) if (monitor != null) monitor.subTask(Messages.javamodel_getting_build_state_number); QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "stateVersionNumber"); //$NON-NLS-1$ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); String versionNumber = null; try { versionNumber = root.getPersistentProperty(qName); } catch (CoreException e) { // could not read version number: consider it is new } final JavaModel model = manager.getJavaModel(); String newVersionNumber = Byte.toString(State.VERSION); if (!newVersionNumber.equals(versionNumber)) { // build state version number has changed: touch every projects to force a rebuild if (JavaBuilder.DEBUG) System.out.println("Build state version number has changed"); //$NON-NLS-1$ IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor progressMonitor2) throws CoreException { for (int i = 0, length = projects.length; i < length; i++) { IJavaProject project = projects[i]; try { if (JavaBuilder.DEBUG) System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$ project.getProject().touch(progressMonitor2); } catch (CoreException e) { // could not touch this project: ignore } } } }; if (monitor != null) monitor.subTask(Messages.javamodel_building_after_upgrade); try { ResourcesPlugin.getWorkspace().run(runnable, monitor); } catch (CoreException e) { // could not touch all projects } try { root.setPersistentProperty(qName, newVersionNumber); } catch (CoreException e) { Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$ } } // ensure external jars are refreshed (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93668) try { if (monitor != null) monitor.subTask(Messages.javamodel_refreshing_external_jars); model.refreshExternalArchives( null/*refresh all projects*/, monitor == null ? null : new SubProgressMonitor(monitor, 1) // 1% of the time is spent in jar refresh ); } catch (JavaModelException e) { // refreshing failed: ignore } } finally { if (monitor != null) monitor.done(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
public void run(IProgressMonitor progressMonitor2) throws CoreException { for (int i = 0, length = projects.length; i < length; i++) { IJavaProject project = projects[i]; try { if (JavaBuilder.DEBUG) System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$ project.getProject().touch(progressMonitor2); } catch (CoreException e) { // could not touch this project: ignore } } }
// in model/org/eclipse/jdt/core/JavaCore.java
public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException { // only match units or classfiles if (element instanceof IMember){ IMember member = (IMember) element; if (member.isBinary()){ element = member.getClassFile(); } else { element = member.getCompilationUnit(); } } if (element == null) return false; if (marker == null) return false; String markerHandleId = (String)marker.getAttribute(ATT_HANDLE_ID); if (markerHandleId == null) return false; IJavaElement markerElement = JavaCore.create(markerHandleId); while (true){ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs. // cycle through enclosing types in case marker is associated with a classfile (15568) if (markerElement instanceof IClassFile){ IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType(); if (enclosingType != null){ markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile continue; } } break; } return false; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException { // only match units or classfiles if (element instanceof IMember){ IMember member = (IMember) element; if (member.isBinary()){ element = member.getClassFile(); } else { element = member.getCompilationUnit(); } } if (element == null) return false; if (markerDelta == null) return false; String markerDeltarHandleId = (String)markerDelta.getAttribute(ATT_HANDLE_ID); if (markerDeltarHandleId == null) return false; IJavaElement markerElement = JavaCore.create(markerDeltarHandleId); while (true){ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs. // cycle through enclosing types in case marker is associated with a classfile (15568) if (markerElement instanceof IClassFile){ IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType(); if (enclosingType != null){ markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile continue; } } break; } return false; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException { run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void run(IWorkspaceRunnable action, ISchedulingRule rule, IProgressMonitor monitor) throws CoreException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); if (workspace.isTreeLocked()) { new BatchOperation(action).run(monitor); } else { // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, monitor); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(boolean ignoreComments) throws CoreException { int curr= 0; do { try { curr= this.scanner.getNextToken(); if (curr == TerminalTokens.TokenNameEOF) { throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$ } } catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); } } while (ignoreComments && isComment(curr)); return curr; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(int offset, boolean ignoreComments) throws CoreException { setOffset(offset); return readNext(ignoreComments); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getNextStartOffset(int offset, boolean ignoreComments) throws CoreException { readNext(offset, ignoreComments); return getCurrentStartOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getNextEndOffset(int offset, boolean ignoreComments) throws CoreException { readNext(offset, ignoreComments); return getCurrentEndOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public void readToToken(int tok) throws CoreException { int curr= 0; do { curr= readNext(false); } while (curr != tok); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public void readToToken(int tok, int offset) throws CoreException { setOffset(offset); readToToken(tok); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getTokenStartOffset(int token, int startOffset) throws CoreException { readToToken(token, startOffset); return getCurrentStartOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getTokenEndOffset(int token, int startOffset) throws CoreException { readToToken(token, startOffset); return getCurrentEndOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getPreviousTokenEndOffset(int token, int startOffset) throws CoreException { setOffset(startOffset); int res= startOffset; int curr= readNext(false); while (curr != token) { res= getCurrentEndOffset(); curr= readNext(false); } return res; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public final TextEdit rewriteImports(IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor= new NullProgressMonitor(); } try { monitor.beginTask(Messages.bind(Messages.importRewrite_processDescription), 2); if (!hasRecordedChanges()) { this.createdImports= CharOperation.NO_STRINGS; this.createdStaticImports= CharOperation.NO_STRINGS; return new MultiTextEdit(); } CompilationUnit usedAstRoot= this.astRoot; if (usedAstRoot == null) { ASTParser parser= ASTParser.newParser(AST.JLS4); parser.setSource(this.compilationUnit); parser.setFocalPosition(0); // reduced AST parser.setResolveBindings(false); usedAstRoot= (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1)); } ImportRewriteAnalyzer computer= new ImportRewriteAnalyzer( this.compilationUnit, usedAstRoot, this.importOrder, this.importOnDemandThreshold, this.staticImportOnDemandThreshold, this.restoreExistingImports, this.useContextToFilterImplicitImports); computer.setFilterImplicitImports(this.filterImplicitImports); if (this.addedImports != null) { for (int i= 0; i < this.addedImports.size(); i++) { String curr= (String) this.addedImports.get(i); computer.addImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0)); } } if (this.removedImports != null) { for (int i= 0; i < this.removedImports.size(); i++) { String curr= (String) this.removedImports.get(i); computer.removeImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0)); } } TextEdit result= computer.getResultingEdits(new SubProgressMonitor(monitor, 1)); this.createdImports= computer.getCreatedImports(); this.createdStaticImports= computer.getCreatedStaticImports(); return result; } finally { monitor.done(); } }
(Domain) AbortCompilation 15
              
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void initializeAnnotationProcessorManager() { try { Class c = Class.forName("org.eclipse.jdt.internal.compiler.apt.dispatch.BatchAnnotationProcessorManager"); //$NON-NLS-1$ AbstractAnnotationProcessorManager annotationManager = (AbstractAnnotationProcessorManager) c.newInstance(); annotationManager.configure(this, this.expandedCommandLine); annotationManager.setErr(this.err); annotationManager.setOut(this.out); this.batchCompiler.annotationProcessorManager = annotationManager; } catch (ClassNotFoundException e) { // ignore } catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); } catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); } catch(UnsupportedClassVersionError e) { // report a warning this.logger.logIncorrectVMVersionForAnnotationProcessing(); } }
// in model/org/eclipse/jdt/internal/core/CancelableProblemFactory.java
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { if (this.monitor != null && this.monitor.isCanceled()) throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); return super.createProblem(originatingFileName, problemId, problemArguments, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber); }
// in model/org/eclipse/jdt/internal/core/CancelableProblemFactory.java
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { if (this.monitor != null && this.monitor.isCanceled()) throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); return super.createProblem(originatingFileName, problemId, problemArguments, elaborationId, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) { if (this.notifier != null) this.notifier.checkCancelWithinCompiler(); if (this.initialTypeNames != null && this.initialTypeNames.includes(qualifiedTypeName)) { if (this.isIncrementalBuild) // catch the case that a type inside a source file has been renamed but other class files are looking for it throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedTypeName)); return null; // looking for a file which we know was provided at the beginning of the compilation } if (this.additionalUnits != null && this.sourceLocations.length > 0) { // if an additional source file is waiting to be compiled, answer it BUT not if this is a secondary type search // if we answer X.java & it no longer defines Y then the binary type looking for Y will think the class path is wrong // let the recompile loop fix up dependents when the secondary type Y has been deleted from X.java SourceFile unit = (SourceFile) this.additionalUnits.get(qualifiedTypeName); // doesn't have file extension if (unit != null) return new NameEnvironmentAnswer(unit, null /*no access restriction*/); } String qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class; String binaryFileName = qBinaryFileName; String qPackageName = ""; //$NON-NLS-1$ if (qualifiedTypeName.length() > typeName.length) { int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class" qPackageName = qBinaryFileName.substring(0, typeNameStart - 1); binaryFileName = qBinaryFileName.substring(typeNameStart); } // NOTE: the output folders are added at the beginning of the binaryLocations NameEnvironmentAnswer suggestedAnswer = null; for (int i = 0, l = this.binaryLocations.length; i < l; i++) { NameEnvironmentAnswer answer = this.binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName); if (answer != null) { if (!answer.ignoreIfBetter()) { if (answer.isBetter(suggestedAnswer)) return answer; } else if (answer.isBetter(suggestedAnswer)) // remember suggestion and keep looking suggestedAnswer = answer; } } if (suggestedAnswer != null) // no better answer was found return suggestedAnswer; return null; }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
public char[] getContents() { try { return Util.getResourceContentsAsCharArray(this.resource); } catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void writeClassFileContents(ClassFile classfile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // Before writing out the class file, compare it to the previous file // If structural changes occurred then add dependent source files byte[] bytes = classfile.getBytes(); if (file.exists()) { if (writeClassFileCheck(file, qualifiedFileName, bytes) || compilationUnit.updateClassFile) { // see 46093 if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(new ByteArrayInputStream(bytes), true, false, null); } else if (JavaBuilder.DEBUG) { System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$ } } else { if (isTopLevelType) addDependentsOf(new Path(qualifiedFileName), true); // new type if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow } } }
// in model/org/eclipse/jdt/internal/core/builder/BuildNotifier.java
public void checkCancelWithinCompiler() { if (this.monitor != null && this.monitor.isCanceled() && !this.cancelling) { // Once the compiler has been canceled, don't check again. setCancelling(true); // Only AbortCompilation can stop the compiler cleanly. // We check cancelation again following the call to compile. throw new AbortCompilation(true, null); } }
// in model/org/eclipse/jdt/internal/core/CancelableNameEnvironment.java
private void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) { if (NameLookup.VERBOSE) System.out.println(Thread.currentThread() + " CANCELLING LOOKUP "); //$NON-NLS-1$ throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); } }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemHandler.java
public void handle( int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity == ProblemSeverities.Ignore) return; // if no reference context, we need to abort from the current compilation process if (referenceContext == null) { if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal CategorizedProblem problem = this.createProblem(null, problemId, problemArguments, elaborationId, messageArguments, severity, 0, 0, 0, 0); throw new AbortCompilation(null, problem); } else { return; // ignore non reportable warning } } int[] lineEnds; int lineNumber = problemStartPosition >= 0 ? Util.getLineNumber(problemStartPosition, lineEnds = unitResult.getLineSeparatorPositions(), 0, lineEnds.length-1) : 0; int columnNumber = problemStartPosition >= 0 ? Util.searchColumnNumber(unitResult.getLineSeparatorPositions(), lineNumber, problemStartPosition) : 0; CategorizedProblem problem = this.createProblem( unitResult.getFileName(), problemId, problemArguments, elaborationId, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, columnNumber); if (problem == null) return; // problem couldn't be created, ignore switch (severity & ProblemSeverities.Error) { case ProblemSeverities.Error : record(problem, unitResult, referenceContext); if ((severity & ProblemSeverities.Fatal) != 0) { referenceContext.tagAsHavingErrors(); // should abort ? int abortLevel; if ((abortLevel = this.policy.stopOnFirstError() ? ProblemSeverities.AbortCompilation : severity & ProblemSeverities.Abort) != 0) { referenceContext.abort(abortLevel, problem); } } break; case ProblemSeverities.Warning : record(problem, unitResult, referenceContext); break; } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
protected void reportProgress(String taskDecription) { if (this.progress != null) { if (this.progress.isCanceled()) { // Only AbortCompilation can stop the compiler cleanly. // We check cancellation again following the call to compile. throw new AbortCompilation(true, null); } this.progress.setTaskName(taskDecription); } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
protected void reportWorked(int workIncrement, int currentUnitIndex) { if (this.progress != null) { if (this.progress.isCanceled()) { // Only AbortCompilation can stop the compiler cleanly. // We check cancellation again following the call to compile. throw new AbortCompilation(true, null); } this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
// in dom/org/eclipse/jdt/core/dom/NameEnvironmentWithProgress.java
private void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) { if (NameLookup.VERBOSE) { System.out.println(Thread.currentThread() + " CANCELLING LOOKUP "); //$NON-NLS-1$ } throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); } }
4
              
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
0
(Domain) AbortFormatting 11
              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void exitAlignment(Alignment alignment, boolean discardAlignment){ Alignment current = this.currentAlignment; while (current != null){ if (current == alignment) break; current = current.enclosing; } if (current == null) { throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ } this.indentationLevel = alignment.location.outputIndentationLevel; this.numberOfIndentations = alignment.location.numberOfIndentations; this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart; if (discardAlignment){ this.currentAlignment = alignment.enclosing; if (this.currentAlignment == null) { this.formatter.lastBinaryExpressionAlignmentBreakIndentation = 0; } } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void exitMemberAlignment(Alignment alignment){ Alignment current = this.memberAlignment; while (current != null){ if (current == alignment) break; current = current.enclosing; } if (current == null) { throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ } this.indentationLevel = current.location.outputIndentationLevel; this.numberOfIndentations = current.location.numberOfIndentations; this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart; this.memberAlignment = current.enclosing; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printEndOfCompilationUnit() { try { // if we have a space between two tokens we ensure it will be dumped in the formatted string int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasLineComment = false; boolean hasWhitespace = false; int count = 0; while (true) { this.currentToken = this.scanner.getNextToken(); switch(this.currentToken) { case TerminalTokens.TokenNameWHITESPACE : char[] whiteSpaces = this.scanner.getCurrentTokenSource(); count = 0; for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } count++; break; case '\n' : count++; } } if (count == 0) { hasWhitespace = true; addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else if (hasLineComment) { preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition()); addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else if (hasComment) { if (count == 1) { this.printNewLine(this.scanner.getCurrentTokenStartPosition()); } else { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else { addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } else if (count == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespace) { space(); } hasWhitespace = false; printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = true; count = 0; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } else if (count == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespace) { space(); } hasWhitespace = false; printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; count = 0; break; case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.startPosition); } else if (count == 1) { printNewLine(this.scanner.startPosition); } } else if (hasWhitespace) { space(); } hasWhitespace = false; if (includesJavadocComments()) { printJavadocComment(this.scanner.startPosition, this.scanner.currentPosition); } else { printBlockComment(true); } printNewLine(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; count = 0; break; case TerminalTokens.TokenNameSEMICOLON : print(this.scanner.currentPosition - this.scanner.startPosition, this.formatter.preferences.insert_space_before_semicolon); break; case TerminalTokens.TokenNameEOF : if (count >= 1 || this.formatter.preferences.insert_new_line_at_end_of_file_if_missing) { this.printNewLine(this.scannerEndPosition); } return; default : // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
void printComment(int kind, int trailing, int emptyLinesRules) { final boolean rejectLineComment = kind == CodeFormatter.K_MULTI_LINE_COMMENT || kind == CodeFormatter.K_JAVA_DOC; final boolean rejectBlockComment = kind == CodeFormatter.K_SINGLE_LINE_COMMENT || kind == CodeFormatter.K_JAVA_DOC; final boolean rejectJavadocComment = kind == CodeFormatter.K_SINGLE_LINE_COMMENT || kind == CodeFormatter.K_MULTI_LINE_COMMENT; try { // if we have a space between two tokens we ensure it will be dumped in the formatted string int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasLineComment = false; boolean hasWhitespaces = false; int lines = 0; while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { int foundTaskCount = this.scanner.foundTaskCount; int tokenStartPosition = this.scanner.getCurrentTokenStartPosition(); switch(this.currentToken) { case TerminalTokens.TokenNameWHITESPACE : char[] whiteSpaces = this.scanner.getCurrentTokenSource(); int whitespacesEndPosition = this.scanner.getCurrentTokenEndPosition(); lines = 0; for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } lines++; break; case '\n' : lines++; } } // If following token is a line comment on the same line or the line just after, // then it might be not really formatted as a trailing comment boolean realTrailing = trailing > NO_TRAILING_COMMENT; if (realTrailing && this.scanner.currentCharacter == '/' && (lines == 0 || (lines == 1 && !hasLineComment && trailing == IMPORT_TRAILING_COMMENT))) { // sometimes changing the trailing may not be the best idea // for complex trailing comment, it's basically a good idea boolean canChangeTrailing = (trailing & COMPLEX_TRAILING_COMMENT) != 0; // for basic trailing comment preceded by a line comment, then it depends on the comments relative position // when following comment column (after having been rounded) is below the preceding one, // then it becomes not a good idea to change the trailing flag if (trailing == BASIC_TRAILING_COMMENT && hasLineComment) { int currentCommentIndentation = getCurrentIndentation(whiteSpaces, 0); int relativeIndentation = currentCommentIndentation - this.lastLineComment.currentIndentation; if (this.tabLength == 0) { canChangeTrailing = relativeIndentation == 0; } else { canChangeTrailing = relativeIndentation > -this.tabLength; } } // if the trailing can be change, then look at the following tokens if (canChangeTrailing) { int currentPosition = this.scanner.currentPosition; if (this.scanner.getNextToken() == TerminalTokens.TokenNameCOMMENT_LINE) { realTrailing = !hasLineComment; switch (this.scanner.getNextToken()) { case TerminalTokens.TokenNameCOMMENT_LINE: // at least two contiguous line comments // the formatter should not consider comments as trailing ones realTrailing = false; break; case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.getNextToken() == TerminalTokens.TokenNameCOMMENT_LINE) { // at least two contiguous line comments // the formatter should not consider comments as trailing ones realTrailing = false; } break; } } this.scanner.resetTo(currentPosition, this.scanner.eofPosition - 1); } } // Look whether comments line may be contiguous or not // Note that when preceding token is a comment line, then only one line // is enough to have an empty line as the line end is included in the comment line... // If comments are contiguous, store the white spaces to be able to compute the current comment indentation if (lines > 1 || (lines == 1 && hasLineComment)) { this.lastLineComment.contiguous = false; } this.lastLineComment.leadingSpaces = whiteSpaces; this.lastLineComment.lines = lines; // Strategy to consume spaces and eventually leave at this stage // depends on the fact that a trailing comment is expected or not if (realTrailing) { // if a line comment is consumed, no other comment can be on the same line after if (hasLineComment) { if (lines >= 1) { currentTokenStartPosition = tokenStartPosition; preserveEmptyLines(lines, currentTokenStartPosition); addDeleteEdit(currentTokenStartPosition, whitespacesEndPosition); this.scanner.resetTo(this.scanner.currentPosition, this.scannerEndPosition - 1); return; } this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } // if one or several new lines are consumed, following comments cannot be considered as trailing ones if (lines >= 1) { if (hasComment) { this.printNewLine(tokenStartPosition); } this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } // delete consumed white spaces hasWhitespaces = true; currentTokenStartPosition = this.scanner.currentPosition; addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } else { if (lines == 0) { hasWhitespaces = true; if (hasLineComment && emptyLinesRules != PRESERVE_EMPTY_LINES_KEEP_LAST_NEW_LINES_INDENTATION) { addReplaceEdit(tokenStartPosition, whitespacesEndPosition, getPreserveEmptyLines(0, emptyLinesRules)); } else { addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } } else if (hasLineComment) { useAlignmentBreakIndentation(emptyLinesRules); currentTokenStartPosition = tokenStartPosition; preserveEmptyLines(lines, currentTokenStartPosition); addDeleteEdit(currentTokenStartPosition, whitespacesEndPosition); } else if (hasComment) { useAlignmentBreakIndentation(emptyLinesRules); if (lines == 1) { this.printNewLine(tokenStartPosition); } else { preserveEmptyLines(lines - 1, tokenStartPosition); } addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } else if (lines != 0 && (!this.formatter.preferences.join_wrapped_lines || this.formatter.preferences.number_of_empty_lines_to_preserve != 0 || this.blank_lines_between_import_groups > 0)) { addReplaceEdit(tokenStartPosition, whitespacesEndPosition, getPreserveEmptyLines(lines-1, emptyLinesRules)); } else { useAlignmentBreakIndentation(emptyLinesRules); addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.fragmentEquals(this.disablingTag, this.scanner.source, tokenStartPosition, true)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } if (rejectLineComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = true; lines = 0; if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.fragmentEquals(this.enablingTag, this.scanner.source, tokenStartPosition, true); } } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.fragmentEquals(this.disablingTag, this.scanner.source, tokenStartPosition, true)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } if (trailing > NO_TRAILING_COMMENT && lines >= 1) { // a block comment on next line means that there's no trailing comment this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); return; } this.lastLineComment.contiguous = false; if (rejectBlockComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; lines = 0; if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.fragmentEquals(this.enablingTag, this.scanner.source, tokenStartPosition, true); } } break; case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (this.useTags && this.editsEnabled && foundTaskCount > 0) { setEditsEnabled(foundTaskCount); if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } if (trailing > NO_TRAILING_COMMENT) { // a javadoc comment should not be considered as a trailing comment this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); return; } this.lastLineComment.contiguous = false; if (rejectJavadocComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; if (includesJavadocComments()) { printJavadocComment(this.scanner.startPosition, this.scanner.currentPosition); } else { printBlockComment(true); } if (this.useTags && !this.editsEnabled && foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } printNewLine(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; lines = 0; break; default : this.lastLineComment.contiguous = false; // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printModifiers(Annotation[] annotations, ASTVisitor visitor, int annotationSourceKind) { try { int annotationsLength = annotations != null ? annotations.length : 0; int annotationsIndex = 0; boolean isFirstModifier = true; int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasModifiers = false; while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { int foundTaskCount = this.scanner.foundTaskCount; int tokenStartPosition = this.scanner.getCurrentTokenStartPosition(); int tokenEndPosition = this.scanner.getCurrentTokenEndPosition(); switch(this.currentToken) { case TerminalTokens.TokenNamepublic : case TerminalTokens.TokenNameprotected : case TerminalTokens.TokenNameprivate : case TerminalTokens.TokenNamestatic : case TerminalTokens.TokenNameabstract : case TerminalTokens.TokenNamefinal : case TerminalTokens.TokenNamenative : case TerminalTokens.TokenNamesynchronized : case TerminalTokens.TokenNametransient : case TerminalTokens.TokenNamevolatile : case TerminalTokens.TokenNamestrictfp : hasModifiers = true; print(this.scanner.currentPosition - this.scanner.startPosition, !isFirstModifier); isFirstModifier = false; currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameAT : hasModifiers = true; if (!isFirstModifier) { space(); } this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); if (annotationsIndex < annotationsLength) { boolean insertSpaceBeforeBrace = this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer; this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer = false; try { annotations[annotationsIndex++].traverse(visitor, (BlockScope) null); } finally { this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer = insertSpaceBeforeBrace; } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=122247 boolean shouldAddNewLine = false; switch (annotationSourceKind) { case ICodeFormatterConstants.ANNOTATION_ON_TYPE : if (this.formatter.preferences.insert_new_line_after_annotation_on_type) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_FIELD : if (this.formatter.preferences.insert_new_line_after_annotation_on_field) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_METHOD : if (this.formatter.preferences.insert_new_line_after_annotation_on_method) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_PACKAGE : if (this.formatter.preferences.insert_new_line_after_annotation_on_package) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_PARAMETER : if (this.formatter.preferences.insert_new_line_after_annotation_on_parameter) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_LOCAL_VARIABLE : if (this.formatter.preferences.insert_new_line_after_annotation_on_local_variable) { shouldAddNewLine = true; } break; default: // do nothing when no annotation formatting option specified } if (shouldAddNewLine) { this.printNewLine(); } } else { return; } isFirstModifier = false; currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.equals(this.disablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition+1)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } printBlockComment(this.currentToken == TerminalTokens.TokenNameCOMMENT_JAVADOC); if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.equals(this.enablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition+1); } } currentTokenStartPosition = this.scanner.currentPosition; hasComment = true; break; case TerminalTokens.TokenNameCOMMENT_LINE : tokenEndPosition = -this.scanner.commentStops[this.scanner.commentPtr]; if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.equals(this.disablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } printLineComment(); if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.equals(this.enablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition); } } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); int count = 0; char[] whiteSpaces = this.scanner.getCurrentTokenSource(); for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } count++; break; case '\n' : count++; } } if (count >= 1 && hasComment) { printNewLine(); } currentTokenStartPosition = this.scanner.currentPosition; hasComment = false; break; default: if (hasModifiers) { space(); } // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny, int emptyLineRules) { // Set brace flag, it's useful for the scribe while preserving line breaks printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT, emptyLineRules); try { this.currentToken = this.scanner.getNextToken(); if (expectedTokenType != this.currentToken) { throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ } print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny); } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){ printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); try { this.currentToken = this.scanner.getNextToken(); if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) { StringBuffer expectations = new StringBuffer(5); for (int i = 0; i < expectedTokenTypes.length; i++){ if (i > 0) { expectations.append(','); } expectations.append(expectedTokenTypes[i]); } throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ } print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny); } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printArrayQualifiedReference(int numberOfTokens, int sourceEnd) { int currentTokenStartPosition = this.scanner.currentPosition; int numberOfIdentifiers = 0; try { do { printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); switch(this.currentToken = this.scanner.getNextToken()) { case TerminalTokens.TokenNameEOF : return; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameIdentifier : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; if (++ numberOfIdentifiers == numberOfTokens) { this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } break; case TerminalTokens.TokenNameDOT : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameRPAREN: currentTokenStartPosition = this.scanner.startPosition; // $FALL-THROUGH$ - fall through default case... default: this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } while (this.scanner.currentPosition <= sourceEnd); } catch(InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printQualifiedReference(int sourceEnd, boolean expectParenthesis) { int currentTokenStartPosition = this.scanner.currentPosition; try { do { printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); switch(this.currentToken = this.scanner.getNextToken()) { case TerminalTokens.TokenNameEOF : return; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameIdentifier : case TerminalTokens.TokenNameDOT : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameRPAREN: if (expectParenthesis) { currentTokenStartPosition = this.scanner.startPosition; } // $FALL-THROUGH$ - fall through default case... default: this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } while (this.scanner.currentPosition <= sourceEnd); } catch(InvalidInputException e) { throw new AbortFormatting(e); } }
7
              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
0
(Domain) DOMException 10
              
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { DOMNode first = getFirstFieldDeclaration(); DOMNode last = getLastFieldDeclaration(); DOMNode node= first; String source= first.getContents(); while (node != last) { node= node.fNextNode; source+=node.getContents(); } DOMBuilder builder = new DOMBuilder(); IDOMField[] details= builder.createFields(source.toCharArray()); if (details.length == 0) { throw new DOMException(Messages.dom_cannotDetail); } else { node= this; for (int i= 0; i < details.length; i++) { node.shareContents((DOMNode)details[i]); node= node.fNextNode; } } } else { super.becomeDetailed(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { DOMNode detailed= getDetailedNode(); if (detailed == null) { throw new DOMException(Messages.dom_cannotDetail); } if (detailed != this) { shareContents(detailed); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
0 6
              
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { DOMNode first = getFirstFieldDeclaration(); DOMNode last = getLastFieldDeclaration(); DOMNode node= first; String source= first.getContents(); while (node != last) { node= node.fNextNode; source+=node.getContents(); } DOMBuilder builder = new DOMBuilder(); IDOMField[] details= builder.createFields(source.toCharArray()); if (details.length == 0) { throw new DOMException(Messages.dom_cannotDetail); } else { node= this; for (int i= 0; i < details.length; i++) { node.shareContents((DOMNode)details[i]); node= node.fNextNode; } } } else { super.becomeDetailed(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { if (isVariableDeclarator()) { expand(); } super.insertSibling(sibling); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException { basicAddChild(child); // if the node is a constructor, it must also be fragmented to update the constructor's name if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } else { fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { DOMNode detailed= getDetailedNode(); if (detailed == null) { throw new DOMException(Messages.dom_cannotDetail); } if (detailed != this) { shareContents(detailed); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
(Domain) ShouldNotImplement 10
              
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public boolean booleanValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "boolean" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public byte byteValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "byte" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public char charValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "char" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public double doubleValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "double" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public float floatValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "float" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public int intValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "int" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public long longValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "long" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public short shortValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "short" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public String stringValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "String" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Expression.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { if (this.constant != Constant.NotAConstant) { // generate a constant expression int pc = codeStream.position; codeStream.generateConstant(this.constant, this.implicitConversion); codeStream.recordPositionsFrom(pc, this.sourceStart); } else { // actual non-constant code generation throw new ShouldNotImplement(Messages.ast_missingCode); } }
0 0
(Lib) UnsupportedOperationException 10
              
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionContext.java
public IJavaElement getEnclosingElement() { if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$ if (this.extendedContext == null) return null; return this.extendedContext.getEnclosingElement(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionContext.java
public IJavaElement[] getVisibleElements(String typeSignature) { if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$ if (this.extendedContext == null) return new IJavaElement[0]; return this.extendedContext.getVisibleElements(typeSignature); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public void remove() { throw new UnsupportedOperationException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public void remove() { throw new UnsupportedOperationException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void unsupportedIn2() { if (this.ast.apiLevel == AST.JLS2_INTERNAL) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void unsupportedIn2_3() { if (this.ast.apiLevel <= AST.JLS3) { throw new UnsupportedOperationException("Operation only supported in JLS4 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void supportedOnlyIn2() { if (this.ast.apiLevel != AST.JLS2_INTERNAL) { throw new UnsupportedOperationException("Operation only supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static ASTNode copySubtree(AST target, ASTNode node) { if (node == null) { return null; } if (target == null) { throw new IllegalArgumentException(); } if (target.apiLevel() != node.getAST().apiLevel()) { throw new UnsupportedOperationException(); } ASTNode newNode = node.clone(target); return newNode; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void supportedOnlyIn2() { if (this.apiLevel != AST.JLS2) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/AST.java
void unsupportedIn2() { if (this.apiLevel == AST.JLS2) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
0 0
(Lib) NumberFormatException 9
              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private int extractInt(char[] array, int start, int end) { int value = 0; for (int i = start; i < end; i++) { final char currentChar = array[i]; int digit = 0; switch(currentChar) { case '0' : digit = 0; break; case '1' : digit = 1; break; case '2' : digit = 2; break; case '3' : digit = 3; break; case '4' : digit = 4; break; case '5' : digit = 5; break; case '6' : digit = 6; break; case '7' : digit = 7; break; case '8' : digit = 8; break; case '9' : digit = 9; break; default : throw new NumberFormatException(); } value *= 10; if (digit < 0) throw new NumberFormatException(); value += digit; } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private int extractInt(char[] array, int start, int end) { int value = 0; for (int i = start; i < end; i++) { final char currentChar = array[i]; int digit = 0; switch(currentChar) { case '0' : digit = 0; break; case '1' : digit = 1; break; case '2' : digit = 2; break; case '3' : digit = 3; break; case '4' : digit = 4; break; case '5' : digit = 5; break; case '6' : digit = 6; break; case '7' : digit = 7; break; case '8' : digit = 8; break; case '9' : digit = 9; break; default : throw new NumberFormatException(); } value *= 10; if (digit < 0) throw new NumberFormatException(); value += digit; } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/util/FloatUtil.java
private static long convertHexFloatingPointLiteralToBits(char[] source) { int length = source.length; long mantissa = 0; // Step 1: process the '0x' lead-in int next = 0; char nextChar = source[next]; nextChar = source[next]; if (nextChar == '0') { next++; } else { throw new NumberFormatException(); } nextChar = source[next]; if (nextChar == 'X' || nextChar == 'x') { next++; } else { throw new NumberFormatException(); } // Step 2: process leading '0's either before or after the '.' int binaryPointPosition = -1; loop: while (true) { nextChar = source[next]; switch (nextChar) { case '0': next++; continue loop; case '.': binaryPointPosition = next; next++; continue loop; default: break loop; } } // Step 3: process the mantissa // leading zeros have been trimmed int mantissaBits = 0; int leadingDigitPosition = -1; loop: while (true) { nextChar = source[next]; int hexdigit; switch (nextChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': hexdigit = nextChar - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': hexdigit = (nextChar - 'a') + 10; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': hexdigit = (nextChar - 'A') + 10; break; case '.': binaryPointPosition = next; next++; continue loop; default: if (binaryPointPosition < 0) { // record virtual '.' as being to right of all digits binaryPointPosition = next; } break loop; } if (mantissaBits == 0) { // this is the first non-zero hex digit // ignore leading binary 0's in hex digit leadingDigitPosition = next; mantissa = hexdigit; mantissaBits = 4; } else if (mantissaBits < 60) { // middle hex digits mantissa <<= 4; mantissa |= hexdigit; mantissaBits += 4; } else { // more mantissa bits than we can handle // drop this hex digit on the ground } next++; continue loop; } // Step 4: process the 'P' nextChar = source[next]; if (nextChar == 'P' || nextChar == 'p') { next++; } else { throw new NumberFormatException(); } // Step 5: process the exponent int exponent = 0; int exponentSign = +1; loop: while (next < length) { nextChar = source[next]; switch (nextChar) { case '+': exponentSign = +1; next++; continue loop; case '-': exponentSign = -1; next++; continue loop; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': int digit = nextChar - '0'; exponent = (exponent * 10) + digit; next++; continue loop; default: break loop; } } // Step 6: process the optional 'f' or 'd' boolean doublePrecision = true; if (next < length) { nextChar = source[next]; switch (nextChar) { case 'f': case 'F': doublePrecision = false; next++; break; case 'd': case 'D': doublePrecision = true; next++; break; default: throw new NumberFormatException(); } } // at this point, all the parsing is done // Step 7: handle mantissa of zero if (mantissa == 0) { return 0L; } // Step 8: normalize non-zero mantissa // mantissa is in right-hand mantissaBits // ensure that top bit (as opposed to hex digit) is 1 int scaleFactorCompensation = 0; long top = (mantissa >>> (mantissaBits - 4)); if ((top & 0x8) == 0) { mantissaBits--; scaleFactorCompensation++; if ((top & 0x4) == 0) { mantissaBits--; scaleFactorCompensation++; if ((top & 0x2) == 0) { mantissaBits--; scaleFactorCompensation++; } } } // Step 9: convert double literals to IEEE double long result = 0L; if (doublePrecision) { long fraction; if (mantissaBits > DOUBLE_PRECISION) { // more bits than we can keep int extraBits = mantissaBits - DOUBLE_PRECISION; // round to DOUBLE_PRECISION bits fraction = mantissa >>> (extraBits - 1); long lowBit = fraction & 0x1; fraction += lowBit; fraction = fraction >>> 1; if ((fraction & (1L << DOUBLE_PRECISION)) != 0) { fraction = fraction >>> 1; scaleFactorCompensation -= 1; } } else { // less bits than the faction can hold - pad on right with 0s fraction = mantissa << (DOUBLE_PRECISION - mantissaBits); } int scaleFactor = 0; // how many bits to move '.' to before leading hex digit if (mantissaBits > 0) { if (leadingDigitPosition < binaryPointPosition) { // e.g., 0x80.0p0 has scaleFactor == +8 scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition); // e.g., 0x10.0p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } else { // e.g., 0x0.08p0 has scaleFactor == -4 scaleFactor = -4 * (leadingDigitPosition - binaryPointPosition - 1); // e.g., 0x0.01p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } } int e = (exponentSign * exponent) + scaleFactor; if (e - 1 > MAX_DOUBLE_EXPONENT) { // overflow to +infinity result = Double.doubleToLongBits(Double.POSITIVE_INFINITY); } else if (e - 1 >= MIN_NORMALIZED_DOUBLE_EXPONENT) { // can be represented as a normalized double // the left most bit must be discarded (it's always a 1) long biasedExponent = e - 1 + DOUBLE_EXPONENT_BIAS; result = fraction & ~(1L << DOUBLE_FRACTION_WIDTH); result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT); } else if (e - 1 > MIN_UNNORMALIZED_DOUBLE_EXPONENT) { // can be represented as an unnormalized double long biasedExponent = 0; result = fraction >>> (MIN_NORMALIZED_DOUBLE_EXPONENT - e + 1); result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT); } else { // underflow - return Double.NaN result = Double.doubleToLongBits(Double.NaN); } return result; } // Step 10: convert float literals to IEEE single long fraction; if (mantissaBits > SINGLE_PRECISION) { // more bits than we can keep int extraBits = mantissaBits - SINGLE_PRECISION; // round to DOUBLE_PRECISION bits fraction = mantissa >>> (extraBits - 1); long lowBit = fraction & 0x1; fraction += lowBit; fraction = fraction >>> 1; if ((fraction & (1L << SINGLE_PRECISION)) != 0) { fraction = fraction >>> 1; scaleFactorCompensation -= 1; } } else { // less bits than the faction can hold - pad on right with 0s fraction = mantissa << (SINGLE_PRECISION - mantissaBits); } int scaleFactor = 0; // how many bits to move '.' to before leading hex digit if (mantissaBits > 0) { if (leadingDigitPosition < binaryPointPosition) { // e.g., 0x80.0p0 has scaleFactor == +8 scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition); // e.g., 0x10.0p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } else { // e.g., 0x0.08p0 has scaleFactor == -4 scaleFactor = -4 * (leadingDigitPosition - binaryPointPosition - 1); // e.g., 0x0.01p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } } int e = (exponentSign * exponent) + scaleFactor; if (e - 1 > MAX_SINGLE_EXPONENT) { // overflow to +infinity result = Float.floatToIntBits(Float.POSITIVE_INFINITY); } else if (e - 1 >= MIN_NORMALIZED_SINGLE_EXPONENT) { // can be represented as a normalized single // the left most bit must be discarded (it's always a 1) long biasedExponent = e - 1 + SINGLE_EXPONENT_BIAS; result = fraction & ~(1L << SINGLE_FRACTION_WIDTH); result |= (biasedExponent << SINGLE_EXPONENT_SHIFT); } else if (e - 1 > MIN_UNNORMALIZED_SINGLE_EXPONENT) { // can be represented as an unnormalized single long biasedExponent = 0; result = fraction >>> (MIN_NORMALIZED_SINGLE_EXPONENT - e + 1); result |= (biasedExponent << SINGLE_EXPONENT_SHIFT); } else { // underflow - return Float.NaN result = Float.floatToIntBits(Float.NaN); } return result; }
// in compiler/org/eclipse/jdt/core/compiler/CharOperation.java
public static final int parseInt(char[] array, int start, int length) throws NumberFormatException { if (length == 1) { int result = array[start] - '0'; if (result < 0 || result > 9) { throw new NumberFormatException("invalid digit"); //$NON-NLS-1$ } return result; } else { return Integer.parseInt(new String(array, start, length)); } }
0 1
              
// in compiler/org/eclipse/jdt/core/compiler/CharOperation.java
public static final int parseInt(char[] array, int start, int length) throws NumberFormatException { if (length == 1) { int result = array[start] - '0'; if (result < 0 || result > 9) { throw new NumberFormatException("invalid digit"); //$NON-NLS-1$ } return result; } else { return Integer.parseInt(new String(array, start, length)); } }
(Lib) RuntimeException 7
              
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
List internalGetChildListProperty(ChildListPropertyDescriptor property) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void addProperty(StructuralPropertyDescriptor property, List propertyList) { Class nodeClass = (Class) propertyList.get(0); if (property.getNodeClass() != nodeClass) { // easily made cut-and-paste mistake throw new RuntimeException("Structural property descriptor has wrong node class!"); //$NON-NLS-1$ } propertyList.add(property); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
IBinding createBinding(String key) { if (this.bindingTables == null) throw new RuntimeException("Cannot be called outside ASTParser#createASTs(...)"); //$NON-NLS-1$ BindingKeyResolver keyResolver = new BindingKeyResolver(key, this, this.lookupEnvironment); Binding compilerBinding = keyResolver.getCompilerBinding(); if (compilerBinding == null) return null; DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, null/*no owner*/, this.bindingTables, false, this.fromJavaProject); return resolver.getBinding(compilerBinding); }
0 0
(Domain) AbortCompilationUnit 6
              
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
public char[] getContents() { if (this.contents != null) return this.contents; // answer the cached source // otherwise retrieve it try { return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding); } catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public char[] getContents() { IBuffer buffer = getBufferManager().getBuffer(this); if (buffer == null) { // no need to force opening of CU to get the content // also this cannot be a working copy, as its buffer is never closed while the working copy is alive IFile file = (IFile) getResource(); // Get encoding from file String encoding; try { encoding = file.getCharset(); } catch(CoreException ce) { // do not use any encoding encoding = null; } try { return Util.getResourceContentsAsCharArray(file, encoding); } catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; } } char[] contents = buffer.getCharacters(); if (contents == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814 if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = new IOException(Messages.buffer_closed); IFile file = (IFile) getResource(); // Get encoding from file String encoding; try { encoding = file.getCharset(); } catch(CoreException ce) { // do not use any encoding encoding = null; } throw new AbortCompilationUnit(null, ioException, encoding); } return CharOperation.NO_CHAR; } return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
2
              
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
0
(Lib) BuildException 6
              
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
public boolean execute() throws BuildException { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.usingJDTCompiler"), Project.MSG_VERBOSE); //$NON-NLS-1$ Commandline cmd = setupJavacCommand(); try { Class c = Class.forName(compilerClass); Constructor batchCompilerConstructor = c.getConstructor(new Class[] { PrintWriter.class, PrintWriter.class, Boolean.TYPE, Map.class}); Object batchCompilerInstance = batchCompilerConstructor.newInstance(new Object[] {new PrintWriter(System.out), new PrintWriter(System.err), Boolean.TRUE, this.customDefaultOptions}); Method compile = c.getMethod("compile", new Class[] {String[].class}); //$NON-NLS-1$ Object result = compile.invoke(batchCompilerInstance, new Object[] { cmd.getArguments()}); final boolean resultValue = ((Boolean) result).booleanValue(); if (!resultValue && this.logFileName != null) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.error.compilationFailed", this.logFileName)); //$NON-NLS-1$ } return resultValue; } catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ } catch (Exception ex) { throw new BuildException(ex); } }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
public void execute() throws BuildException { if (this.file == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.cannot.be.null")); //$NON-NLS-1$ } if (this.property == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.property.argument.cannot.be.null")); //$NON-NLS-1$ } try { boolean hasDebugAttributes = false; if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(this.file)) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } else { ZipFile jarFile = null; try { jarFile = new ZipFile(this.file); } catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ } for (Enumeration entries = jarFile.entries(); !hasDebugAttributes && entries.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entry.getName())) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, entry.getName(), IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } } } if (hasDebugAttributes) { getProject().setUserProperty(this.property, "has debug"); //$NON-NLS-1$ } } catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ } }
4
              
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
3
              
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
public boolean execute() throws BuildException { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.usingJDTCompiler"), Project.MSG_VERBOSE); //$NON-NLS-1$ Commandline cmd = setupJavacCommand(); try { Class c = Class.forName(compilerClass); Constructor batchCompilerConstructor = c.getConstructor(new Class[] { PrintWriter.class, PrintWriter.class, Boolean.TYPE, Map.class}); Object batchCompilerInstance = batchCompilerConstructor.newInstance(new Object[] {new PrintWriter(System.out), new PrintWriter(System.err), Boolean.TRUE, this.customDefaultOptions}); Method compile = c.getMethod("compile", new Class[] {String[].class}); //$NON-NLS-1$ Object result = compile.invoke(batchCompilerInstance, new Object[] { cmd.getArguments()}); final boolean resultValue = ((Boolean) result).booleanValue(); if (!resultValue && this.logFileName != null) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.error.compilationFailed", this.logFileName)); //$NON-NLS-1$ } return resultValue; } catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ } catch (Exception ex) { throw new BuildException(ex); } }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
protected Commandline setupJavacCommand() throws BuildException { Commandline cmd = new Commandline(); this.customDefaultOptions = new CompilerOptions().getMap(); Class javacClass = Javac.class; /* * Read in the compiler arguments first since we might need to modify * the classpath if any access rules were specified */ String [] compilerArgs = processCompilerArguments(javacClass); /* * This option is used to never exit at the end of the ant task. */ cmd.createArgument().setValue("-noExit"); //$NON-NLS-1$ if (this.bootclasspath != null) { cmd.createArgument().setValue("-bootclasspath"); //$NON-NLS-1$ if (this.bootclasspath.size() != 0) { /* * Set the bootclasspath for the Eclipse compiler. */ cmd.createArgument().setPath(this.bootclasspath); } else { cmd.createArgument().setValue(Util.EMPTY_STRING); } } /* * Eclipse compiler doesn't support -extdirs. * It is emulated using the classpath. We add extdirs entries after the * bootclasspath. */ if (this.extdirs != null) { cmd.createArgument().setValue("-extdirs"); //$NON-NLS-1$ cmd.createArgument().setPath(this.extdirs); } Path classpath = new Path(this.project); /* * The java runtime is already handled, so we simply want to retrieve the * ant runtime and the compile classpath. */ classpath.append(getCompileClasspath()); /* * Set the classpath for the Eclipse compiler. */ cmd.createArgument().setValue("-classpath"); //$NON-NLS-1$ createClasspathArgument(cmd, classpath); // For -sourcepath, use the "sourcepath" value if present. // Otherwise default to the "srcdir" value. Path sourcepath = null; // retrieve the method getSourcepath() using reflect // This is done to improve the compatibility to ant 1.5 Method getSourcepathMethod = null; try { getSourcepathMethod = javacClass.getMethod("getSourcepath", null); //$NON-NLS-1$ } catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) } Path compileSourcePath = null; if (getSourcepathMethod != null) { try { compileSourcePath = (Path) getSourcepathMethod.invoke(this.attributes, null); } catch (IllegalAccessException e) { // should never happen } catch (InvocationTargetException e) { // should never happen } } if (compileSourcePath != null) { sourcepath = compileSourcePath; } else { sourcepath = this.src; } cmd.createArgument().setValue("-sourcepath"); //$NON-NLS-1$ createClasspathArgument(cmd, sourcepath); final String javaVersion = JavaEnvUtils.getJavaVersion(); String memoryParameterPrefix = javaVersion.equals(JavaEnvUtils.JAVA_1_1) ? "-J-" : "-J-X";//$NON-NLS-1$//$NON-NLS-2$ if (this.memoryInitialSize != null) { if (!this.attributes.isForkedJavac()) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryInitialSize"), Project.MSG_WARN); //$NON-NLS-1$ } else { cmd.createArgument().setValue(memoryParameterPrefix + "ms" + this.memoryInitialSize); //$NON-NLS-1$ } } if (this.memoryMaximumSize != null) { if (!this.attributes.isForkedJavac()) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryMaximumSize"), Project.MSG_WARN); //$NON-NLS-1$ } else { cmd.createArgument().setValue(memoryParameterPrefix + "mx" + this.memoryMaximumSize); //$NON-NLS-1$ } } if (this.debug) { // retrieve the method getSourcepath() using reflect // This is done to improve the compatibility to ant 1.5 Method getDebugLevelMethod = null; try { getDebugLevelMethod = javacClass.getMethod("getDebugLevel", null); //$NON-NLS-1$ } catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x } String debugLevel = null; if (getDebugLevelMethod != null) { try { debugLevel = (String) getDebugLevelMethod.invoke(this.attributes, null); } catch (IllegalAccessException e) { // should never happen } catch (InvocationTargetException e) { // should never happen } } if (debugLevel != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.DO_NOT_GENERATE); if (debugLevel.length() != 0) { if (debugLevel.indexOf("vars") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } if (debugLevel.indexOf("lines") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } if (debugLevel.indexOf("source") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.GENERATE); } } } else { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.GENERATE); } } else { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.DO_NOT_GENERATE); } /* * Handle the nowarn option. If none, then we generate all warnings. */ if (this.attributes.getNowarn()) { // disable all warnings Object[] entries = this.customDefaultOptions.entrySet().toArray(); for (int i = 0, max = entries.length; i < max; i++) { Map.Entry entry = (Map.Entry) entries[i]; if (!(entry.getKey() instanceof String)) continue; if (!(entry.getValue() instanceof String)) continue; if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) { this.customDefaultOptions.put(entry.getKey(), CompilerOptions.IGNORE); } } this.customDefaultOptions.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING); if (this.deprecation) { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED); } } else if (this.deprecation) { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED); } else { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED); } /* * destDir option. */ if (this.destDir != null) { cmd.createArgument().setValue("-d"); //$NON-NLS-1$ cmd.createArgument().setFile(this.destDir.getAbsoluteFile()); } /* * verbose option */ if (this.verbose) { cmd.createArgument().setValue("-verbose"); //$NON-NLS-1$ } /* * failnoerror option */ if (!this.attributes.getFailonerror()) { cmd.createArgument().setValue("-proceedOnError"); //$NON-NLS-1$ } /* * target option. */ if (this.target != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_TargetPlatform, this.target); } /* * source option */ String source = this.attributes.getSource(); if (source != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_Source, source); } if (compilerArgs != null) { /* * Add extra argument on the command line */ final int length = compilerArgs.length; if (length != 0) { for (int i = 0, max = length; i < max; i++) { String arg = compilerArgs[i]; if (this.logFileName == null && "-log".equals(arg) && ((i + 1) < max)) { //$NON-NLS-1$ this.logFileName = compilerArgs[i + 1]; } cmd.createArgument().setValue(arg); } } } /* * encoding option. javac task encoding property must be the last encoding on the command * line as compiler arg might also specify an encoding. */ if (this.encoding != null) { cmd.createArgument().setValue("-encoding"); //$NON-NLS-1$ cmd.createArgument().setValue(this.encoding); } /* * Eclipse compiler doesn't have a -sourcepath option. This is * handled through the javac task that collects all source files in * srcdir option. */ logAndAddFilesToCompile(cmd); return cmd; }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
public void execute() throws BuildException { if (this.file == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.cannot.be.null")); //$NON-NLS-1$ } if (this.property == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.property.argument.cannot.be.null")); //$NON-NLS-1$ } try { boolean hasDebugAttributes = false; if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(this.file)) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } else { ZipFile jarFile = null; try { jarFile = new ZipFile(this.file); } catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ } for (Enumeration entries = jarFile.entries(); !hasDebugAttributes && entries.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entry.getName())) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, entry.getName(), IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } } } if (hasDebugAttributes) { getProject().setUserProperty(this.property, "has debug"); //$NON-NLS-1$ } } catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ } }
(Domain) AbortType 5
              
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
public void generateCode(ClassFile enclosingClassFile) { if ((this.bits & ASTNode.HasBeenGenerated) != 0) return; this.bits |= ASTNode.HasBeenGenerated; if (this.ignoreFurtherInvestigation) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); return; } try { // create the result for a compiled type ClassFile classFile = new CodeSnippetClassFile(this.binding, enclosingClassFile, false); // generate all fiels classFile.addFieldInfos(); if (this.binding.isMemberType()) { classFile.recordInnerClasses(this.binding); } else if (this.binding.isLocalType()) { enclosingClassFile.recordInnerClasses(this.binding); classFile.recordInnerClasses(this.binding); } TypeVariableBinding[] typeVariables = this.binding.typeVariables(); for (int i = 0, max = typeVariables.length; i < max; i++) { TypeVariableBinding typeVariableBinding = typeVariables[i]; if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) { Util.recordNestedType(classFile, typeVariableBinding); } } if (this.memberTypes != null) { for (int i = 0, max = this.memberTypes.length; i < max; i++) { TypeDeclaration memberType = this.memberTypes[i]; classFile.recordInnerClasses(memberType.binding); memberType.generateCode(this.scope, classFile); } } // generate all methods classFile.setForMethodInfos(); if (this.methods != null) { for (int i = 0, max = this.methods.length; i < max; i++) { this.methods[i].generateCode(this.scope, classFile); } } // generate all methods classFile.addSpecialMethods(); if (this.ignoreFurtherInvestigation){ // trigger problem type generation for code gen errors throw new AbortType(this.scope.referenceCompilationUnit().compilationResult, null); } // finalize the compiled type result classFile.addAttributes(); this.scope.referenceCompilationUnit().compilationResult.record(this.binding.constantPoolName(), classFile); } catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void generateCode(ClassFile enclosingClassFile) { if ((this.bits & ASTNode.HasBeenGenerated) != 0) return; this.bits |= ASTNode.HasBeenGenerated; if (this.ignoreFurtherInvestigation) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); return; } try { // create the result for a compiled type ClassFile classFile = ClassFile.getNewInstance(this.binding); classFile.initialize(this.binding, enclosingClassFile, false); if (this.binding.isMemberType()) { classFile.recordInnerClasses(this.binding); } else if (this.binding.isLocalType()) { enclosingClassFile.recordInnerClasses(this.binding); classFile.recordInnerClasses(this.binding); } TypeVariableBinding[] typeVariables = this.binding.typeVariables(); for (int i = 0, max = typeVariables.length; i < max; i++) { TypeVariableBinding typeVariableBinding = typeVariables[i]; if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) { Util.recordNestedType(classFile, typeVariableBinding); } } // generate all fiels classFile.addFieldInfos(); if (this.memberTypes != null) { for (int i = 0, max = this.memberTypes.length; i < max; i++) { TypeDeclaration memberType = this.memberTypes[i]; classFile.recordInnerClasses(memberType.binding); memberType.generateCode(this.scope, classFile); } } // generate all methods classFile.setForMethodInfos(); if (this.methods != null) { for (int i = 0, max = this.methods.length; i < max; i++) { this.methods[i].generateCode(this.scope, classFile); } } // generate all synthetic and abstract methods classFile.addSpecialMethods(); if (this.ignoreFurtherInvestigation) { // trigger problem type generation for code gen errors throw new AbortType(this.scope.referenceCompilationUnit().compilationResult, null); } // finalize the compiled type result classFile.addAttributes(); this.scope.referenceCompilationUnit().compilationResult.record( this.binding.constantPoolName(), classFile); } catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
0 0
(Domain) AlignmentException 4
              
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void handleLineTooLong() { if (this.formatter.preferences.wrap_outer_expressions_when_nested) { handleLineTooLongSmartly(); return; } // search for closest breakable alignment, using tiebreak rules // look for outermost breakable one int relativeDepth = 0, outerMostDepth = -1; Alignment targetAlignment = this.currentAlignment; while (targetAlignment != null){ if (targetAlignment.tieBreakRule == Alignment.R_OUTERMOST && targetAlignment.couldBreak()){ outerMostDepth = relativeDepth; } targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (outerMostDepth >= 0) { throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth); } // look for innermost breakable one relativeDepth = 0; targetAlignment = this.currentAlignment; while (targetAlignment != null){ if (targetAlignment.couldBreak()){ throw new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth); } targetAlignment = targetAlignment.enclosing; relativeDepth++; } // did not find any breakable location - proceed }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
private void handleLineTooLongSmartly() { // search for closest breakable alignment, using tiebreak rules // look for outermost breakable one int relativeDepth = 0, outerMostDepth = -1; Alignment targetAlignment = this.currentAlignment; int previousKind = -1; int insideMessage = 0; boolean insideStringConcat = false; while (targetAlignment != null){ boolean couldBreak = targetAlignment.tieBreakRule == Alignment.R_OUTERMOST || (!insideStringConcat && insideMessage > 0 && targetAlignment.kind == Alignment.MESSAGE_ARGUMENTS && (!targetAlignment.wasReset() || previousKind != Alignment.MESSAGE_SEND)); if (couldBreak && targetAlignment.couldBreak()){ outerMostDepth = relativeDepth; } switch (targetAlignment.kind) { case Alignment.MESSAGE_ARGUMENTS: case Alignment.MESSAGE_SEND: insideMessage++; break; case Alignment.STRING_CONCATENATION: insideStringConcat = true; break; } previousKind = targetAlignment.kind; targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (outerMostDepth >= 0) { throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth); } // look for innermost breakable one relativeDepth = 0; targetAlignment = this.currentAlignment; AlignmentException alignmentException = null; int msgArgsDepth = -1; while (targetAlignment != null) { if (targetAlignment.kind == Alignment.MESSAGE_ARGUMENTS) { msgArgsDepth = relativeDepth; } if (alignmentException == null) { if (targetAlignment.couldBreak()) { // do not throw the exception immediately to have a chance to reset // previously broken alignments (see bug 203588) alignmentException = new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth); if (insideStringConcat) throw alignmentException; } } else if (targetAlignment.wasSplit) { // reset the nearest already broken outermost alignment. // Note that it's not done twice to avoid infinite loop while raising // the exception on an innermost alignment... if (!targetAlignment.wasReset()) { targetAlignment.reset(); if (msgArgsDepth > alignmentException.relativeDepth) { alignmentException.relativeDepth = msgArgsDepth; } throw alignmentException; } } targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (alignmentException != null) { throw alignmentException; } // did not find any breakable location - proceed if (this.currentAlignment != null) { this.currentAlignment.blockAlign = false; this.currentAlignment.tooLong = true; } }
// in formatter/org/eclipse/jdt/internal/formatter/align/Alignment.java
public void checkColumn() { if ((this.mode & M_MULTICOLUMN) != 0 && this.fragmentCount > 0) { int currentIndentation = this.scribe.getNextIndentationLevel(this.scribe.column+(this.scribe.needSpace ? 1 : 0)); int fragmentIndentation = this.fragmentIndentations[this.fragmentIndex]; if (currentIndentation > fragmentIndentation) { this.fragmentIndentations[this.fragmentIndex] = currentIndentation; if (fragmentIndentation != 0) { for (int i = this.fragmentIndex+1; i < this.fragmentCount; i++) { this.fragmentIndentations[i] = 0; } this.needRedoColumnAlignment = true; } } // backtrack only once all fragments got checked if (this.needRedoColumnAlignment && this.fragmentIndex == this.fragmentCount-1) { // alignment too small // if (CodeFormatterVisitor.DEBUG){ // System.out.println("ALIGNMENT TOO SMALL"); // System.out.println(this); // } this.needRedoColumnAlignment = false; int relativeDepth = 0; Alignment targetAlignment = this.scribe.memberAlignment; while (targetAlignment != null){ if (targetAlignment == this){ throw new AlignmentException(AlignmentException.ALIGN_TOO_SMALL, relativeDepth); } targetAlignment = targetAlignment.enclosing; relativeDepth++; } } } }
0 0
(Lib) ArrayIndexOutOfBoundsException 4
              
// in model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java
public CharArrayBuffer append(char[] src, int start, int length) { if (start < 0) throw new ArrayIndexOutOfBoundsException(); if (length < 0) throw new ArrayIndexOutOfBoundsException(); if (src != null) { int srcLength = src.length; if (start > srcLength) throw new ArrayIndexOutOfBoundsException(); if (length + start > srcLength) throw new ArrayIndexOutOfBoundsException(); /** do length check here to allow exceptions to be thrown */ if (length > 0) { if (this.end == this.size) { int size2 = this.size * 2; System.arraycopy(this.buffer, 0, (this.buffer = new char[size2][]), 0, this.size); System.arraycopy(this.ranges, 0, (this.ranges = new int[size2][]), 0, this.size); this.size *= 2; } this.buffer[this.end] = src; this.ranges[this.end] = new int[] {start, length}; this.end++; } } return this; }
0 0
(Lib) IndexOutOfBoundsException 4
              
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
0 0
(Domain) InvalidCursorLocation 4
              
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public final void getNextUnicodeChar() throws InvalidInputException { int temp = this.currentPosition; // the \ is already read super.getNextUnicodeChar(); if(this.cursorLocation > temp) { this.unicodeCharSize += (this.currentPosition - temp); } if (temp < this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { int token = super.scanNumber(dotPrefix); // consider completion just before a number to be ok, will insert before it if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER); } return token; }
0 0
(Lib) UTFDataFormatException 3
              
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private char[] readStreamChars(FileInputStream stream) throws IOException { // read chars array length if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int length = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; length += this.streamBuffer[this.bufferIndex++] & 0xFF; // fill the chars from bytes buffer char[] word = new char[length]; int i = 0; while (i < length) { // how many characters can be decoded without refilling the buffer? int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3); // all the characters must already be in the buffer if we're at the end of the stream if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null) charsInBuffer = length; while (i < charsInBuffer) { byte b = this.streamBuffer[this.bufferIndex++]; switch (b & 0xF0) { case 0x00 : case 0x10 : case 0x20 : case 0x30 : case 0x40 : case 0x50 : case 0x60 : case 0x70 : word[i++]= (char) b; break; case 0xC0 : case 0xD0 : char next = (char) this.streamBuffer[this.bufferIndex++]; if ((next & 0xC0) != 0x80) { throw new UTFDataFormatException(); } char ch = (char) ((b & 0x1F) << 6); ch |= next & 0x3F; word[i++] = ch; break; case 0xE0 : char first = (char) this.streamBuffer[this.bufferIndex++]; char second = (char) this.streamBuffer[this.bufferIndex++]; if ((first & second & 0xC0) != 0x80) { throw new UTFDataFormatException(); } ch = (char) ((b & 0x0F) << 12); ch |= ((first& 0x3F) << 6); ch |= second & 0x3F; word[i++] = ch; break; default: throw new UTFDataFormatException(); } } if (i < length && stream != null) readStreamBuffer(stream); } return word; }
0 0
(Lib) Error 2
              
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void deleteVariable(IGlobalVariable variable) { if (variable instanceof GlobalVariableWrapper) { GlobalVariableWrapper wrapper = (GlobalVariableWrapper)variable; this.context.deleteVariable(wrapper.variable); } else { throw new Error("Unknown implementation of IGlobalVariable"); //$NON-NLS-1$ } }
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new Error(); } }
1
              
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
3
              
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
public CompilationUnitDeclaration removeNextUnit() throws Error { CompilationUnitDeclaration next = null; boolean yield = false; synchronized (this) { next = this.units[this.currentIndex]; if (next == null || this.caughtException != null) { do { if (this.processingThread == null) { if (this.caughtException != null) { // rethrow the caught exception from the processingThread in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } return null; } //System.out.print('r'); //if (this.sleepCount > 0) throw new IllegalStateException(new Integer(this.sleepCount).toString()); this.sleepCount = -1; try { wait(100); } catch (InterruptedException ignore) { // ignore } this.sleepCount = 0; next = this.units[this.currentIndex]; } while (next == null); } this.units[this.currentIndex++] = null; if (this.currentIndex >= this.size) this.currentIndex = 0; if (this.sleepCount >= 1 && ++this.sleepCount > 4) { notify(); // wake up processing thread to add next unit but only after removing some elements first yield = this.sleepCount > 8; } } if (yield) Thread.yield(); return next; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
public char[] getContents(ICompilationUnit unit) throws Error { if (this.readingThreads == null || this.units.length == 0) { if (this.caughtException != null) { // rethrow the caught exception from the readingThreads in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } return unit.getContents(); } boolean yield = false; char[] result = null; synchronized (this) { if (unit == this.filesRead[this.readyToReadPosition]) { result = this.contentsRead[this.readyToReadPosition]; while (result == this.readInProcessMarker || result == null) { // let the readingThread know we're waiting //System.out.print('|'); this.contentsRead[this.readyToReadPosition] = null; try { wait(250); } catch (InterruptedException ignore) { // ignore } if (this.caughtException != null) { // rethrow the caught exception from the readingThreads in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } result = this.contentsRead[this.readyToReadPosition]; } // free spot for next file this.filesRead[this.readyToReadPosition] = null; this.contentsRead[this.readyToReadPosition] = null; if (++this.readyToReadPosition >= this.contentsRead.length) this.readyToReadPosition = 0; if (this.sleepingThreadCount > 0) { //System.out.print('+'); //System.out.print(this.nextFileToRead); notify(); yield = this.sleepingThreadCount == this.readingThreads.length; } } else { // must make sure we're reading ahead of the unit int unitIndex = 0; for (int l = this.units.length; unitIndex < l; unitIndex++) if (this.units[unitIndex] == unit) break; if (unitIndex == this.units.length) { // attempting to read a unit that was not included in the initial files - should not happen this.units = new ICompilationUnit[0]; // stop looking for more } else if (unitIndex >= this.nextFileToRead) { // start over //System.out.println(unitIndex + " vs " + this.nextFileToRead); this.nextFileToRead = unitIndex + START_CUSHION; this.readyToReadPosition = 0; this.nextAvailablePosition = 0; this.filesRead = new ICompilationUnit[CACHE_SIZE]; this.contentsRead = new char[CACHE_SIZE][]; notifyAll(); } } } if (yield) Thread.yield(); // ensure other threads get a chance if (result != null) return result; //System.out.print('-'); return unit.getContents(); }
(Domain) FoundRelevantDeltaException 2
              
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
public boolean visit(IResourceDelta delta) /* throws CoreException */ { switch (delta.getKind()){ case IResourceDelta.ADDED : case IResourceDelta.REMOVED : throw new FoundRelevantDeltaException(); case IResourceDelta.CHANGED : // if any flag is set but SYNC or MARKER, this delta should be considered if (delta.getAffectedChildren().length == 0 // only check leaf delta nodes && (delta.getFlags() & ~(IResourceDelta.SYNC | IResourceDelta.MARKERS)) != 0) { throw new FoundRelevantDeltaException(); } } return true; }
0 0
(Domain) InstallException 2
              
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate( char[] codeSnippet, char[][] contextLocalVariableTypeNames, char[][] contextLocalVariableNames, int[] contextLocalVariableModifiers, char[] contextDeclaringTypeName, boolean contextIsStatic, boolean contextIsConstructorCall, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { // Initialialize context this.localVariableTypeNames = contextLocalVariableTypeNames; this.localVariableNames = contextLocalVariableNames; this.localVariableModifiers = contextLocalVariableModifiers; this.declaringTypeName = contextDeclaringTypeName; this.isStatic = contextIsStatic; this.isConstructorCall = contextIsConstructorCall; deployCodeSnippetClassIfNeeded(requestor); try { // Install new variables if needed class ForwardingRequestor implements IRequestor { boolean hasErrors = false; public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) { return requestor.acceptClassFiles(classFiles, codeSnippetClassName); } public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) { requestor.acceptProblem(problem, fragmentSource, fragmentKind); if (problem.isError()) { this.hasErrors = true; } } } ForwardingRequestor forwardingRequestor = new ForwardingRequestor(); if (this.varsChanged) { evaluateVariables(environment, options, forwardingRequestor, problemFactory); } // Compile code snippet if there was no errors while evaluating the variables if (!forwardingRequestor.hasErrors) { Evaluator evaluator = new CodeSnippetEvaluator( codeSnippet, this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); // Send code snippet on target if (classes != null && classes.length > 0) { char[] simpleClassName = evaluator.getClassName(); char[] pkgName = getPackageName(); char[] qualifiedClassName = pkgName.length == 0 ? simpleClassName : CharOperation.concat(pkgName, simpleClassName, '.'); CODE_SNIPPET_COUNTER++; if (!requestor.acceptClassFiles(classes, qualifiedClassName)) throw new InstallException(); } } } finally { // Reinitialize context to default values this.localVariableTypeNames = null; this.localVariableNames = null; this.localVariableModifiers = null; this.declaringTypeName = null; this.isStatic = true; this.isConstructorCall = false; } }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariables(INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { deployCodeSnippetClassIfNeeded(requestor); VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); if (classes != null) { if (classes.length > 0) { // Sort classes so that enclosing types are cached before nested types // otherwise an AbortCompilation is thrown in 1.5 mode since the enclosing type // is needed to resolve a nested type Util.sort(classes, new Util.Comparer() { public int compare(Object a, Object b) { if (a == b) return 0; ClassFile enclosing = ((ClassFile) a).enclosingClassFile; while (enclosing != null) { if (enclosing == b) return 1; enclosing = enclosing.enclosingClassFile; } return -1; } }); // Send classes if (!requestor.acceptClassFiles(classes, null)) { throw new InstallException(); } // Remember that the variables have been installed int count = this.variableCount; GlobalVariable[] variablesCopy = new GlobalVariable[count]; System.arraycopy(this.variables, 0, variablesCopy, 0, count); this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, count); VAR_CLASS_COUNTER++; } this.varsChanged = false; }
0 5
              
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
private void deployCodeSnippetClassIfNeeded(IRequestor requestor) throws InstallException { if (this.codeSnippetBinary == null) { // Deploy CodeSnippet class (only once) if (!requestor.acceptClassFiles( new ClassFile[] { new ClassFile() { public byte[] getBytes() { return getCodeSnippetBytes(); } public char[][] getCompoundName() { return EvaluationConstants.ROOT_COMPOUND_NAME; } } }, null)) throw new InstallException();
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate( char[] codeSnippet, char[][] contextLocalVariableTypeNames, char[][] contextLocalVariableNames, int[] contextLocalVariableModifiers, char[] contextDeclaringTypeName, boolean contextIsStatic, boolean contextIsConstructorCall, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { // Initialialize context this.localVariableTypeNames = contextLocalVariableTypeNames; this.localVariableNames = contextLocalVariableNames; this.localVariableModifiers = contextLocalVariableModifiers; this.declaringTypeName = contextDeclaringTypeName; this.isStatic = contextIsStatic; this.isConstructorCall = contextIsConstructorCall; deployCodeSnippetClassIfNeeded(requestor); try { // Install new variables if needed class ForwardingRequestor implements IRequestor { boolean hasErrors = false; public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) { return requestor.acceptClassFiles(classFiles, codeSnippetClassName); } public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) { requestor.acceptProblem(problem, fragmentSource, fragmentKind); if (problem.isError()) { this.hasErrors = true; } } } ForwardingRequestor forwardingRequestor = new ForwardingRequestor(); if (this.varsChanged) { evaluateVariables(environment, options, forwardingRequestor, problemFactory); } // Compile code snippet if there was no errors while evaluating the variables if (!forwardingRequestor.hasErrors) { Evaluator evaluator = new CodeSnippetEvaluator( codeSnippet, this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); // Send code snippet on target if (classes != null && classes.length > 0) { char[] simpleClassName = evaluator.getClassName(); char[] pkgName = getPackageName(); char[] qualifiedClassName = pkgName.length == 0 ? simpleClassName : CharOperation.concat(pkgName, simpleClassName, '.'); CODE_SNIPPET_COUNTER++; if (!requestor.acceptClassFiles(classes, qualifiedClassName)) throw new InstallException(); } } } finally { // Reinitialize context to default values this.localVariableTypeNames = null; this.localVariableNames = null; this.localVariableModifiers = null; this.declaringTypeName = null; this.isStatic = true; this.isConstructorCall = false; } }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate(char[] codeSnippet, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { this.evaluate( codeSnippet, null, null, null, null, true, false, environment, options, requestor, problemFactory); }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariable(GlobalVariable variable, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { this.evaluate(variable.getName(), environment, options, requestor, problemFactory); }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariables(INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { deployCodeSnippetClassIfNeeded(requestor); VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); if (classes != null) { if (classes.length > 0) { // Sort classes so that enclosing types are cached before nested types // otherwise an AbortCompilation is thrown in 1.5 mode since the enclosing type // is needed to resolve a nested type Util.sort(classes, new Util.Comparer() { public int compare(Object a, Object b) { if (a == b) return 0; ClassFile enclosing = ((ClassFile) a).enclosingClassFile; while (enclosing != null) { if (enclosing == b) return 1; enclosing = enclosing.enclosingClassFile; } return -1; } }); // Send classes if (!requestor.acceptClassFiles(classes, null)) { throw new InstallException(); } // Remember that the variables have been installed int count = this.variableCount; GlobalVariable[] variablesCopy = new GlobalVariable[count]; System.arraycopy(this.variables, 0, variablesCopy, 0, count); this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, count); VAR_CLASS_COUNTER++; } this.varsChanged = false; }
(Domain) SourceTypeCollisionException 2
              
// in compiler/org/eclipse/jdt/internal/compiler/lookup/CompilationUnitScope.java
void buildTypeBindings(AccessRestriction accessRestriction) { this.topLevelTypes = new SourceTypeBinding[0]; // want it initialized if the package cannot be resolved boolean firstIsSynthetic = false; if (this.referenceContext.compilationResult.compilationUnit != null) { char[][] expectedPackageName = this.referenceContext.compilationResult.compilationUnit.getPackageName(); if (expectedPackageName != null && !CharOperation.equals(this.currentPackageName, expectedPackageName)) { // only report if the unit isn't structurally empty if (this.referenceContext.currentPackage != null || this.referenceContext.types != null || this.referenceContext.imports != null) { problemReporter().packageIsNotExpectedPackage(this.referenceContext); } this.currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR : expectedPackageName; } } if (this.currentPackageName == CharOperation.NO_CHAR_CHAR) { // environment default package is never null this.fPackage = this.environment.defaultPackage; } else { if ((this.fPackage = this.environment.createPackage(this.currentPackageName)) == null) { if (this.referenceContext.currentPackage != null) { problemReporter().packageCollidesWithType(this.referenceContext); // only report when the unit has a package statement } // ensure fPackage is not null this.fPackage = this.environment.defaultPackage; return; } else if (this.referenceContext.isPackageInfo()) { // resolve package annotations now if this is "package-info.java". if (this.referenceContext.types == null || this.referenceContext.types.length == 0) { this.referenceContext.types = new TypeDeclaration[1]; this.referenceContext.createPackageInfoType(); firstIsSynthetic = true; } // ensure the package annotations are copied over before resolution if (this.referenceContext.currentPackage != null) this.referenceContext.types[0].annotations = this.referenceContext.currentPackage.annotations; } recordQualifiedReference(this.currentPackageName); // always dependent on your own package } // Skip typeDeclarations which know of previously reported errors TypeDeclaration[] types = this.referenceContext.types; int typeLength = (types == null) ? 0 : types.length; this.topLevelTypes = new SourceTypeBinding[typeLength]; int count = 0; nextType: for (int i = 0; i < typeLength; i++) { TypeDeclaration typeDecl = types[i]; if (this.environment.isProcessingAnnotations && this.environment.isMissingType(typeDecl.name)) throw new SourceTypeCollisionException(); // resolved a type ref before APT generated the type ReferenceBinding typeBinding = this.fPackage.getType0(typeDecl.name); recordSimpleReference(typeDecl.name); // needed to detect collision cases if (typeBinding != null && typeBinding.isValidBinding() && !(typeBinding instanceof UnresolvedReferenceBinding)) { // if its an unresolved binding - its fixed up whenever its needed, see UnresolvedReferenceBinding.resolve() if (this.environment.isProcessingAnnotations) throw new SourceTypeCollisionException(); // resolved a type ref before APT generated the type // if a type exists, check that its a valid type // it can be a NotFound problem type if its a secondary type referenced before its primary type found in additional units // and it can be an unresolved type which is now being defined problemReporter().duplicateTypes(this.referenceContext, typeDecl); continue nextType; } if (this.fPackage != this.environment.defaultPackage && this.fPackage.getPackage(typeDecl.name) != null) { // if a package exists, it must be a valid package - cannot be a NotFound problem package // this is now a warning since a package does not really 'exist' until it contains a type, see JLS v2, 7.4.3 problemReporter().typeCollidesWithPackage(this.referenceContext, typeDecl); } if ((typeDecl.modifiers & ClassFileConstants.AccPublic) != 0) { char[] mainTypeName; if ((mainTypeName = this.referenceContext.getMainTypeName()) != null // mainTypeName == null means that implementor of ICompilationUnit decided to return null && !CharOperation.equals(mainTypeName, typeDecl.name)) { problemReporter().publicClassMustMatchFileName(this.referenceContext, typeDecl); // tolerate faulty main type name (91091), allow to proceed into type construction } } ClassScope child = new ClassScope(this, typeDecl); SourceTypeBinding type = child.buildType(null, this.fPackage, accessRestriction); if (firstIsSynthetic && i == 0) type.modifiers |= ClassFileConstants.AccSynthetic; if (type != null) this.topLevelTypes[count++] = type; } // shrink topLevelTypes... only happens if an error was reported if (count != this.topLevelTypes.length) System.arraycopy(this.topLevelTypes, 0, this.topLevelTypes = new SourceTypeBinding[count], 0, count); }
0 0
(Domain) AnonymousMemberFound 1
              
// 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; }
0 0
(Lib) ClassCastException 1
              
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void checkNewChild(ASTNode node, ASTNode newChild, boolean cycleCheck, Class nodeType) { if (newChild.ast != node.ast) { // new child is from a different AST throw new IllegalArgumentException(); } if (newChild.getParent() != null) { // new child currently has a different parent throw new IllegalArgumentException(); } if (cycleCheck && newChild == node.getRoot()) { // inserting new child would create a cycle throw new IllegalArgumentException(); } Class childClass = newChild.getClass(); if (nodeType != null && !nodeType.isAssignableFrom(childClass)) { // new child is not of the right type throw new ClassCastException(); } if ((newChild.typeAndFlags & PROTECT) != 0) { // new child node is protected => cannot be parented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } }
0 0
(Lib) ExceptionInInitializerError 1 1
              
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
0
(Lib) NullPointerException 1
              
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setLineEndTable(int[] lineEndTable) { if (lineEndTable == null) { throw new NullPointerException(); } // alternate root is *not* considered a structural property // but we protect them nevertheless checkModifiable(); this.lineEndTable = lineEndTable; }
0 0
(Domain) WrappedCoreException 1
              
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
public boolean visit(TypeDeclaration typeDeclaration, BlockScope unused) { try { char[] simpleName; if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { simpleName = CharOperation.NO_CHAR; } else { simpleName = typeDeclaration.name; } int occurrenceCount = this.occurrencesCounts.get(simpleName); if (occurrenceCount == HashtableOfIntValues.NO_VALUE) { occurrenceCount = 1; } else { occurrenceCount = occurrenceCount + 1; } this.occurrencesCounts.put(simpleName, occurrenceCount); if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { this.locator.reportMatching(typeDeclaration, this.enclosingElement, -1, this.nodeSet, occurrenceCount); } else { Integer level = (Integer) this.nodeSet.matchingNodes.removeKey(typeDeclaration); this.locator.reportMatching(typeDeclaration, this.enclosingElement, level != null ? level.intValue() : -1, this.nodeSet, occurrenceCount); } return false; // don't visit members as this was done during reportMatching(...) } catch (CoreException e) { throw new WrappedCoreException(e); } }
1
              
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
0
Explicit thrown (throw new...): 1278/1426
Explicit thrown ratio: 89.6%
Builder thrown ratio: 1.4%
Variable thrown ratio: 8.9%
Checked Runtime Total
Domain 220 228 448
Lib 31 574 605
Total 251 802

Caught Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be caught, and it happens that the catch block contains a throw (e.g. for wrapping a low-level exception). Hovering over a number triggers showing code snippets from the application code.

Type Exception Caught
(directly)
Caught
with Thrown
(Domain) JavaModelException 280
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (JavaModelException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (JavaModelException e) { // copy doesn't exist: ignore }
// in search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
catch (JavaModelException e) { Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$ return new IPath[0]; }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchPattern.java
catch (JavaModelException jme) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchPattern.java
catch (JavaModelException jme) { return; }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (JavaModelException e) { // working copy doesn't exist: cannot happen }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (JavaModelException e) { // project doesn't exist this.locations = new ClasspathLocation[0]; return; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem collecting super type names: leave it null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException jme) { // skip }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with classpath in this project -> skip it }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with classpath in last project -> ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { throw e; }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
catch (JavaModelException e) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
catch (JavaModelException e) { // inaccurate matches will be found }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
catch(JavaModelException e) { // unable to determine kind; tolerate this match }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorPattern.java
catch (JavaModelException e) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (JavaModelException e) { // ignore: continue with next element }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { // project is not a java project }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return new IPath[0]; }
// in search/org/eclipse/jdt/internal/core/search/TypeNameMatchRequestorWrapper.java
catch (JavaModelException e) { // skip }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { // ignored }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(JavaModelException e){ // cannot retrieve classpath info }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (JavaModelException npe) { // elt doesn't exist: return the element }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // if type doesn't exist, no matching method can exist return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // default to using the outer most declaring type name IType type = this; IType enclosingType = getDeclaringType(); while (enclosingType != null) { type = enclosingType; enclosingType = type.getDeclaringType(); } return type.getElementName() + Util.defaultJavaExtension(); }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // root doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // project doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e2) { // project doesn't exist -> ignore continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e1) { // project does not exist -> ignore continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java model could not be opened }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external archives"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project doesn't exist any longer, continue with next one if (!e.isDoesNotExist()) Util.log(e, "Exception while updating project references"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // a project no longer exists }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project no longer exists }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return new JavaModelStatus(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) { e.printStackTrace(); } // project no longer exist return result; }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { pkgFragmentRoots = new PackageFragmentRoot[] {}; }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // project doesn't exist return; }
// in model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // working copy doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return false; // the class is not present, do not accept. }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { continue; // the root is not present, continue; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // pkg does not exist // -> try next package }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { continue; // the package fragment root is not present; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException jme) { // give up }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return; // the package is not present }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // package doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // cu doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // package doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return false; // the enclosing type is not present }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // an exception occurs, return nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // isStatic == false }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { //nothing to do }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // type is null }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // type is null }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { // no source can be attached mapper = null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // could not read classpath, then assume it is outside return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
// in model/org/eclipse/jdt/internal/core/JavaModel.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // in doubt, there is a conflict return true; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // project doesn't exist: return null }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { Util.log(e, "Could not set classpath variable " + varName + " to " + newPath); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // skip }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // cannot retrieve Java projects }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException jme) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java
catch (JavaModelException e) { return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch(JavaModelException e) { return new IProject[0]; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/BinaryField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException jme) { throw jme; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java
catch (JavaModelException e) { // root doesn't exist: consider package has no nonJavaResources this.nonJavaResources = NO_NON_JAVA_RESOURCES; }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch(JavaModelException e) { javadocContents = null; }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (JavaModelException e) { // element doesn't exist: return false }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(JavaModelException jme) { // Proceed with raw classpath }
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (JavaModelException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch(JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { // igmore this project }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) { e.printStackTrace(); } return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
catch (JavaModelException e) { // project doesn't exist }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (JavaModelException e) { // cannot happen since element is open return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (JavaModelException e) { // types/cu exist since cu is opened }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // project doesn't exit: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (JavaModelException e) { // if the focus type is not present, or if cannot get workbench path // we cannot create the hierarchy return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { continue; }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { superRefKind = SuperTypeReferencePattern.ALL_SUPER_TYPES; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { // nothing can be done return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { // continue with next project continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { return this.javaProjectNamesCache; }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/ElementCache.java
catch (JavaModelException npe) { return false; }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
catch (JavaModelException jme) { if (errorsCounter == errors.length) { // resize System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter); } errors[errorsCounter++] = jme.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // ignore and try to find another project }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // java model is not accessible return null; }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // JavaModelException from getResolvedClasspath - a problem occurred while accessing project: nothing we can do, ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { // declaring type doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { // does not exist return null; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
catch (JavaModelException e) { // cu doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { isClasspathResolved = false; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // project does not exist: cannot happen since this is the info of the project roots = new IPackageFragmentRoot[0]; reverseMap.clear(); }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // root doesn't exist: ignore return; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // project doesn't exit continue; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java
catch (JavaModelException jme) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
catch (JavaModelException e) { // receiver doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java
catch (JavaModelException e) { // type parameter does not exist: ignore }
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException npe) { // fall back to using owner }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/CreateImportOperation.java
catch (JavaModelException e) { // cu doesn't exit: ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return new IPackageFragmentRoot[] {}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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
catch (JavaModelException e) { // project doesn't exist: return an empty array }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException jme) { projectOptions = new Hashtable(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return true; // unsure }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ return false; // not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return false; // Perhaps, not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ return false; // not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // project doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // if type doesn't exist, no matching method can exist return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
catch (JavaModelException jme) { return jme.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ExternalJavaProject.java
catch (JavaModelException e) { // getPerProjectInfo() never throws JavaModelException for an ExternalJavaProject }
// in model/org/eclipse/jdt/internal/core/Initializer.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelStatus.java
catch(JavaModelException e){ // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (JavaModelException e) { Util.log(e, "Exception while setting user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // type parameter does not exist: ignore }
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (JavaModelException e) { return null; /* } finally { System.out.println("Spent " + (System.currentTimeMillis() - start) + "ms to convert " + ((JavaElement) converter.cu).toStringWithAncestors()); */ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // project no longer exist: ignore continue; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(JavaModelException jme) { // Creation of external folder project failed. Log it and continue; Util.log(jme, "Error while processing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // /search failed: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // refreshing failed: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { Util.log(e, "Exception while removing variable " + variableName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (JavaModelException e) { return; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch(JavaModelException e) { // Do nothing }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (JavaModelException e) { // method doesn't exist: ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceType.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceMethod.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceField.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(JavaModelException e){ parameters = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(JavaModelException e){ parameters = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (JavaModelException e) { // do nothing }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (JavaModelException e) { return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch (JavaModelException e) { Util.log(e, "Cannot compute enclosing element"); //$NON-NLS-1$ return null; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (JavaModelException e) { return name; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (JavaModelException e) { return name; }
// in dom/org/eclipse/jdt/core/dom/PackageBinding.java
catch(JavaModelException e) { return AnnotationBinding.NoAnnotations; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { // project doesn't exist -> simple parse without resolving parse(compilationUnits, requestor, apiLevel, options, flags, monitor); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (JavaModelException e) { flags &= ~ICompilationUnit.ENABLE_BINDINGS_RECOVERY; compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; }
18
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException jme) { throw jme; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
(Lib) CoreException 208
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/ClasspathSourceDirectory.java
catch(CoreException ignored) { // treat as if missing }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (CoreException e1) { // problem opening zip file or getting root kind // consider root corrupt and ignore // just resize cpLocations System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { // cannot read class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException ce) { // Do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch(CoreException ce) { try { return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset(); } catch (CoreException e) { // use no encoding } }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (CoreException e) { // use no encoding }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddFolderToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(CoreException e) { // ignore delta if not able to traverse }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(CoreException e){ // project doesn't exist or is not open: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e){ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName})); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
catch (CoreException e) { Util.log(e, "Could not retrieve children of " + this.resource.getFullPath()); //$NON-NLS-1$ return NO_CHILDREN; }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { // skip }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { // ignore Util.log(e, "Exception while initializing all containers"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
catch(CoreException e) { this.sourceLocations = new ClasspathMultiDirectory[0]; this.binaryLocations = new ClasspathLocation[0]; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there are no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there are no tasks }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException ignore) { // skip it }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException ignore) { // skip it }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch(CoreException ignored) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (CoreException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException ignored) { // ignore the second exception }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Error while creating a link for external folder :" + folderPath); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while initializing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // use default encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // no problem, use default encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // Ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
catch (CoreException e1) { this.encoding = null; }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (CoreException e) { // CoreException from hasNature - should not happen since we check that the project is accessible // JavaModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/ResourceCompilationUnit.java
catch (CoreException e) { return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (CoreException e) { resources = NO_NON_JAVA_RESOURCES; resourcesCounter = 0; }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName())) return true; // project does not exist or is not open }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not create marker: cannot do much if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not flush markers: not much we can do if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not get markers: return null }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // problems loading preference store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { return newDoesNotExistStatus(); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e) { // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_container_initializer(containerID, configurationElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e){ // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_variable_initializer(variable, configElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException ce) { // fails silently and return plugin global encoding if core exception occurs }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not read version number: consider it is new }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not touch this project: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not touch all projects }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(CoreException e){ // unable to instantiate extension, will answer default formatter instead }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(CoreException e){ // unable to read }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch(CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
79
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
(Lib) IOException 156
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IOException e) { //ignore }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
// in scripts/GenerateBuildScript.java
catch (IOException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (IOException e) { // should not happen as we know that the file exists this.path = directory.getAbsolutePath(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (IOException e) { // treat as if file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { return null; }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // best effort }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // treat as if class file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // in case of error, simply return the absolute path this.path = this.file.getAbsolutePath(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathSourceJar.java
catch (IOException e) { // treat as if source file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch (IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch(IOException exception) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch (IOException e) { // this should not happen as the file exists continue; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { // ignore; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { logNoClassFileCreated(outputPath, relativeFileName, e); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e1) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { this.logger.logNoClassFileCreated(currentDestinationPath, relativeStringName, e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (IOException e) { // cannot read class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/search/indexing/SaveIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to save index " + this.containerPath + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // failed to read the existing file or its no longer compatible if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt if (VERBOSE) Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ rebuildIndex(indexLocation, containerPath); return null; } /*index = null;*/ // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { if (VERBOSE) Util.verbose("-> unable to create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ // The file could not be created. Possible reason: the project has been deleted. return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read javaLikeNames file"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to recreate index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to reset index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(IOException e) { if (VERBOSE) { Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$ e.printStackTrace(); } allSaved = false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read participant index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write javaLikeNames file", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write participant index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write saved index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFolderFromIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
catch (IOException e) { if (e instanceof java.io.EOFException) e.printStackTrace(); return FAILED; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { this.cachedChunks = null; throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // best effort }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // problem occured closing zip file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // problem occured closing zip file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (cacheFile.exists()) Util.log(e, "Unable to read non-chaining jar cache file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(IOException e){ // problem loading xml file: nothing we can do }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { Util.log(e, "Could not recreate persisted container: \n" + containerString); //$NON-NLS-1$ entries = JavaProject.INVALID_CLASSPATH; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (IOException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch(IOException e) { // ignore it }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (IOException e) { // treat as if class file is missing }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { if (timestampsFile.exists()) Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
catch (IOException e) { // could not read file: returns an empty array }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // default to original path return externalPath; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // bad format return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { return null; // never happens since all is done in memory }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // problems loading preference store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // ignore problems with close }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while serializing user library " + libName); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { /* ignore */ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = file.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { /* ignore */ }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e1) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch(IOException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IOException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch(IOException e) { // go to the next unit continue; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch(IOException e) { // go to the next unit continue; }
30
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { this.cachedChunks = null; throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch(IOException e) { throw e; }
(Domain) InvalidInputException 149
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException ex) { // give up }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException iie) { // give up }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { //ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (InvalidInputException e) { // invalid class name }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { openBodyEnd = this.fDocument.length; openBodyStart = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { closeBodyStart = this.fDocument.length; closeBodyEnd = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { closeBodyStart = this.fDocument.length; closeBodyEnd = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/Member.java
catch (InvalidInputException ex) { // try if there is inherited Javadoc }
// in model/org/eclipse/jdt/internal/core/InternalNamingConventions.java
catch(InvalidInputException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/InternalNamingConventions.java
catch(InvalidInputException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { // ignore }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (InvalidInputException e) { return; }
// in model/org/eclipse/jdt/core/JavaConventions.java
catch (InvalidInputException e) { return null; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(currentTokenEndPosition-1); newLine = false; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(commentEnd); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // skip }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // maybe an unterminated string or comment lastColumn += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // Assume length is one int tokenLength = 1; if (nodeStart > (previousEnd+1)) { tokenLength++; // include space between nodes } if ((this.column + tokenLength) > maxColumn) { return 1; } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // does not happen as syntax is correct }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { // maybe an unterminated string or comment textLength += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // there's nothing to do if this exception happens }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // leave }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // skip }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(textEnd); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
catch (InvalidInputException e) { // ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { break nextArg; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException ex) { // ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (InvalidInputException e) { // Nothing to do }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ // it's impossible because we added pending tokens before }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ pos = this.scanner.currentPosition; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/diagnose/LexStream.java
catch (InvalidInputException e) { // return next token }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { consumeToken(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { break nextArg; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { // Do nothing as we want to keep positions for error message }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { end = this.lineEnd; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException iie) { // token is already set to error }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/NodeFinder.java
catch (InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // Should not happen, but return no extended position... return nodeStart; }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // Should not happen, but return no extended position... return nodeEnd; }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch (InvalidInputException e){ // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
19
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
(Domain) AbortCompilation 81
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (AbortCompilation e) { // problem with classpath: report inacurrate matches return null; }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (AbortCompilation e) { // ignore: continue with next element }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (AbortCompilation ignored) { // ignore the AbortCompilcation coming from BuildNotifier.checkCancelWithinCompiler() // the Compiler failed after the user has chose to cancel... likely due to an OutOfMemory error }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // missing 'java.lang' package: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superInterfaces() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperinterfaces; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) hasLocalType[i] = false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // skip it silently }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if (TypeHierarchy.DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // unresolved superclass/superinterface -> ignore }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (AbortCompilation e) { problemFinder.handleInternalException(e, unit); }
// in model/org/eclipse/jdt/internal/compiler/SourceElementParser.java
catch (AbortCompilation e) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch (AbortCompilation e) { assignableTypeBinding = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
catch (AbortCompilation a){ // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
catch (AbortCompilation a){ // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // handle missing types }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch(AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // ignore missing types }
// in dom/org/eclipse/jdt/core/dom/MethodBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
10
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
(Lib) NumberFormatException 69
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { // by default we don't support a class file version we cannot recognize return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch(NumberFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch(NumberFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (NumberFormatException e) { return null; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (NumberFormatException e) { // not a parsable constant return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelCache.java
catch (NumberFormatException e) { // ignore Util.log(e, "Could not parse value for " + RATIO_PROPERTY + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$ }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
catch (NumberFormatException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_annotation = Alignment.M_NO_ALIGNMENT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_enum_constants = Alignment.NONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_resources_in_try = Alignment.M_NEXT_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_union_type_in_multicatch = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.continuation_indentation = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.continuation_indentation_for_array_initializer = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_after_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_after_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_field = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_first_class_body_declaration = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_member_type = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_method = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_new_chunk = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_between_import_groups = 1; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_between_type_declarations = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_at_beginning_of_method_body = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.comment_line_length = 80; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.indentation_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.number_of_empty_lines_to_preserve = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.tab_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.page_width = 80; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (NumberFormatException e) { return def; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (NumberFormatException nfe) { output.append(message, end + 1, start - end); }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(NumberFormatException e) { // key ill-formed }
// in compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
catch(NumberFormatException e){ // ignore ill-formatted limit }
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Float.valueOf(...) doesn't handle hex decimal floats try { float v = FloatUtil.valueOfHexFloatLiteral(this.source); if (v == Float.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Float.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = FloatConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e1) { // if the computation of the constant fails }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats try { double v = FloatUtil.valueOfHexDoubleLiteral(this.source); if (v == Double.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Double.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = DoubleConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e1) { // if the computation of the constant fails }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (NumberFormatException e) { // fall through }
8
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
(Lib) ClassCastException 65
            
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (ClassCastException e){ // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_annotation = Alignment.M_NO_ALIGNMENT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_enum_constants = Alignment.NONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_resources_in_try = Alignment.M_NEXT_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_union_type_in_multicatch = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_annotation_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_anonymous_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.continuation_indentation = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.continuation_indentation_for_array_initializer = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_after_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_after_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_field = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_first_class_body_declaration = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_member_type = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_method = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_new_chunk = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_between_import_groups = 1; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_between_type_declarations = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_at_beginning_of_method_body = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.comment_line_length = 80; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.indentation_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.number_of_empty_lines_to_preserve = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.tab_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.page_width = 80; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ClassCastException e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ClassCastException e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/FieldBinding.java
catch (ClassCastException e) { return null; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/MethodBinding.java
catch (ClassCastException e) { return null; }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
6
            
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
(Lib) IndexOutOfBoundsException 45
            
// in model/org/eclipse/jdt/internal/core/Member.java
catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.wasAcr = true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.wasAcr = true; }
// in dom/org/eclipse/jdt/core/dom/NodeFinder.java
catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 return null; }
9
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
(Domain) AlignmentException 31
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
1
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
(Lib) RuntimeException 31
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(RuntimeException e) { return null; }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/util/BindingKeyResolver.java
catch (RuntimeException e) { Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$ return null; }
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
catch(RuntimeException e) { return null; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (RuntimeException e) { synchronized (this) { this.processingThread = null; this.caughtException = e; } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (RuntimeException e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
catch (RuntimeException e) { // since debugger sometimes call toString methods, problems can easily happen when // toString is called on an instance that is being initialized buffer.setLength(p); buffer.append("!"); //$NON-NLS-1$ buffer.append(standardToString()); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared fields"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve interfaces"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve superclass"); //$NON-NLS-1$ return this.resolver.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ }
13
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
(Lib) IllegalArgumentException 28
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // declaring type is invalid return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // string is not a valid type syntax return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // declaring type is invalid return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // string is not a valid type syntax return null; }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalArgumentException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalArgumentException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316 return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(IllegalArgumentException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch(IllegalArgumentException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch(IllegalArgumentException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (IllegalArgumentException e) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IllegalArgumentException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/NodeInfoStore.java
catch (IllegalArgumentException e) { return null; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
3
            
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
(Domain) ClassFormatException 25
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type return null; }
// in eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (ClassFormatException e) { // treat as if file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch(ClassFormatException e) { // treat as if class file is missing }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (ClassFormatException e) { // invalid class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (ClassFormatException e) { //e.printStackTrace(); return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown if (JavaCore.getPlugin().isDebugging()) { cfe.printStackTrace(System.err); } return null; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (ClassFormatException e) { // treat as if class file is missing }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(ClassFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch(ClassFormatException e) { dumpTab(tabNumber + 2, buffer); buffer.append(Messages.classformat_classformatexception); writeNewLine(buffer, lineSeparator, tabNumber + 1); }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (ClassFormatException e) { return true; }
2
            
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
(Lib) InterruptedException 18
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch(InterruptedException e){ // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // background indexing was interrupted }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
catch(InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
catch(InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (InterruptedException e) { return projectInfo.secondaryTypes; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (InterruptedException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (InterruptedException e) { // Do nothing }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (InterruptedException e) { // continue }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignored) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InterruptedException e) { // ignore }
0
(Lib) Exception 17
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (Exception e) { this.printlnErr(this.main.bind( "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
catch(Exception e){ // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
catch (Exception e) { if (JobManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch(Exception e) { this.knownPackageNames = new SimpleSet(); // assume for this build the zipFile is empty }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (Exception ex) { validComment = false; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (Exception e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ast/JavadocSingleNameReference.java
catch (Exception e) { scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, -1); }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
4
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
(Lib) FileNotFoundException 16
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (FileNotFoundException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559 }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
1
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
(Lib) BackingStoreException 14
            
// in model/org/eclipse/jdt/internal/core/JavaCorePreferenceModifyListener.java
catch (BackingStoreException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e1) { // TODO (frederic) see if it's necessary to report this failure... }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(BackingStoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(BackingStoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e) { Util.log(e, "Could not save JavaCore preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e) { // ignore exception }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { projectOptions = new Hashtable(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // problem with pref store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // problem with pref store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // fails silently }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while initializing user libraries"); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while flusing instance preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while removing user library " + libName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while saving user library " + libName); //$NON-NLS-1$ }
0
(Lib) BadLocationException 14
            
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
catch (BadLocationException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (BadLocationException e) { e.printStackTrace(); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (BadLocationException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { log(e); // bug in the formatter Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (BadLocationException e) { // can not happen return code; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (BadLocationException cannotHappen) { // can not happen }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/LineInformation.java
catch (BadLocationException e) { return -1; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/LineInformation.java
catch (BadLocationException e) { return -1; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { //JavaPlugin.log(e); // bug in the formatter Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
4
            
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
(Lib) ArrayIndexOutOfBoundsException 12
            
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (ArrayIndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/core/JavaConventions.java
catch (ArrayIndexOutOfBoundsException e) { return null; }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (ArrayIndexOutOfBoundsException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (ArrayIndexOutOfBoundsException e) { return "Cannot bind message for problem (id: " //$NON-NLS-1$ + (id & IProblem.IgnoreCategoriesMask) + ") \"" //$NON-NLS-1$ + new String(message) + "\" with arguments: {" //$NON-NLS-1$ + Util.toString(problemArguments) +"}"; //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
6
            
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
(Lib) Error 11
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (Error e) { synchronized (this) { this.processingThread = null; this.caughtException = e; } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (Error e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
9
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
(Lib) UnsupportedEncodingException 11
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (UnsupportedEncodingException e) { // ignore (UTF8 is always supported) }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); }
// in compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
catch(UnsupportedEncodingException e){ // ignore unsupported encoding }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); }
4
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
(Domain) AbortType 10
            
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
0
(Lib) IllegalAccessException 10
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalAccessException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (IllegalAccessException ignored) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IllegalAccessException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ProblemReferenceBinding.java
catch (IllegalAccessException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) MissingResourceException 9
            
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch (MissingResourceException e) { return '!' + key + '!'; }
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch (MissingResourceException e) { return '!' + key + '!'; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (MissingResourceException e) { // If we got an exception looking for the message, fail gracefully by just returning // the id we were looking for. In most cases this is semi-informative so is not too bad. return "Missing message: " + id + " in: " + Main.bundleName; //$NON-NLS-2$ //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { result[i] = name[i]; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (MissingResourceException e) { // available ID }
4
            
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
(Lib) OperationCanceledException 9
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (OperationCanceledException oce) { // do nothing }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (OperationCanceledException e) { // catch this exception so as to not enter the catch(RuntimeException e) below throw e; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { // Do nothing }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (OperationCanceledException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
4
            
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (OperationCanceledException e) { // catch this exception so as to not enter the catch(RuntimeException e) below throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
(Domain) AssertionFailedException 8
            
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (AssertionFailedException e) { // Catch the assertion failure and throw java model exception instead // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException ase) { Util.log(ase, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
2
            
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
(Domain) AbortCompilationUnit 7
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(AbortCompilationUnit abortException) { problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); contents = CharOperation.NO_CHAR; // pretend empty from thereon }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { // ignore }
2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
(Domain) AbortMethod 7
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/MethodDeclaration.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { // should never occur // the clinit referenceContext is the type declaration // All clinit problems will be reported against the type: AbortType instead of AbortMethod // reset the contentsOffset to the value before generating the clinit code // decrement the number of method info as well. // This is done in the addProblemMethod and addProblemConstructor for other // cases. if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode // restart method generation restart = true; } else { classFile.contentsOffset = clinitOffset; classFile.methodCount--; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); // restart method generation restart = true; } else { // produce a problem method accounting for this fatal error classFile.contentsOffset = clinitOffset; classFile.methodCount--; restart = false; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // a fatal error was detected during code generation, need to restart code gen if possible if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { // after restarting in wide mode, code generation failed again // report a problem restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // ========= abort on fatal error ============= this.ignoreFurtherInvestigation = true; }
0
(Lib) SecurityException 7
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (SecurityException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SecurityException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (SecurityException e) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (SecurityException e) { // ignore }
0
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
(Lib) InvocationTargetException 6
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (InvocationTargetException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InvocationTargetException e) { // ignored }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) NoSuchMethodException 6
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (NoSuchMethodException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (NoSuchMethodException e) { // ignored }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) IllegalStateException 5
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IllegalStateException e) { this.logger.logWrongJDK(); this.proceed = false; return null; }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
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 */ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (IllegalStateException ise) { // happen when there's no workspace (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=216817) // or when it is shutting down (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=60687) return System.getProperty("file.encoding"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
2
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
(Domain) AbortFormatting 4
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
0
(Domain) CompletionNodeFound 4
            
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, compilationUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
0
(Domain) InstallException 4
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
catch (InstallException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
0
(Lib) ParserConfigurationException 4
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(ParserConfigurationException e){ return; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { return null; }
2
            
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
(Lib) SAXException 4
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SAXException e) { return; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { return null; }
2
            
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
(Lib) ClassNotFoundException 3
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (ClassNotFoundException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (ClassNotFoundException e) { // ignored }
1
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
(Lib) CloneNotSupportedException 3
            
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (CloneNotSupportedException e1) { // ignore (implementation of HashtableOfArrayToObject supports cloning) }
// in model/org/eclipse/jdt/internal/core/builder/State.java
catch (CloneNotSupportedException e) { this.references = new SimpleLookupTable(lastState.references.elementSize); Object[] keyTable = lastState.references.keyTable; Object[] valueTable = lastState.references.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.references.put(keyTable[i], valueTable[i]); this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize); keyTable = lastState.typeLocators.keyTable; valueTable = lastState.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.typeLocators.put(keyTable[i], valueTable[i]); }
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
1
            
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
(Lib) MalformedTreeException 3
            
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (MalformedTreeException e) { e.printStackTrace(); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
2
            
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
(Domain) SourceTypeCollisionException 3
            
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { reset(); // a generated type was referenced before it was created // the compiler either created a MissingType or found a BinaryType for it // so add the processor's generated files & start over, // but remember to only pass the generated files to the annotation processor int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits); return; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
2
            
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
(Lib) BadPositionCategoryException 2
            
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadPositionCategoryException cannotHappen) { // can not happen: category is correctly set up }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadPositionCategoryException cannotHappen) { // can not happen: category is correctly set up }
0
(Lib) InstantiationException 2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Domain) InvalidCursorLocation 2
            
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error (added to fix 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
0
(Lib) MalformedURLException 2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
(Lib) NegativeArraySizeException 2
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
2
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
(Lib) NullPointerException 2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (NullPointerException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316 return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (NullPointerException e) { return false; }
0
(Domain) SelectionNodeFound 2
            
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
0
(Domain) ShouldNotImplement 2
            
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ShouldNotImplement e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ShouldNotImplement e) { this.contentsOffset = startingContentsOffset; }
0
(Domain) WrappedCoreException 2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
(Domain) AbortIncrementalBuildException 1
            
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (AbortIncrementalBuildException e) { // abort the incremental build and let the batch builder handle the problem if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... problem with " + e.qualifiedTypeName + //$NON-NLS-1$ ". Likely renamed inside its existing source file."); //$NON-NLS-1$ return false; }
0
(Domain) AnonymousMemberFound 1
            
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (AnonymousMemberFound e) { return new Parser(this.problemReporter, true).parse(this.cu, compilationResult); }
0
(Lib) ArithmeticException 1
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/BinaryExpression.java
catch (ArithmeticException e) { this.constant = Constant.NotAConstant; // 1.2 no longer throws an exception at compile-time //scope.problemReporter().compileTimeConstantThrowsArithmeticException(this); }
0
(Domain) DOMException 1
            
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (DOMException e) { if (e.code != DOMException.NOT_FOUND_ERR) throw e; return null; }
1
            
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (DOMException e) { if (e.code != DOMException.NOT_FOUND_ERR) throw e; return null; }
(Domain) FoundRelevantDeltaException 1
            
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(FoundRelevantDeltaException e) { //System.out.println("RELEVANT DELTA detected in: "+ (System.currentTimeMillis() - start)); return true; }
0
(Domain) ImageBuilderInternalException 1
            
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
0
(Domain) MissingSourceFileException 1
            
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
0
(Lib) OutOfMemoryError 1
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
1
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
(Lib) ProtocolException 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(ProtocolException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0
(Lib) SocketException 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(SocketException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0
(Lib) SocketTimeoutException 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
(Lib) Throwable 1
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/SwitchStatement.java
catch (Throwable e) { e.printStackTrace(); }
0
(Lib) UnknownHostException 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(UnknownHostException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0
(Lib) UnsupportedClassVersionError 1
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(UnsupportedClassVersionError e) { // report a warning this.logger.logIncorrectVMVersionForAnnotationProcessing(); }
0
(Lib) ZipException 1
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
1
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }

Exception Recast Summary

There is a common practice of throwing exceptions from within a catch block (e.g. for wrapping a low-level exception). The following table summarizes the usage of this practice in the application. The last column gives the number of times it happens for a pair of exceptions. The graph below the table graphically renders the same information. For a given node, its color represents its origin (blue means library exception, orange means domain exception); the left-most number is the number of times it is thrown, the right-most is the number of times it is caught.

Catch Throw
(Lib) MissingResourceException
Unknown
4
                    
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
(Lib) ClassNotFoundException
(Lib) BuildException
1
                    
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
(Lib) Exception
(Lib) BuildException
(Lib) CoreException
(Domain) ClassFormatException
1
                    
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
1
                    
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
2
                    
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
(Domain) ClassFormatException
Unknown
2
                    
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
(Domain) InvalidInputException
(Domain) AbortFormatting
(Lib) CoreException
(Lib) IllegalArgumentException
Unknown
7
                    
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
1
                    
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
8
                    
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
3
                    
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
(Lib) NoSuchMethodException
(Lib) IllegalArgumentException
1
                    
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) IllegalAccessException
(Domain) AbortCompilation
(Lib) IllegalArgumentException
1
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
1
                    
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) InvocationTargetException
(Lib) IllegalArgumentException
1
                    
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Lib) IOException
(Lib) BuildException
(Domain) AbortCompilationUnit
(Lib) IllegalArgumentException
(Domain) JavaModelException
(Lib) CoreException
(Lib) ExceptionInInitializerError
Unknown
1
                    
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
1
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
2
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
12
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
5
                    
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
1
                    
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
8
                    
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { this.cachedChunks = null; throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch(IOException e) { throw e; }
(Lib) ZipException
(Lib) BuildException
1
                    
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
(Domain) AbortCompilationUnit
Unknown
2
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
(Lib) IllegalArgumentException
(Domain) JavaModelException
(Lib) IllegalStateException
Unknown
1
                    
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
1
                    
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
1
                    
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
(Lib) FileNotFoundException
(Lib) IllegalArgumentException
1
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
(Lib) UnsupportedEncodingException
(Lib) IllegalArgumentException
(Domain) JavaModelException
3
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
1
                    
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
(Lib) NumberFormatException
(Lib) IllegalArgumentException
Unknown
2
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
6
                    
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
(Lib) RuntimeException
(Lib) CoreException
(Domain) JavaModelException
Unknown
1
                    
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
1
                    
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
11
                    
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
(Domain) WrappedCoreException
Unknown
2
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
(Domain) AssertionFailedException
(Domain) JavaModelException
2
                    
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
(Domain) DOMException
Unknown
1
                    
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (DOMException e) { if (e.code != DOMException.NOT_FOUND_ERR) throw e; return null; }
(Domain) AlignmentException
Unknown
1
                    
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
(Domain) AbortCompilation
Unknown
10
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
(Domain) SourceTypeCollisionException
Unknown
2
                    
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
(Lib) IllegalStateException
(Lib) IllegalArgumentException
2
                    
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
(Lib) InstantiationException
(Domain) AbortCompilation
(Lib) IllegalArgumentException
1
                    
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
1
                    
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
(Domain) JavaModelException
(Domain) AbortCompilationUnit
(Lib) IllegalArgumentException
(Lib) IllegalStateException
Unknown
1
                    
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
2
                    
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
2
                    
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
13
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException jme) { throw jme; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
(Lib) OperationCanceledException
Unknown
4
                    
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (OperationCanceledException e) { // catch this exception so as to not enter the catch(RuntimeException e) below throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
(Lib) CoreException
(Domain) JavaModelException
(Domain) WrappedCoreException
(Domain) AbortCompilation
Unknown
49
                    
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
1
                    
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
2
                    
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
27
                    
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
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/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
(Lib) Error
Unknown
9
                    
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
(Lib) ArrayIndexOutOfBoundsException
(Domain) ClassFormatException
(Lib) IllegalArgumentException
2
                    
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
4
                    
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
(Lib) OutOfMemoryError
Unknown
1
                    
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
(Lib) BadLocationException
(Domain) JavaModelException
(Lib) IllegalArgumentException
2
                    
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
2
                    
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
(Lib) CloneNotSupportedException
(Lib) Error
1
                    
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
(Lib) MalformedTreeException
(Domain) JavaModelException
Unknown
1
                    
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
1
                    
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
(Lib) SAXException
(Lib) IOException
2
                    
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
(Lib) ParserConfigurationException
(Lib) IOException
2
                    
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
(Lib) MalformedURLException
(Domain) JavaModelException
2
                    
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
(Lib) SocketTimeoutException
(Domain) JavaModelException
1
                    
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
(Lib) IndexOutOfBoundsException
(Domain) InvalidInputException
9
                    
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
(Lib) ClassCastException
(Domain) InvalidInputException
6
                    
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
(Lib) NegativeArraySizeException
(Domain) AbortMethod
2
                    
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }

Caught / Thrown Exception

Not all exceptions are thrown AND caught in the same project. The following table gives the exceptions types with respect to this. The lower left hand side sell lists all exceptions thrown but not caught (prevalent for libraries), the upper right-hand side lists all exceptions caught but not thrown (usually coming from external dependencies).

Thrown Not Thrown
Caught
Type Name
(Domain) InstallException
(Domain) ClassFormatException
(Domain) InvalidInputException
(Lib) IOException
(Domain) AbortType
(Domain) AbortMethod
(Domain) AbortCompilationUnit
(Lib) IllegalArgumentException
(Lib) NumberFormatException
(Lib) RuntimeException
(Domain) WrappedCoreException
(Domain) FoundRelevantDeltaException
(Domain) AssertionFailedException
(Domain) AnonymousMemberFound
(Domain) DOMException
(Domain) AbortFormatting
(Domain) AlignmentException
(Domain) CompletionNodeFound
(Domain) InvalidCursorLocation
(Domain) SelectionNodeFound
(Domain) AbortCompilation
(Domain) ShouldNotImplement
(Domain) SourceTypeCollisionException
(Lib) IllegalStateException
(Domain) JavaModelException
(Lib) OperationCanceledException
(Lib) CoreException
(Lib) Error
(Lib) ArrayIndexOutOfBoundsException
(Lib) NullPointerException
(Lib) IndexOutOfBoundsException
(Lib) ClassCastException
Type Name
(Lib) MissingResourceException
(Lib) ClassNotFoundException
(Lib) Exception
(Lib) NoSuchMethodException
(Lib) IllegalAccessException
(Lib) InvocationTargetException
(Lib) ZipException
(Lib) SecurityException
(Lib) FileNotFoundException
(Lib) UnsupportedEncodingException
(Domain) AbortIncrementalBuildException
(Domain) MissingSourceFileException
(Domain) ImageBuilderInternalException
(Lib) InstantiationException
(Lib) UnsupportedClassVersionError
(Lib) InterruptedException
(Lib) OutOfMemoryError
(Lib) BackingStoreException
(Lib) BadLocationException
(Lib) CloneNotSupportedException
(Lib) MalformedTreeException
(Lib) SAXException
(Lib) ParserConfigurationException
(Lib) MalformedURLException
(Lib) SocketTimeoutException
(Lib) SocketException
(Lib) UnknownHostException
(Lib) ProtocolException
(Lib) BadPositionCategoryException
(Lib) NegativeArraySizeException
(Lib) Throwable
(Lib) ArithmeticException
Not caught
Type Name
(Lib) BuildException
(Lib) UTFDataFormatException
(Lib) NoSuchElementException
(Lib) UnsupportedOperationException
(Lib) ExceptionInInitializerError

Methods called in Catch and Finally Blocks

The following shows the methods that are called inside catch blocks (first column) and finally blocks (second column). For each method, we give the number of times it is called in a catch block (second sub-column), and the total number of calls (third sub-column). If the method name is red, it means that it is only called from catch/finally blocks. Hovering over a number triggers showing code snippets from the application code.

Catch Finally
Method Nbr Nbr total
printStackTrace 105
                  
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type return null; }
// in eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in scripts/GenerateBuildScript.java
catch (IOException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (SecurityException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddFolderToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/SaveIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to save index " + this.containerPath + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to recreate index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to reset index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(IOException e) { if (VERBOSE) { Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$ e.printStackTrace(); } allSaved = false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFolderFromIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
catch (Exception e) { if (JobManager.VERBOSE) { e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
catch (IOException e) { if (e instanceof java.io.EOFException) e.printStackTrace(); return FAILED; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown if (JavaCore.getPlugin().isDebugging()) { cfe.printStackTrace(System.err); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) { e.printStackTrace(); } // project no longer exist return result; }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) { e.printStackTrace(); } return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if (TypeHierarchy.DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (MalformedTreeException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (BadLocationException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not create marker: cannot do much if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not flush markers: not much we can do if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
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); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e) { // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_container_initializer(containerID, configurationElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e){ // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_variable_initializer(variable, configElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { e.printStackTrace(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error (added to fix 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SwitchStatement.java
catch (Throwable e) { e.printStackTrace(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
128
log 71
                  
// in search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
catch (JavaModelException e) { Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$ return new IPath[0]; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external archives"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project doesn't exist any longer, continue with next one if (!e.isDoesNotExist()) Util.log(e, "Exception while updating project references"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
catch (CoreException e) { Util.log(e, "Could not retrieve children of " + this.resource.getFullPath()); //$NON-NLS-1$ return NO_CHILDREN; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { Util.log(e, "Could not set classpath variable " + varName + " to " + newPath); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { // ignore Util.log(e, "Exception while initializing all containers"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (cacheFile.exists()) Util.log(e, "Unable to read non-chaining jar cache file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { Util.log(e, "Could not recreate persisted container: \n" + containerString); //$NON-NLS-1$ entries = JavaProject.INVALID_CLASSPATH; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e) { Util.log(e, "Could not save JavaCore preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Error while creating a link for external folder :" + folderPath); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while initializing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { if (timestampsFile.exists()) Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/util/BindingKeyResolver.java
catch (RuntimeException e) { Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$ return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); }
// in model/org/eclipse/jdt/internal/core/JavaModelCache.java
catch (NumberFormatException e) { // ignore Util.log(e, "Could not parse value for " + RATIO_PROPERTY + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while initializing user libraries"); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while flusing instance preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (JavaModelException e) { Util.log(e, "Exception while setting user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException ase) { Util.log(ase, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while removing user library " + libName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while serializing user library " + libName); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while saving user library " + libName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(JavaModelException jme) { // Creation of external folder project failed. Log it and continue; Util.log(jme, "Error while processing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { Util.log(e, "Exception while removing variable " + variableName); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (BadLocationException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { log(e); // bug in the formatter Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch (JavaModelException e) { Util.log(e, "Cannot compute enclosing element"); //$NON-NLS-1$ return null; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared fields"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve interfaces"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve superclass"); //$NON-NLS-1$ return this.resolver.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
110
handleException
49
                  
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
49
println 34
                  
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (AbortIncrementalBuildException e) { // abort the incremental build and let the batch builder handle the problem if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... problem with " + e.qualifiedTypeName + //$NON-NLS-1$ ". Likely renamed inside its existing source file."); //$NON-NLS-1$ return false; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error (added to fix 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
855
append 30
                  
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/BinaryField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch(ClassFormatException e) { dumpTab(tabNumber + 2, buffer); buffer.append(Messages.classformat_classformatexception); writeNewLine(buffer, lineSeparator, tabNumber + 1); }
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/Initializer.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (NumberFormatException nfe) { output.append(message, end + 1, start - end); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
catch (RuntimeException e) { // since debugger sometimes call toString methods, problems can easily happen when // toString is called on an instance that is being initialized buffer.setLength(p); buffer.append("!"); //$NON-NLS-1$ buffer.append(standardToString()); }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
5000
redoAlignment
29
                  
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
29
bind 27
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (Exception e) { this.printlnErr(this.main.bind( "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e){ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName})); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
471
verbose 22
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/AddFolderToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/SaveIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to save index " + this.containerPath + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // failed to read the existing file or its no longer compatible if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt if (VERBOSE) Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ rebuildIndex(indexLocation, containerPath); return null; } /*index = null;*/ // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { if (VERBOSE) Util.verbose("-> unable to create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ // The file could not be created. Possible reason: the project has been deleted. return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read javaLikeNames file"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to recreate index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to reset index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(IOException e) { if (VERBOSE) { Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$ e.printStackTrace(); } allSaved = false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read participant index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write javaLikeNames file", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write participant index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write saved index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFolderFromIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
169
getMessage 20
                  
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (AssertionFailedException e) { // Catch the assertion failure and throw java model exception instead // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { log(e); // bug in the formatter Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { //JavaPlugin.log(e); // bug in the formatter Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
64
getStatus 18
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
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/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (JavaModelException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { if (e.getStatus().getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { return null; } else { throw e; } }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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); } }
25
handleInternalException 16
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (AbortCompilation e) { problemFinder.handleInternalException(e, unit); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
19
JavaModelStatus 14
                  
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return new JavaModelStatus(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (AssertionFailedException e) { // Catch the assertion failure and throw java model exception instead // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e){ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName})); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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; }
176
String 14
                  
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (ArrayIndexOutOfBoundsException e) { return "Cannot bind message for problem (id: " //$NON-NLS-1$ + (id & IProblem.IgnoreCategoriesMask) + ") \"" //$NON-NLS-1$ + new String(message) + "\" with arguments: {" //$NON-NLS-1$ + Util.toString(problemArguments) +"}"; //$NON-NLS-1$ }
1987
getElementName 14
                  
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // default to using the outer most declaring type name IType type = this; IType enclosingType = getDeclaringType(); while (enclosingType != null) { type = enclosingType; enclosingType = type.getDeclaringType(); } return type.getElementName() + Util.defaultJavaExtension(); }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/BinaryField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/Initializer.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
352
equals 12
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName())) return true; // project does not exist or is not open }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
1920
referenceCompilationUnit 12
                  
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
57
getCode 11
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
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/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { if (e.getStatus().getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { return null; } else { throw e; } }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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); } }
23
getJavaModelStatus 10
                  
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // could not read classpath, then assume it is outside return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
catch (JavaModelException jme) { if (errorsCounter == errors.length) { // resize System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter); } errors[errorsCounter++] = jme.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
catch (JavaModelException jme) { return jme.getJavaModelStatus(); }
11
toString 9
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (Exception e) { this.printlnErr(this.main.bind( "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (ArrayIndexOutOfBoundsException e) { return "Cannot bind message for problem (id: " //$NON-NLS-1$ + (id & IProblem.IgnoreCategoriesMask) + ") \"" //$NON-NLS-1$ + new String(message) + "\" with arguments: {" //$NON-NLS-1$ + Util.toString(problemArguments) +"}"; //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
1016
exists 8
                  
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (cacheFile.exists()) Util.log(e, "Unable to read non-chaining jar cache file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { if (timestampsFile.exists()) Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
140
getPath 8
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
318
updateContext
8
                  
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
8
Status 7
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
38
getName 7
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName())) return true; // project does not exist or is not open }
501
problemReporter 7
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(AbortCompilationUnit abortException) { problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); contents = CharOperation.NO_CHAR; // pretend empty from thereon }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/JavadocSingleNameReference.java
catch (Exception e) { scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, -1); }
1017
delete 6
                  
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); }
46
close 5
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
124
createDefaultParameterNames 5
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
7
internalException 5
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
6
recordComment 5
                  
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
15
removeIndex 5
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
15
arraycopy 4
                  
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (CoreException e1) { // problem opening zip file or getting root kind // consider root corrupt and ignore // just resize cpLocations System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index); }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
catch (JavaModelException jme) { if (errorsCounter == errors.length) { // resize System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter); } errors[errorsCounter++] = jme.getJavaModelStatus(); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { reset(); // a generated type was referenced before it was created // the compiler either created a MissingType or found a BinaryType for it // so add the processor's generated files & start over, // but remember to only pass the generated files to the annotation processor int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits); return; }
1370
consumeToken 4
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { consumeToken(); }
50
convertSearchFilterToModelFilter 4
                  
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
7
failedToFormat 4
                  
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
5
getAbsolutePath 4
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (IOException e) { // should not happen as we know that the file exists this.path = directory.getAbsolutePath(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // in case of error, simply return the absolute path this.path = this.file.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = file.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); }
26
getException 4
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
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/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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); } }
22
getKey 4
                  
// in model/org/eclipse/jdt/internal/core/util/BindingKeyResolver.java
catch (RuntimeException e) { Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$ return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
129
isDoesNotExist 4
                  
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external archives"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project doesn't exist any longer, continue with next one if (!e.isDoesNotExist()) Util.log(e, "Exception while updating project references"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
5
parseTags 4
                  
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
8
replace 4
                  
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
142
checkTaskTag 3
                  
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
9
consumeInvalidToken
3
                  
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(currentTokenEndPosition-1); newLine = false; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(commentEnd); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(textEnd); }
3
createInconsistentBuildMarker
3
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
3
flush 3
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
35
getFullPath 3
                  
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
catch (CoreException e) { Util.log(e, "Could not retrieve children of " + this.resource.getFullPath()); //$NON-NLS-1$ return NO_CHILDREN; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
168
getProperty 3
                  
// in model/org/eclipse/jdt/core/JavaCore.java
catch (IllegalStateException ise) { // happen when there's no workspace (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=216817) // or when it is shutting down (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=60687) return System.getProperty("file.encoding"); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
39
getString 3
                  
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
16
handleInstallException
3
                  
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
3
logRepeatedMessage 3
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
6
parse 3
                  
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (AnonymousMemberFound e) { return new Parser(this.problemReporter, true).parse(this.cu, compilationResult); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { // project doesn't exist -> simple parse without resolving parse(compilationUnits, requestor, apiLevel, options, flags, monitor); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (JavaModelException e) { flags &= ~ICompilationUnit.ENABLE_BINDINGS_RECOVERY; compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; }
74
remove 3
                  
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
157
reset 3
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { reset(); // a generated type was referenced before it was created // the compiler either created a MissingType or found a BinaryType for it // so add the processor's generated files & start over, // but remember to only pass the generated files to the annotation processor int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits); return; }
81
resetForCodeGenUnusedLocals 3
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { // should never occur // the clinit referenceContext is the type declaration // All clinit problems will be reported against the type: AbortType instead of AbortMethod // reset the contentsOffset to the value before generating the clinit code // decrement the number of method info as well. // This is done in the addProblemMethod and addProblemConstructor for other // cases. if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode // restart method generation restart = true; } else { classFile.contentsOffset = clinitOffset; classFile.methodCount--; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); // restart method generation restart = true; } else { // produce a problem method accounting for this fatal error classFile.contentsOffset = clinitOffset; classFile.methodCount--; restart = false; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // a fatal error was detected during code generation, need to restart code gen if possible if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { // after restarting in wide mode, code generation failed again // report a problem restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
4
resetInWideMode 3
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { // should never occur // the clinit referenceContext is the type declaration // All clinit problems will be reported against the type: AbortType instead of AbortMethod // reset the contentsOffset to the value before generating the clinit code // decrement the number of method info as well. // This is done in the addProblemMethod and addProblemConstructor for other // cases. if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode // restart method generation restart = true; } else { classFile.contentsOffset = clinitOffset; classFile.methodCount--; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); // restart method generation restart = true; } else { // produce a problem method accounting for this fatal error classFile.contentsOffset = clinitOffset; classFile.methodCount--; restart = false; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // a fatal error was detected during code generation, need to restart code gen if possible if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { // after restarting in wide mode, code generation failed again // report a problem restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
4
shutdown 3
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (Error e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (RuntimeException e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
7
toOSString 3
                  
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
53
valueOf 3
                  
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
337
Hashtable 2
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException jme) { projectOptions = new Hashtable(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { projectOptions = new Hashtable(); }
26
NLSTag 2
                  
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
4
Path 2
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); }
96
PrintWriter 2
                  
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
22
SimpleLookupTable 2
                  
// in model/org/eclipse/jdt/internal/core/builder/State.java
catch (CloneNotSupportedException e) { this.references = new SimpleLookupTable(lastState.references.elementSize); Object[] keyTable = lastState.references.keyTable; Object[] valueTable = lastState.references.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.references.put(keyTable[i], valueTable[i]); this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize); keyTable = lastState.typeLocators.keyTable; valueTable = lastState.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.typeLocators.put(keyTable[i], valueTable[i]); }
55
StringBuffer 2
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
405
StringWriter 2
                  
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
6
add 2
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
954
atEnd 2
                  
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // maybe an unterminated string or comment lastColumn += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { // maybe an unterminated string or comment textLength += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
43
complete 2
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, compilationUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
9
createExternalFoldersProject 2
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); }
5
createProblemFor 2
                  
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
4
createProblemType 2
                  
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); }
6
discardJobs 2
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
9
exit 2
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
3
findExactTypes 2
                  
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
4
findTypes 2
                  
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
12
fromValue 2
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Float.valueOf(...) doesn't handle hex decimal floats try { float v = FloatUtil.valueOfHexFloatLiteral(this.source); if (v == Float.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Float.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = FloatConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats try { double v = FloatUtil.valueOfHexDoubleLiteral(this.source); if (v == Double.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Double.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = DoubleConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
766
getBuffer 2
                  
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
60
getBytes 2
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); }
25
getCurrentTokenEndPosition 2
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
56
getDeclaringType 2
                  
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // default to using the outer most declaring type name IType type = this; IType enclosingType = getDeclaringType(); while (enclosingType != null) { type = enclosingType; enclosingType = type.getDeclaringType(); } return type.getElementName() + Util.defaultJavaExtension(); }
45
getDefault 2
                  
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
27
getJavaModelManager 2
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
219
getLocalizedMessage 2
                  
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
6
getMethodDescriptor 2
                  
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
31
getParameterTypes 2
                  
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
60
getParent 2
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
276
getPlugin 2
                  
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown if (JavaCore.getPlugin().isDebugging()) { cfe.printStackTrace(System.err); } return null; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
26
getProject 2
                  
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
124
getTokenEndPosition 2
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition()); }
6
isNaN
2
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Float.valueOf(...) doesn't handle hex decimal floats try { float v = FloatUtil.valueOfHexFloatLiteral(this.source); if (v == Float.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Float.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = FloatConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats try { double v = FloatUtil.valueOfHexDoubleLiteral(this.source); if (v == Double.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Double.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = DoubleConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
2
isTrue 2
                  
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { log(e); // bug in the formatter Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { //JavaPlugin.log(e); // bug in the formatter Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
35
lastSegment 2
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
46
length 2
                  
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
485
logException
2
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
2
logNoClassFileCreated
2
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { logNoClassFileCreated(outputPath, relativeFileName, e); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { this.logger.logNoClassFileCreated(currentDestinationPath, relativeStringName, e); }
2
print 2
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
303
put 2
                  
// in model/org/eclipse/jdt/internal/core/builder/State.java
catch (CloneNotSupportedException e) { this.references = new SimpleLookupTable(lastState.references.elementSize); Object[] keyTable = lastState.references.keyTable; Object[] valueTable = lastState.references.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.references.put(keyTable[i], valueTable[i]); this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize); keyTable = lastState.typeLocators.keyTable; valueTable = lastState.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.typeLocators.put(keyTable[i], valueTable[i]); }
1435
redoMemberAlignment
2
                  
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
2
removeAllIndexEntries 2
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
3
removeProblemsAndTasksFor 2
                  
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
9
scannerError
2
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
2
selectFrom 2
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
7
toCharArray 2
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
1135
verbose_failure
2
                  
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
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); } }
2
ArrayList 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); }
271
BufferedReader 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); }
3
ByteArrayInputStream 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
14
FileOutputStream 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
14
InputStreamReader 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); }
6
Integer 1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
353
NameEnvironmentAnswer 1
                  
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
18
Parser 1
                  
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (AnonymousMemberFound e) { return new Parser(this.problemReporter, true).parse(this.cu, compilationResult); }
48
SimpleSet 1
                  
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch(Exception e) { this.knownPackageNames = new SimpleSet(); // assume for this build the zipFile is empty }
35
acceptResult 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
10
addDependentsOf 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); }
15
addInvalidArchive
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
1
cannotReadSource
1
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(AbortCompilationUnit abortException) { problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); contents = CharOperation.NO_CHAR; // pretend empty from thereon }
1
clear 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // project does not exist: cannot happen since this is the info of the project roots = new IPackageFragmentRoot[0]; reverseMap.clear(); }
54
compile 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { reset(); // a generated type was referenced before it was created // the compiler either created a MissingType or found a BinaryType for it // so add the processor's generated files & start over, // but remember to only pass the generated files to the annotation processor int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits); return; }
18
create 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
98
createError 1
                  
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
2
createMarker 1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
10
defaultClasspath 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
4
defaultJavaExtension 1
                  
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // default to using the outer most declaring type name IType type = this; IType enclosingType = getDeclaringType(); while (enclosingType != null) { type = enclosingType; enclosingType = type.getDeclaringType(); } return type.getElementName() + Util.defaultJavaExtension(); }
11
dumpTab 1
                  
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch(ClassFormatException e) { dumpTab(tabNumber + 2, buffer); buffer.append(Messages.classformat_classformatexception); writeNewLine(buffer, lineSeparator, tabNumber + 1); }
10
findLineSeparator 1
                  
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
4
findRecommendedLineSeparator 1
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
4
flushClasspathProblemMarkers 1
                  
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
4
get 1
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
1255
getCanonicalPath 1
                  
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
8
getCause
1
                  
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
1
getCurrentTokenStartPosition 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
68
getDefaultCharset 1
                  
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch(CoreException ce) { try { return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset(); } catch (CoreException e) { // use no encoding } }
6
getDefinedTypeNamesFor 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
6
getDeltaProcessor 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
14
getFile 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
30
getJavaProject 1
                  
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
145
getMainTypeName 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
16
getRoot 1
                  
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch(CoreException ce) { try { return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset(); } catch (CoreException e) { // use no encoding } }
73
getSource 1
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
21
getStateLocation 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
7
getThrowable
1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
1
getWorkspace 1
                  
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch(CoreException ce) { try { return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset(); } catch (CoreException e) { // use no encoding } }
93
hasJavaNature 1
                  
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
38
isAbsolute 1
                  
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
25
isAccessible 1
                  
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
26
isCanceled 1
                  
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
83
isDebugging 1
                  
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown if (JavaCore.getPlugin().isDebugging()) { cfe.printStackTrace(System.err); } return null; }
2
javadocInvalidReference 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); }
7
javadocInvalidSeeReferenceArgs
1
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
1
javadocInvalidThrowsClass
1
                  
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition()); }
1
javadocUndeclaredParamTagName 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/JavadocSingleNameReference.java
catch (Exception e) { scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, -1); }
4
logIncorrectVMVersionForAnnotationProcessing 1
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(UnsupportedClassVersionError e) { // report a warning this.logger.logIncorrectVMVersionForAnnotationProcessing(); }
2
logWrongJDK
1
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IllegalStateException e) { this.logger.logWrongJDK(); this.proceed = false; return null; }
1
mkdirs 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
3
newDoesNotExistStatus 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { return newDoesNotExistStatus(); }
10
open 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
5
printlnErr 1
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (Exception e) { this.printlnErr(this.main.bind( "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$ }
21
rebuildIndex 1
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // failed to read the existing file or its no longer compatible if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt if (VERBOSE) Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ rebuildIndex(indexLocation, containerPath); return null; } /*index = null;*/ // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate }
5
refreshLocal 1
                  
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
3
removeFileExtension 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
6
reportMatching 1
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
15
resolveWellKnownType 1
                  
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve superclass"); //$NON-NLS-1$ return this.resolver.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ }
3
segment 1
                  
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e){ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName})); }
63
setAttributes 1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
9
setChildren 1
                  
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
12
setLength 1
                  
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
catch (RuntimeException e) { // since debugger sometimes call toString methods, problems can easily happen when // toString is called on an instance that is being initialized buffer.setLength(p); buffer.append("!"); //$NON-NLS-1$ buffer.append(standardToString()); }
73
setSourceAttachmentProperty 1
                  
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
4
sourceName 1
                  
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
170
standardToString
1
                  
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
catch (RuntimeException e) { // since debugger sometimes call toString methods, problems can easily happen when // toString is called on an instance that is being initialized buffer.setLength(p); buffer.append("!"); //$NON-NLS-1$ buffer.append(standardToString()); }
1
superclass 1
                  
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
158
tagAsAccepted 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
9
toFile 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
12
toStringWithAncestors 1
                  
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
41
typeLocator 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
11
valueOfHexDoubleLiteral
1
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats try { double v = FloatUtil.valueOfHexDoubleLiteral(this.source); if (v == Double.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Double.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = DoubleConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
1
valueOfHexFloatLiteral
1
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Float.valueOf(...) doesn't handle hex decimal floats try { float v = FloatUtil.valueOfHexFloatLiteral(this.source); if (v == Float.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Float.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = FloatConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
1
verbose_failed_to_instanciate_container_initializer
1
                  
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e) { // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_container_initializer(containerID, configurationElement); e.printStackTrace(); } }
1
verbose_failed_to_instanciate_variable_initializer
1
                  
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e){ // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_variable_initializer(variable, configElement); e.printStackTrace(); } }
1
wasStructurallyChanged 1
                  
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); }
3
write 1
                  
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
67
writeNewLine 1
                  
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch(ClassFormatException e) { dumpTab(tabNumber + 2, buffer); buffer.append(Messages.classformat_classformatexception); writeNewLine(buffer, lineSeparator, tabNumber + 1); }
297
Method Nbr Nbr total
close 56
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // best effort } } }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathSourceJar.java
finally { if (stream != null) stream.close(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
finally { this.logger.flush(); this.logger.close(); if (this.progress != null) this.progress.done(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
finally { if (stream != null) { try { stream.close(); } catch(IOException e) { // ignore } } }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
finally { if (zip != null) { if (JavaModelManager.ZIP_ACCESS_VERBOSE) System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$ //$NON-NLS-2$ zip.close(); } monitor.exitWrite(); // free write lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); this.streamBuffer = null; BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); this.streamBuffer = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); this.streamBuffer = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { file.close(); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { stream.close(); this.streamBuffer = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
finally { file.close(); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // best effort } } manager.closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { reader.close(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { in.close(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { out.close(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
finally { output.close(); }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
finally { reader.close(); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
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 */ } } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
finally { try { stream.close(); } catch (IOException e) { // ignore } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
finally { try { stream.close(); } catch (IOException e) { // ignore } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
finally { if (in != null) in.close(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
finally { reader.close(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
finally { reader.close(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore problems with close } } }
// in model/org/eclipse/jdt/core/ToolFactory.java
finally { if (in != null) try { in.close(); } catch (IOException e) { // ignore } }
// in model/org/eclipse/jdt/core/ToolFactory.java
finally { if (zipFile != null) { try { zipFile.close(); } catch(IOException e) { // ignore } } }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
finally { try { out.close(); } catch (IOException e) { /* ignore */ } }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { /* ignore */ } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { if (writer != null) { try { writer.close(); } catch (IOException e1) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { try { stream.close(); } catch (IOException e) { // ignore } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { try { stream.close(); } catch (IOException e) { // ignore } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
finally { try { stream.close(); } catch (IOException e) { // ignore } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
finally { output.close(); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
finally { try { input.close(); } catch (IOException e) { // ignore } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { if (writer != null) writer.close(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { if (writer != null) writer.close(); }
124
done 42
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
finally { this.logger.flush(); this.logger.close(); if (this.progress != null) this.progress.done(); }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { requestor.endReporting(); if (monitor != null) monitor.done(); }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { if (progressMonitor != null) { progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { if (progressMonitor != null) { progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { if (progressMonitor != null) { progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { if (progressMonitor != null) { progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { if (subProgress != null) subProgress.done(); }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { if (progress != null) progress.done(); if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
finally { if (progressMonitor != null) progressMonitor.done(); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
finally { if (progressMonitor != null) progressMonitor.done(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
finally { this.currentDelta = null; if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/SetClasspathOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
finally { if (monitor != null) { monitor.done(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { this.notifier.done(); cleanup(); }
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
finally { if (monitor != null) { monitor.done(); } this.progressMonitor = null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
finally { if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
finally { if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
finally { if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
finally { if (monitor != null) monitor.done(); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/SetVariablesOperation.java
finally { done(); }
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
finally { done(); }
// in model/org/eclipse/jdt/core/JavaCore.java
finally { if (subMonitor != null) subMonitor.done(); manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(null); }
// in model/org/eclipse/jdt/core/JavaCore.java
finally { if (monitor != null) monitor.done(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
finally { monitor.done(); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
finally { monitor.done(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); 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 } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); 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 } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); if (monitor != null) monitor.done(); }
46
closeZipFile 13
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { manager.closeZipFile(zipFile); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // best effort } } manager.closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
finally { manager.closeZipFile(zip); // handle null case }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
finally { manager.closeZipFile(zip); // handle null case }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
finally { manager.closeZipFile(zip); // handle null case }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
// in model/org/eclipse/jdt/core/ToolFactory.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
14
cleanUp 12
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
finally { JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null); if (unit != null) { unit.cleanUp(); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
finally { if (compilationUnitDeclaration != null) { compilationUnitDeclaration.cleanUp(); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
finally { cleanUp(); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
finally { cleanUp(); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
finally { if (JavaBuilder.SHOW_STATS) printStats(); cleanUp(); }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
finally { if (this.unitToProcess != null) this.unitToProcess.cleanUp(); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { // cleanup compilation unit result unit.cleanUp(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { // cleanup compilation unit result unit.cleanUp(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { // cleanup compilation unit result unit.cleanUp(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { if (compilationUnitDeclaration != null && ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0)) { compilationUnitDeclaration.cleanUp(); } }
38
getJavaModelManager 11
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
finally { JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null); if (unit != null) { unit.cleanUp(); } }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
finally { JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
// in model/org/eclipse/jdt/core/JavaCore.java
finally { if (!ok) JavaModelManager.getJavaModelManager().variablePut(variableName, null); // flush cache }
// in model/org/eclipse/jdt/core/ToolFactory.java
finally { JavaModelManager.getJavaModelManager().closeZipFile(jar); }
219
reset 11
                  
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
finally { reset(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
finally { reset(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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(); }
// in model/org/eclipse/jdt/internal/compiler/SourceElementNotifier.java
finally { reset(); }
// in model/org/eclipse/jdt/internal/compiler/SourceElementParser.java
finally { this.diet = old; reset(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
finally { reset(true); }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
finally { reset(true); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { if (processingTask != null) { processingTask.shutdown(); processingTask = null; } reset(); this.annotationProcessorStartIndex = 0; this.stats.endTime = System.currentTimeMillis(); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { this.lookupEnvironment.isProcessingAnnotations = false; this.annotationProcessorManager.reset(); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { this.lookupEnvironment.isProcessingAnnotations = false; this.annotationProcessorManager.reset(); }
81
reenableEvents 10
                  
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
finally { reenableEvents(); }
11
cleanup 7
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
finally { if (environment != null) environment.cleanup(); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
finally { if (environment != null) environment.cleanup(); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
finally { if (environment != null) environment.cleanup(); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
finally { if (environment != null) environment.cleanup(); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { this.notifier.done(); cleanup(); }
15
exitRead
6
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/AddFolderToIndex.java
finally { monitor.exitRead(); // free read lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
finally { monitor.exitRead(); // free read lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { monitor.exitRead(); }
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFolderFromIndex.java
finally { monitor.exitRead(); // free read lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
finally { if (monitor != null) monitor.exitRead(); // free read lock }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
finally { monitor.exitRead(); // finished reading }
6
endReporting 5
                  
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { requestor.endReporting(); if (monitor != null) monitor.done(); }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { requestor.endReporting(); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
finally { problemRequestor.endReporting(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
finally { perWorkingCopyInfo.endReporting(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
8
flushZipFiles 5
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
finally { manager.flushZipFiles(this); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
finally { javaModelManager.flushZipFiles(this); // clean up cached zip files. }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
finally { manager.flushZipFiles(this); }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
finally { manager.flushZipFiles(this); }
6
set 5
                  
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
finally { JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null); if (unit != null) { unit.cleanUp(); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
finally { JavaModelManager.getJavaModelManager().abortOnMissingSource.set(null); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ? if (event.getType() == IResourceChangeEvent.POST_CHANGE) { this.deltaProcessors.set(null); } else { // If we are going to reuse the delta processor of this thread, don't hang on to state // that isn't meant to be reused. https://bugs.eclipse.org/bugs/show_bug.cgi?id=273385 getDeltaProcessor().overridenEventType = -1; } }
// in model/org/eclipse/jdt/core/JavaCore.java
finally { if (subMonitor != null) subMonitor.done(); manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(null); }
97
currentTimeMillis 4
                  
// in search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
finally { if (BasicSearchEngine.VERBOSE) { long time = System.currentTimeMillis() - start; int length = result == null ? 0 : result.length; Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: "+length+" paths computed in "+time+"ms."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
finally { if (VERBOSE) this.timeSpentInSeekTypesInBinaryPackage += System.currentTimeMillis()-start; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
finally { if (VERBOSE) this.timeSpentInSeekTypesInSourcePackage += System.currentTimeMillis()-start; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { if (processingTask != null) { processingTask.shutdown(); processingTask = null; } reset(); this.annotationProcessorStartIndex = 0; this.stats.endTime = System.currentTimeMillis(); }
65
exitWrite 4
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java
finally { monitor.exitWrite(); // free write lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/SaveIndex.java
finally { monitor.exitWrite(); // free write lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
finally { if (zip != null) { if (JavaModelManager.ZIP_ACCESS_VERBOSE) System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$ //$NON-NLS-2$ zip.close(); } monitor.exitWrite(); // free write lock }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { monitor.exitWrite(); // free write lock }
5
initializeDefaults 4
                  
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); if (monitor != null) monitor.done(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); }
5
resetTo 4
                  
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
finally { // reset the scanner this.scanner.resetTo(end, this.scannerEndPosition - 1); this.needSpace = false; this.indentationLevel = lastIndentationLevel; this.lastNumberOfNewLines = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
finally { this.scanner.recordLineSeparator = false; this.needSpace = false; this.scanner.resetTo(textEndPosition+1, this.scannerEndPosition - 1); this.lastNumberOfNewLines += newLines; this.line += newLines; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
finally { // Reset this.needSpace = false; this.scanner.tokenizeWhiteSpace = true; this.scanner.resetTo(text.sourceEnd+1, this.scannerEndPosition - 1); }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
finally { if (valid) { if (closing) { this.htmlTagsPtr--; } } else if (!this.abort) { if (incremented) { this.htmlTagsPtr--; if (this.htmlTagsPtr == -1) this.htmlTags = null; } this.scanner.resetTo(start, this.scanner.eofPosition-1); this.index = start; } }
178
setMonitor 4
                  
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); 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 } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
finally { if (monitor != null) monitor.done(); 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 } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
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 } }
6
String 3
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
1987
size 3
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
finally { this.resultElements = new IJavaElement[this.createdElements.size()]; this.createdElements.toArray(this.resultElements); processDeltas(); }
433
stopQuery 3
                  
// in search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
finally { index.stopQuery(); }
// in search/org/eclipse/jdt/internal/core/search/matching/IntersectingPattern.java
finally { index.stopQuery(); }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
finally { index.stopQuery(); }
5
verbose 3
                  
// in search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
finally { if (BasicSearchEngine.VERBOSE) { long time = System.currentTimeMillis() - start; int length = result == null ? 0 : result.length; Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: "+length+" paths computed in "+time+"ms."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { if (progress != null) progress.done(); if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { this.executing = false; if (VERBOSE) Util.verbose("FINISHED background job - " + job); //$NON-NLS-1$ moveToNextJob(); if (this.awaitingClients == 0) Thread.sleep(50); }
169
enable
2
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { enable(); }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { enable(); }
2
exitWriteEnterRead
2
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { monitor.exitWriteEnterRead(); }
// in search/org/eclipse/jdt/internal/core/index/Index.java
finally { this.monitor.exitWriteEnterRead(); }
2
getDeltaProcessor 2
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ? if (event.getType() == IResourceChangeEvent.POST_CHANGE) { this.deltaProcessors.set(null); } else { // If we are going to reuse the delta processor of this thread, don't hang on to state // that isn't meant to be reused. https://bugs.eclipse.org/bugs/show_bug.cgi?id=273385 getDeltaProcessor().overridenEventType = -1; } }
14
isTopLevelOperation 2
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { if (isTopLevelOperation()) { runPostActions(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
3
length 2
                  
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
finally { this.scanner.skipComments = false; // Add remaining buffered tokens if (this.javadocTokensBuffer.length() > 0) { buffer.append(this.javadocTokensBuffer); this.column += this.javadocTokensBuffer.length(); } }
485
println 2
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
finally { if (zip != null) { if (JavaModelManager.ZIP_ACCESS_VERBOSE) System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$ //$NON-NLS-2$ zip.close(); } monitor.exitWrite(); // free write lock }
855
valueOf 2
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
337
worked 2
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
finally { worked(1); }
49
HashSet 1
                  
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
finally { this.projectsToUpdate = new HashSet(); }
103
InternalCompletionContext 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
5
acceptContext 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
6
add 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
954
addDefaultAbstractMethods 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/lookup/SourceTypeBinding.java
finally { if (failed > 0) { int newSize = resolvedMethods.length - failed; if (newSize == 0) { this.methods = Binding.NO_METHODS; } else { MethodBinding[] newMethods = new MethodBinding[newSize]; for (int i = 0, j = 0, length = resolvedMethods.length; i < length; i++) if (resolvedMethods[i] != null) newMethods[j++] = resolvedMethods[i]; this.methods = newMethods; } } // handle forward references to potential default abstract methods addDefaultAbstractMethods(); this.tagBits |= TagBits.AreMethodsComplete; }
3
append 1
                  
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
finally { this.scanner.skipComments = false; // Add remaining buffered tokens if (this.javadocTokensBuffer.length() > 0) { buffer.append(this.javadocTokensBuffer); this.column += this.javadocTokensBuffer.length(); } }
5000
batchInitializationFinished
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { batchInitializationFinished(); }
1
bind 1
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
471
breakpoint 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
finally { if (!isClasspathBeingResolved) { manager.setClasspathBeingResolved(this, false); } if (CP_RESOLUTION_BP_LISTENERS != null) breakpoint(3, this); }
4
buildFinished 1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); }
2
clearLastState 1
                  
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); }
4
constant 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/FieldDeclaration.java
finally { initializationScope.initializedField = previousField; initializationScope.lastVisibleFieldID = previousFieldID; if (this.binding.constant() == null) this.binding.setConstant(Constant.NotAConstant); }
277
containerPut 1
                  
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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 } } }
13
containerRemoveInitializationInProgress 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
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); } }
2
currentThread 1
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
finally { if (zip != null) { if (JavaModelManager.ZIP_ACCESS_VERBOSE) System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$ //$NON-NLS-2$ zip.close(); } monitor.exitWrite(); // free write lock }
50
doneSearching 1
                  
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { requestor.exitParticipant(participant); participant.doneSearching(); }
2
endLoggingSources
1
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
finally { this.logger.endLoggingSources(); }
1
endRun 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
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); } }
5
equals 1
                  
// in model/org/eclipse/jdt/internal/core/VerboseElementCache.java
finally { if (key.equals(this.beingAdded)) this.beingAdded = null; }
1920
exitParticipant
1
                  
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
finally { requestor.exitParticipant(participant); participant.doneSearching(); }
1
finished 1
                  
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
finally { job.finished(); }
2
fire 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
3
flush 1
                  
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
finally { this.logger.flush(); this.logger.close(); if (this.progress != null) this.progress.done(); }
35
get 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
1255
getElementType 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
154
getFileName 1
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); }
54
getJarFile
1
                  
// in model/org/eclipse/jdt/internal/core/JavaElement.java
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 */ } } }
1
getJavaProject 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
145
getOpenable 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
5
getParent 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
276
getRoot 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (xmlString != null){ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one } }
73
getSimilarMatch 1
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); }
5
getType 1
                  
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ? if (event.getType() == IResourceChangeEvent.POST_CHANGE) { this.deltaProcessors.set(null); } else { // If we are going to reuse the delta processor of this thread, don't hang on to state // that isn't meant to be reused. https://bugs.eclipse.org/bugs/show_bug.cgi?id=273385 getDeltaProcessor().overridenEventType = -1; } }
356
getWorkspace 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (xmlString != null){ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one } }
93
hasModifiedResource
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
1
hasSimilarMatch
1
                  
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); }
1
isAlive
1
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { synchronized(this) { this.awaitingClients--; } if (t != null && originalPriority > -1 && t.isAlive()) t.setPriority(originalPriority); }
1
isEmpty 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
71
isExtendedContextRequired 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
6
isWorkingCopy 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
33
moveToNextJob 1
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { this.executing = false; if (VERBOSE) Util.verbose("FINISHED background job - " + job); //$NON-NLS-1$ moveToNextJob(); if (this.awaitingClients == 0) Thread.sleep(50); }
2
popDeclaringType
1
                  
// in model/org/eclipse/jdt/internal/compiler/SourceElementNotifier.java
finally { this.localDeclarationVisitor.popDeclaringType(); }
1
popOperation
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { popOperation(); }
1
printStats 1
                  
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
finally { if (JavaBuilder.SHOW_STATS) printStats(); cleanUp(); }
2
processDeltas
1
                  
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
finally { this.resultElements = new IJavaElement[this.createdElements.size()]; this.createdElements.toArray(this.resultElements); processDeltas(); }
1
releaseCursor
1
                  
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
finally { children.releaseCursor(cursor); }
1
remove 1
                  
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
finally { if (addedCurrentThread) { this.initializingThreads.remove(currentThread); } }
157
resetOldJavaProjectNames
1
                  
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
finally { // workaround for bug 15168 circular errors not reported this.state.resetOldJavaProjectNames(); this.oldRoots = null; }
1
resetProjectCaches 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
2
resetTemporaryCache
1
                  
// in model/org/eclipse/jdt/internal/core/JavaElement.java
finally { if (!hadTemporaryCache) { manager.resetTemporaryCache(); } }
1
runPostActions
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { if (isTopLevelOperation()) { runPostActions(); } }
1
setClasspathBeingResolved 1
                  
// in model/org/eclipse/jdt/internal/core/JavaProject.java
finally { if (!isClasspathBeingResolved) { manager.setClasspathBeingResolved(this, false); } if (CP_RESOLUTION_BP_LISTENERS != null) breakpoint(3, this); }
2
setConstant 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/ast/FieldDeclaration.java
finally { initializationScope.initializedField = previousField; initializationScope.lastVisibleFieldID = previousFieldID; if (this.binding.constant() == null) this.binding.setConstant(Constant.NotAConstant); }
20
setContents 1
                  
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
finally { if (!hasSaved){ // restore original buffer contents since something went wrong primaryBuffer.setContents(primaryContents); } }
20
setExtended 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
4
setIndex 1
                  
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
finally { searchDocument.setIndex(null); }
5
setOffset 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
20
setOptions 1
                  
// in model/org/eclipse/jdt/core/CorrectionEngine.java
finally { JavaCore.setOptions(oldOptions); }
3
setPersistentProperty 1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
finally { if (xmlString != null){ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one } }
3
setPriority 1
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { synchronized(this) { this.awaitingClients--; } if (t != null && originalPriority > -1 && t.isAlive()) t.setPriority(originalPriority); }
5
setReadOnly 1
                  
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
finally { Util.setReadOnly(destFile, wasReadOnly); }
11
setTokenKind 1
                  
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
finally { if(!contextAccepted) { contextAccepted = true; InternalCompletionContext context = new InternalCompletionContext(); context.setTokenKind(CompletionContext.TOKEN_KIND_UNKNOWN); context.setOffset(completionPosition - this.offset); if (this.requestor.isExtendedContextRequired()) context.setExtended(); this.requestor.acceptContext(context); } this.requestor.endReporting(); if (this.monitor != null) this.monitor.done(); reset(); }
4
shutdown 1
                  
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
finally { if (processingTask != null) { processingTask.shutdown(); processingTask = null; } reset(); this.annotationProcessorStartIndex = 0; this.stats.endTime = System.currentTimeMillis(); }
7
sleep 1
                  
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
finally { this.executing = false; if (VERBOSE) Util.verbose("FINISHED background job - " + job); //$NON-NLS-1$ moveToNextJob(); if (this.awaitingClients == 0) Thread.sleep(50); }
8
startDeltas
1
                  
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
finally { this.sourceElementParserCache = null; // don't hold onto parser longer than necessary startDeltas(); }
1
stop
1
                  
// in model/org/eclipse/jdt/core/JavaCore.java
finally { // ensure we call super.stop as the last thing super.stop(context); }
1
toArray 1
                  
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
finally { this.resultElements = new IJavaElement[this.createdElements.size()]; this.createdElements.toArray(this.resultElements); processDeltas(); }
155
updateJavaModel
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } }
1
variablePut 1
                  
// in model/org/eclipse/jdt/core/JavaCore.java
finally { if (!ok) JavaModelManager.getJavaModelManager().variablePut(variableName, null); // flush cache }
5
verbose_container_initialization_failed
1
                  
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
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); } }
1

Reference Table

This table concatenates the results of the previous tables.

Checked/Runtime Type Exception Thrown Thrown from Catch Declared Caught directly Caught
with Thrown
Caught
with Thrown Runtime
unknown (Lib) . 0 0 0 0 0 0
runtime (Domain) AbortCompilation
public class AbortCompilation extends RuntimeException {

	public CompilationResult compilationResult;
	public Throwable exception;
	public CategorizedProblem problem;

	/* special fields used to abort silently (e.g. when canceling build process) */
	public boolean isSilent;
	public RuntimeException silentException;

	private static final long serialVersionUID = -2047226595083244852L; // backward compatible

	public AbortCompilation() {
		// empty
	}

	public AbortCompilation(CompilationResult compilationResult, CategorizedProblem problem) {
		this();
		this.compilationResult = compilationResult;
		this.problem = problem;
	}

	public AbortCompilation(CompilationResult compilationResult, Throwable exception) {
		this();
		this.compilationResult = compilationResult;
		this.exception = exception;
	}

	public AbortCompilation(boolean isSilent, RuntimeException silentException) {
		this();
		this.isSilent = isSilent;
		this.silentException = silentException;
	}
	public String getMessage() {
		String message = super.getMessage();
		StringBuffer buffer = new StringBuffer(message == null ? Util.EMPTY_STRING : message);
		if (this.problem != null) {
			buffer.append(this.problem);
		} else if (this.exception != null) {
			message = this.exception.getMessage();
			buffer.append(message == null ? Util.EMPTY_STRING : message);
		} else if (this.silentException != null) {
			message = this.silentException.getMessage();
			buffer.append(message == null ? Util.EMPTY_STRING : message);
		}
		return String.valueOf(buffer);
	}
	public void updateContext(InvocationSite invocationSite, CompilationResult unitResult) {
		if (this.problem == null) return;
		if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
		this.problem.setSourceStart(invocationSite.sourceStart());
		this.problem.setSourceEnd(invocationSite.sourceEnd());
		int[] lineEnds = unitResult.getLineSeparatorPositions();
		this.problem.setSourceLineNumber(Util.getLineNumber(invocationSite.sourceStart(), lineEnds, 0, lineEnds.length-1));
		this.compilationResult = unitResult;
	}

	public void updateContext(ASTNode astNode, CompilationResult unitResult) {
		if (this.problem == null) return;
		if (this.problem.getSourceStart() != 0 || this.problem.getSourceEnd() != 0) return;
		this.problem.setSourceStart(astNode.sourceStart());
		this.problem.setSourceEnd(astNode.sourceEnd());
		int[] lineEnds = unitResult.getLineSeparatorPositions();
		this.problem.setSourceLineNumber(Util.getLineNumber(astNode.sourceStart(), lineEnds, 0, lineEnds.length-1));
		this.compilationResult = unitResult;
	}

	public String getKey() {
		StringBuffer buffer = new StringBuffer();
		if (this.problem != null) {
			buffer.append(this.problem);
		}
		return String.valueOf(buffer);
	}
}
15
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void initializeAnnotationProcessorManager() { try { Class c = Class.forName("org.eclipse.jdt.internal.compiler.apt.dispatch.BatchAnnotationProcessorManager"); //$NON-NLS-1$ AbstractAnnotationProcessorManager annotationManager = (AbstractAnnotationProcessorManager) c.newInstance(); annotationManager.configure(this, this.expandedCommandLine); annotationManager.setErr(this.err); annotationManager.setOut(this.out); this.batchCompiler.annotationProcessorManager = annotationManager; } catch (ClassNotFoundException e) { // ignore } catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); } catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); } catch(UnsupportedClassVersionError e) { // report a warning this.logger.logIncorrectVMVersionForAnnotationProcessing(); } }
// in model/org/eclipse/jdt/internal/core/CancelableProblemFactory.java
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { if (this.monitor != null && this.monitor.isCanceled()) throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); return super.createProblem(originatingFileName, problemId, problemArguments, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber); }
// in model/org/eclipse/jdt/internal/core/CancelableProblemFactory.java
public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { if (this.monitor != null && this.monitor.isCanceled()) throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); return super.createProblem(originatingFileName, problemId, problemArguments, elaborationId, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) { if (this.notifier != null) this.notifier.checkCancelWithinCompiler(); if (this.initialTypeNames != null && this.initialTypeNames.includes(qualifiedTypeName)) { if (this.isIncrementalBuild) // catch the case that a type inside a source file has been renamed but other class files are looking for it throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedTypeName)); return null; // looking for a file which we know was provided at the beginning of the compilation } if (this.additionalUnits != null && this.sourceLocations.length > 0) { // if an additional source file is waiting to be compiled, answer it BUT not if this is a secondary type search // if we answer X.java & it no longer defines Y then the binary type looking for Y will think the class path is wrong // let the recompile loop fix up dependents when the secondary type Y has been deleted from X.java SourceFile unit = (SourceFile) this.additionalUnits.get(qualifiedTypeName); // doesn't have file extension if (unit != null) return new NameEnvironmentAnswer(unit, null /*no access restriction*/); } String qBinaryFileName = qualifiedTypeName + SUFFIX_STRING_class; String binaryFileName = qBinaryFileName; String qPackageName = ""; //$NON-NLS-1$ if (qualifiedTypeName.length() > typeName.length) { int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class" qPackageName = qBinaryFileName.substring(0, typeNameStart - 1); binaryFileName = qBinaryFileName.substring(typeNameStart); } // NOTE: the output folders are added at the beginning of the binaryLocations NameEnvironmentAnswer suggestedAnswer = null; for (int i = 0, l = this.binaryLocations.length; i < l; i++) { NameEnvironmentAnswer answer = this.binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName); if (answer != null) { if (!answer.ignoreIfBetter()) { if (answer.isBetter(suggestedAnswer)) return answer; } else if (answer.isBetter(suggestedAnswer)) // remember suggestion and keep looking suggestedAnswer = answer; } } if (suggestedAnswer != null) // no better answer was found return suggestedAnswer; return null; }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
public char[] getContents() { try { return Util.getResourceContentsAsCharArray(this.resource); } catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void writeClassFileContents(ClassFile classfile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // Before writing out the class file, compare it to the previous file // If structural changes occurred then add dependent source files byte[] bytes = classfile.getBytes(); if (file.exists()) { if (writeClassFileCheck(file, qualifiedFileName, bytes) || compilationUnit.updateClassFile) { // see 46093 if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(new ByteArrayInputStream(bytes), true, false, null); } else if (JavaBuilder.DEBUG) { System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$ } } else { if (isTopLevelType) addDependentsOf(new Path(qualifiedFileName), true); // new type if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow } } }
// in model/org/eclipse/jdt/internal/core/builder/BuildNotifier.java
public void checkCancelWithinCompiler() { if (this.monitor != null && this.monitor.isCanceled() && !this.cancelling) { // Once the compiler has been canceled, don't check again. setCancelling(true); // Only AbortCompilation can stop the compiler cleanly. // We check cancelation again following the call to compile. throw new AbortCompilation(true, null); } }
// in model/org/eclipse/jdt/internal/core/CancelableNameEnvironment.java
private void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) { if (NameLookup.VERBOSE) System.out.println(Thread.currentThread() + " CANCELLING LOOKUP "); //$NON-NLS-1$ throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); } }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemHandler.java
public void handle( int problemId, String[] problemArguments, int elaborationId, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) { if (severity == ProblemSeverities.Ignore) return; // if no reference context, we need to abort from the current compilation process if (referenceContext == null) { if ((severity & ProblemSeverities.Error) != 0) { // non reportable error is fatal CategorizedProblem problem = this.createProblem(null, problemId, problemArguments, elaborationId, messageArguments, severity, 0, 0, 0, 0); throw new AbortCompilation(null, problem); } else { return; // ignore non reportable warning } } int[] lineEnds; int lineNumber = problemStartPosition >= 0 ? Util.getLineNumber(problemStartPosition, lineEnds = unitResult.getLineSeparatorPositions(), 0, lineEnds.length-1) : 0; int columnNumber = problemStartPosition >= 0 ? Util.searchColumnNumber(unitResult.getLineSeparatorPositions(), lineNumber, problemStartPosition) : 0; CategorizedProblem problem = this.createProblem( unitResult.getFileName(), problemId, problemArguments, elaborationId, messageArguments, severity, problemStartPosition, problemEndPosition, lineNumber, columnNumber); if (problem == null) return; // problem couldn't be created, ignore switch (severity & ProblemSeverities.Error) { case ProblemSeverities.Error : record(problem, unitResult, referenceContext); if ((severity & ProblemSeverities.Fatal) != 0) { referenceContext.tagAsHavingErrors(); // should abort ? int abortLevel; if ((abortLevel = this.policy.stopOnFirstError() ? ProblemSeverities.AbortCompilation : severity & ProblemSeverities.Abort) != 0) { referenceContext.abort(abortLevel, problem); } } break; case ProblemSeverities.Warning : record(problem, unitResult, referenceContext); break; } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
protected void reportProgress(String taskDecription) { if (this.progress != null) { if (this.progress.isCanceled()) { // Only AbortCompilation can stop the compiler cleanly. // We check cancellation again following the call to compile. throw new AbortCompilation(true, null); } this.progress.setTaskName(taskDecription); } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
protected void reportWorked(int workIncrement, int currentUnitIndex) { if (this.progress != null) { if (this.progress.isCanceled()) { // Only AbortCompilation can stop the compiler cleanly. // We check cancellation again following the call to compile. throw new AbortCompilation(true, null); } this.progress.worked(workIncrement, (this.totalUnits* this.remainingIterations) - currentUnitIndex - 1); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
// in dom/org/eclipse/jdt/core/dom/NameEnvironmentWithProgress.java
private void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) { if (NameLookup.VERBOSE) { System.out.println(Thread.currentThread() + " CANCELLING LOOKUP "); //$NON-NLS-1$ } throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); } }
4
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
0 81
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (AbortCompilation e) { // problem with classpath: report inacurrate matches return null; }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (AbortCompilation e) { // ignore: continue with next element }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (AbortCompilation ignored) { // ignore the AbortCompilcation coming from BuildNotifier.checkCancelWithinCompiler() // the Compiler failed after the user has chose to cancel... likely due to an OutOfMemory error }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // missing 'java.lang' package: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); this.hasMissingSuperClass = true; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // allow subsequent call to superInterfaces() to succeed so that we don't have to catch AbortCompilation everywhere ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperinterfaces; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) hasLocalType[i] = false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // skip it silently }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if (TypeHierarchy.DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (AbortCompilation e) { // unresolved superclass/superinterface -> ignore }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (AbortCompilation e) { problemFinder.handleInternalException(e, unit); }
// in model/org/eclipse/jdt/internal/compiler/SourceElementParser.java
catch (AbortCompilation e) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in model/org/eclipse/jdt/internal/compiler/DocumentElementParser.java
catch (AbortCompilation ex) { // ignore this exception }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistParser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch (AbortCompilation e) { assignableTypeBinding = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch(AbortCompilation e) { // log the exception and proceed Util.logRepeatedMessage(e.getKey(), e); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (AbortCompilation ex) { this.lastAct = ERROR_ACTION; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
catch (AbortCompilation a){ // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
catch (AbortCompilation a){ // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (AbortCompilation e) { this.handleInternalException(e, unit); return unit == null ? this.unitsToProcess[0] : unit; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // handle missing types }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch(AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
catch (AbortCompilation e) { // ignore missing types }
// in dom/org/eclipse/jdt/core/dom/MethodBinding.java
catch (AbortCompilation e) { // don't surface internal exception to clients // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=143013 return false; }
10
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/LookupEnvironment.java
catch (AbortCompilation abort) { if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME)) return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver) throw abort; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { e.updateContext(this.referenceContext, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java
catch (AbortCompilation e) { SourceTypeBinding sourceType = this.referenceContext.binding; if (sourceType.superInterfaces == null) sourceType.superInterfaces = Binding.NO_SUPERINTERFACES; // be more resilient for hierarchies (144976) e.updateContext(typeReference, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/Scope.java
catch (AbortCompilation e) { e.updateContext(invocationSite, referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/QualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ArrayQualifiedTypeReference.java
catch (AbortCompilation e) { e.updateContext(this, scope.referenceCompilationUnit().compilationResult); throw e; }
0
runtime (Domain) AbortCompilationUnit
public class AbortCompilationUnit extends AbortCompilation {

	private static final long serialVersionUID = -4253893529982226734L; // backward compatible

	public String encoding;

public AbortCompilationUnit(CompilationResult compilationResult, CategorizedProblem problem) {
	super(compilationResult, problem);
}

/**
 * Used to surface encoding issues when reading sources
 */
public AbortCompilationUnit(CompilationResult compilationResult, IOException exception, String encoding) {
	super(compilationResult, exception);
	this.encoding = encoding;
}
}
6
            
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
public char[] getContents() { if (this.contents != null) return this.contents; // answer the cached source // otherwise retrieve it try { return Util.getFileCharContent(new File(new String(this.fileName)), this.encoding); } catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); } }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
public char[] getContents() { IBuffer buffer = getBufferManager().getBuffer(this); if (buffer == null) { // no need to force opening of CU to get the content // also this cannot be a working copy, as its buffer is never closed while the working copy is alive IFile file = (IFile) getResource(); // Get encoding from file String encoding; try { encoding = file.getCharset(); } catch(CoreException ce) { // do not use any encoding encoding = null; } try { return Util.getResourceContentsAsCharArray(file, encoding); } catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; } } char[] contents = buffer.getCharacters(); if (contents == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814 if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = new IOException(Messages.buffer_closed); IFile file = (IFile) getResource(); // Get encoding from file String encoding; try { encoding = file.getCharset(); } catch(CoreException ce) { // do not use any encoding encoding = null; } throw new AbortCompilationUnit(null, ioException, encoding); } return CharOperation.NO_CHAR; } return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
0 7
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(AbortCompilationUnit abortException) { problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); contents = CharOperation.NO_CHAR; // pretend empty from thereon }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
catch (AbortCompilationUnit e) { // ignore }
2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once //requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (AbortCompilationUnit e) { // at this point, currentCompilationUnitResult may not be sourceUnit, but some other // one requested further along to resolve sourceUnit. if (unitResult.compilationUnit == sourceUnit) { // only report once this.requestor.acceptResult(unitResult.tagAsAccepted()); } else { throw e; // want to abort enclosing request to compile } }
0
runtime (Domain) AbortFormatting
public class AbortFormatting extends RuntimeException {

	Throwable nestedException;
	private static final long serialVersionUID = -5796507276311428526L; // backward compatible

	public AbortFormatting(String message) {
		super(message);
	}
	public AbortFormatting(Throwable nestedException) {
		super(nestedException.getMessage());
		this.nestedException = nestedException;
	}
}
11
            
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void exitAlignment(Alignment alignment, boolean discardAlignment){ Alignment current = this.currentAlignment; while (current != null){ if (current == alignment) break; current = current.enclosing; } if (current == null) { throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ } this.indentationLevel = alignment.location.outputIndentationLevel; this.numberOfIndentations = alignment.location.numberOfIndentations; this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart; if (discardAlignment){ this.currentAlignment = alignment.enclosing; if (this.currentAlignment == null) { this.formatter.lastBinaryExpressionAlignmentBreakIndentation = 0; } } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void exitMemberAlignment(Alignment alignment){ Alignment current = this.memberAlignment; while (current != null){ if (current == alignment) break; current = current.enclosing; } if (current == null) { throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ } this.indentationLevel = current.location.outputIndentationLevel; this.numberOfIndentations = current.location.numberOfIndentations; this.formatter.lastLocalDeclarationSourceStart = alignment.location.lastLocalDeclarationSourceStart; this.memberAlignment = current.enclosing; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printEndOfCompilationUnit() { try { // if we have a space between two tokens we ensure it will be dumped in the formatted string int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasLineComment = false; boolean hasWhitespace = false; int count = 0; while (true) { this.currentToken = this.scanner.getNextToken(); switch(this.currentToken) { case TerminalTokens.TokenNameWHITESPACE : char[] whiteSpaces = this.scanner.getCurrentTokenSource(); count = 0; for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } count++; break; case '\n' : count++; } } if (count == 0) { hasWhitespace = true; addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else if (hasLineComment) { preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition()); addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else if (hasComment) { if (count == 1) { this.printNewLine(this.scanner.getCurrentTokenStartPosition()); } else { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } else { addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } else if (count == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespace) { space(); } hasWhitespace = false; printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = true; count = 0; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); } else if (count == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespace) { space(); } hasWhitespace = false; printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; count = 0; break; case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (count >= 1) { if (count > 1) { preserveEmptyLines(count - 1, this.scanner.startPosition); } else if (count == 1) { printNewLine(this.scanner.startPosition); } } else if (hasWhitespace) { space(); } hasWhitespace = false; if (includesJavadocComments()) { printJavadocComment(this.scanner.startPosition, this.scanner.currentPosition); } else { printBlockComment(true); } printNewLine(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; count = 0; break; case TerminalTokens.TokenNameSEMICOLON : print(this.scanner.currentPosition - this.scanner.startPosition, this.formatter.preferences.insert_space_before_semicolon); break; case TerminalTokens.TokenNameEOF : if (count >= 1 || this.formatter.preferences.insert_new_line_at_end_of_file_if_missing) { this.printNewLine(this.scannerEndPosition); } return; default : // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
void printComment(int kind, int trailing, int emptyLinesRules) { final boolean rejectLineComment = kind == CodeFormatter.K_MULTI_LINE_COMMENT || kind == CodeFormatter.K_JAVA_DOC; final boolean rejectBlockComment = kind == CodeFormatter.K_SINGLE_LINE_COMMENT || kind == CodeFormatter.K_JAVA_DOC; final boolean rejectJavadocComment = kind == CodeFormatter.K_SINGLE_LINE_COMMENT || kind == CodeFormatter.K_MULTI_LINE_COMMENT; try { // if we have a space between two tokens we ensure it will be dumped in the formatted string int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasLineComment = false; boolean hasWhitespaces = false; int lines = 0; while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { int foundTaskCount = this.scanner.foundTaskCount; int tokenStartPosition = this.scanner.getCurrentTokenStartPosition(); switch(this.currentToken) { case TerminalTokens.TokenNameWHITESPACE : char[] whiteSpaces = this.scanner.getCurrentTokenSource(); int whitespacesEndPosition = this.scanner.getCurrentTokenEndPosition(); lines = 0; for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } lines++; break; case '\n' : lines++; } } // If following token is a line comment on the same line or the line just after, // then it might be not really formatted as a trailing comment boolean realTrailing = trailing > NO_TRAILING_COMMENT; if (realTrailing && this.scanner.currentCharacter == '/' && (lines == 0 || (lines == 1 && !hasLineComment && trailing == IMPORT_TRAILING_COMMENT))) { // sometimes changing the trailing may not be the best idea // for complex trailing comment, it's basically a good idea boolean canChangeTrailing = (trailing & COMPLEX_TRAILING_COMMENT) != 0; // for basic trailing comment preceded by a line comment, then it depends on the comments relative position // when following comment column (after having been rounded) is below the preceding one, // then it becomes not a good idea to change the trailing flag if (trailing == BASIC_TRAILING_COMMENT && hasLineComment) { int currentCommentIndentation = getCurrentIndentation(whiteSpaces, 0); int relativeIndentation = currentCommentIndentation - this.lastLineComment.currentIndentation; if (this.tabLength == 0) { canChangeTrailing = relativeIndentation == 0; } else { canChangeTrailing = relativeIndentation > -this.tabLength; } } // if the trailing can be change, then look at the following tokens if (canChangeTrailing) { int currentPosition = this.scanner.currentPosition; if (this.scanner.getNextToken() == TerminalTokens.TokenNameCOMMENT_LINE) { realTrailing = !hasLineComment; switch (this.scanner.getNextToken()) { case TerminalTokens.TokenNameCOMMENT_LINE: // at least two contiguous line comments // the formatter should not consider comments as trailing ones realTrailing = false; break; case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.getNextToken() == TerminalTokens.TokenNameCOMMENT_LINE) { // at least two contiguous line comments // the formatter should not consider comments as trailing ones realTrailing = false; } break; } } this.scanner.resetTo(currentPosition, this.scanner.eofPosition - 1); } } // Look whether comments line may be contiguous or not // Note that when preceding token is a comment line, then only one line // is enough to have an empty line as the line end is included in the comment line... // If comments are contiguous, store the white spaces to be able to compute the current comment indentation if (lines > 1 || (lines == 1 && hasLineComment)) { this.lastLineComment.contiguous = false; } this.lastLineComment.leadingSpaces = whiteSpaces; this.lastLineComment.lines = lines; // Strategy to consume spaces and eventually leave at this stage // depends on the fact that a trailing comment is expected or not if (realTrailing) { // if a line comment is consumed, no other comment can be on the same line after if (hasLineComment) { if (lines >= 1) { currentTokenStartPosition = tokenStartPosition; preserveEmptyLines(lines, currentTokenStartPosition); addDeleteEdit(currentTokenStartPosition, whitespacesEndPosition); this.scanner.resetTo(this.scanner.currentPosition, this.scannerEndPosition - 1); return; } this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } // if one or several new lines are consumed, following comments cannot be considered as trailing ones if (lines >= 1) { if (hasComment) { this.printNewLine(tokenStartPosition); } this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } // delete consumed white spaces hasWhitespaces = true; currentTokenStartPosition = this.scanner.currentPosition; addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } else { if (lines == 0) { hasWhitespaces = true; if (hasLineComment && emptyLinesRules != PRESERVE_EMPTY_LINES_KEEP_LAST_NEW_LINES_INDENTATION) { addReplaceEdit(tokenStartPosition, whitespacesEndPosition, getPreserveEmptyLines(0, emptyLinesRules)); } else { addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } } else if (hasLineComment) { useAlignmentBreakIndentation(emptyLinesRules); currentTokenStartPosition = tokenStartPosition; preserveEmptyLines(lines, currentTokenStartPosition); addDeleteEdit(currentTokenStartPosition, whitespacesEndPosition); } else if (hasComment) { useAlignmentBreakIndentation(emptyLinesRules); if (lines == 1) { this.printNewLine(tokenStartPosition); } else { preserveEmptyLines(lines - 1, tokenStartPosition); } addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } else if (lines != 0 && (!this.formatter.preferences.join_wrapped_lines || this.formatter.preferences.number_of_empty_lines_to_preserve != 0 || this.blank_lines_between_import_groups > 0)) { addReplaceEdit(tokenStartPosition, whitespacesEndPosition, getPreserveEmptyLines(lines-1, emptyLinesRules)); } else { useAlignmentBreakIndentation(emptyLinesRules); addDeleteEdit(tokenStartPosition, whitespacesEndPosition); } } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.fragmentEquals(this.disablingTag, this.scanner.source, tokenStartPosition, true)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } if (rejectLineComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = true; lines = 0; if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.fragmentEquals(this.enablingTag, this.scanner.source, tokenStartPosition, true); } } break; case TerminalTokens.TokenNameCOMMENT_BLOCK : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.fragmentEquals(this.disablingTag, this.scanner.source, tokenStartPosition, true)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } if (trailing > NO_TRAILING_COMMENT && lines >= 1) { // a block comment on next line means that there's no trailing comment this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); return; } this.lastLineComment.contiguous = false; if (rejectBlockComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; lines = 0; if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.fragmentEquals(this.enablingTag, this.scanner.source, tokenStartPosition, true); } } break; case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (this.useTags && this.editsEnabled && foundTaskCount > 0) { setEditsEnabled(foundTaskCount); if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } if (trailing > NO_TRAILING_COMMENT) { // a javadoc comment should not be considered as a trailing comment this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); return; } this.lastLineComment.contiguous = false; if (rejectJavadocComment) break; if (lines >= 1) { if (lines > 1) { preserveEmptyLines(lines - 1, this.scanner.getCurrentTokenStartPosition()); } else if (lines == 1) { printNewLine(this.scanner.getCurrentTokenStartPosition()); } } else if (hasWhitespaces) { space(); } hasWhitespaces = false; if (includesJavadocComments()) { printJavadocComment(this.scanner.startPosition, this.scanner.currentPosition); } else { printBlockComment(true); } if (this.useTags && !this.editsEnabled && foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } printNewLine(); currentTokenStartPosition = this.scanner.currentPosition; hasLineComment = false; hasComment = true; lines = 0; break; default : this.lastLineComment.contiguous = false; // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printModifiers(Annotation[] annotations, ASTVisitor visitor, int annotationSourceKind) { try { int annotationsLength = annotations != null ? annotations.length : 0; int annotationsIndex = 0; boolean isFirstModifier = true; int currentTokenStartPosition = this.scanner.currentPosition; boolean hasComment = false; boolean hasModifiers = false; while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { int foundTaskCount = this.scanner.foundTaskCount; int tokenStartPosition = this.scanner.getCurrentTokenStartPosition(); int tokenEndPosition = this.scanner.getCurrentTokenEndPosition(); switch(this.currentToken) { case TerminalTokens.TokenNamepublic : case TerminalTokens.TokenNameprotected : case TerminalTokens.TokenNameprivate : case TerminalTokens.TokenNamestatic : case TerminalTokens.TokenNameabstract : case TerminalTokens.TokenNamefinal : case TerminalTokens.TokenNamenative : case TerminalTokens.TokenNamesynchronized : case TerminalTokens.TokenNametransient : case TerminalTokens.TokenNamevolatile : case TerminalTokens.TokenNamestrictfp : hasModifiers = true; print(this.scanner.currentPosition - this.scanner.startPosition, !isFirstModifier); isFirstModifier = false; currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameAT : hasModifiers = true; if (!isFirstModifier) { space(); } this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); if (annotationsIndex < annotationsLength) { boolean insertSpaceBeforeBrace = this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer; this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer = false; try { annotations[annotationsIndex++].traverse(visitor, (BlockScope) null); } finally { this.formatter.preferences.insert_space_before_opening_brace_in_array_initializer = insertSpaceBeforeBrace; } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=122247 boolean shouldAddNewLine = false; switch (annotationSourceKind) { case ICodeFormatterConstants.ANNOTATION_ON_TYPE : if (this.formatter.preferences.insert_new_line_after_annotation_on_type) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_FIELD : if (this.formatter.preferences.insert_new_line_after_annotation_on_field) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_METHOD : if (this.formatter.preferences.insert_new_line_after_annotation_on_method) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_PACKAGE : if (this.formatter.preferences.insert_new_line_after_annotation_on_package) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_PARAMETER : if (this.formatter.preferences.insert_new_line_after_annotation_on_parameter) { shouldAddNewLine = true; } break; case ICodeFormatterConstants.ANNOTATION_ON_LOCAL_VARIABLE : if (this.formatter.preferences.insert_new_line_after_annotation_on_local_variable) { shouldAddNewLine = true; } break; default: // do nothing when no annotation formatting option specified } if (shouldAddNewLine) { this.printNewLine(); } } else { return; } isFirstModifier = false; currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.equals(this.disablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition+1)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } printBlockComment(this.currentToken == TerminalTokens.TokenNameCOMMENT_JAVADOC); if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.equals(this.enablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition+1); } } currentTokenStartPosition = this.scanner.currentPosition; hasComment = true; break; case TerminalTokens.TokenNameCOMMENT_LINE : tokenEndPosition = -this.scanner.commentStops[this.scanner.commentPtr]; if (this.useTags && this.editsEnabled) { boolean turnOff = false; if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); turnOff = true; } else if (this.tagsKind == this.currentToken && CharOperation.equals(this.disablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition)) { this.editsEnabled = false; turnOff = true; } if (turnOff) { if (!this.editsEnabled && this.editsIndex > 1) { OptimizedReplaceEdit currentEdit = this.edits[this.editsIndex-1]; if (this.scanner.startPosition == currentEdit.offset+currentEdit.length) { printNewLinesBeforeDisablingComment(); } } } } printLineComment(); if (this.useTags && !this.editsEnabled) { if (foundTaskCount > 0) { setEditsEnabled(foundTaskCount); } else if (this.tagsKind == this.currentToken) { this.editsEnabled = CharOperation.equals(this.enablingTag, this.scanner.source, tokenStartPosition, tokenEndPosition); } } currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); int count = 0; char[] whiteSpaces = this.scanner.getCurrentTokenSource(); for (int i = 0, max = whiteSpaces.length; i < max; i++) { switch(whiteSpaces[i]) { case '\r' : if ((i + 1) < max) { if (whiteSpaces[i + 1] == '\n') { i++; } } count++; break; case '\n' : count++; } } if (count >= 1 && hasComment) { printNewLine(); } currentTokenStartPosition = this.scanner.currentPosition; hasComment = false; break; default: if (hasModifiers) { space(); } // step back one token this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny, int emptyLineRules) { // Set brace flag, it's useful for the scribe while preserving line breaks printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT, emptyLineRules); try { this.currentToken = this.scanner.getNextToken(); if (expectedTokenType != this.currentToken) { throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ } print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny); } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){ printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); try { this.currentToken = this.scanner.getNextToken(); if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) { StringBuffer expectations = new StringBuffer(5); for (int i = 0; i < expectedTokenTypes.length; i++){ if (i > 0) { expectations.append(','); } expectations.append(expectedTokenTypes[i]); } throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ } print(this.scanner.currentPosition - this.scanner.startPosition, considerSpaceIfAny); } catch (InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printArrayQualifiedReference(int numberOfTokens, int sourceEnd) { int currentTokenStartPosition = this.scanner.currentPosition; int numberOfIdentifiers = 0; try { do { printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); switch(this.currentToken = this.scanner.getNextToken()) { case TerminalTokens.TokenNameEOF : return; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameIdentifier : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; if (++ numberOfIdentifiers == numberOfTokens) { this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } break; case TerminalTokens.TokenNameDOT : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameRPAREN: currentTokenStartPosition = this.scanner.startPosition; // $FALL-THROUGH$ - fall through default case... default: this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } while (this.scanner.currentPosition <= sourceEnd); } catch(InvalidInputException e) { throw new AbortFormatting(e); } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void printQualifiedReference(int sourceEnd, boolean expectParenthesis) { int currentTokenStartPosition = this.scanner.currentPosition; try { do { printComment(CodeFormatter.K_UNKNOWN, NO_TRAILING_COMMENT); switch(this.currentToken = this.scanner.getNextToken()) { case TerminalTokens.TokenNameEOF : return; case TerminalTokens.TokenNameWHITESPACE : addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : printBlockComment(false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameCOMMENT_LINE : printLineComment(); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameIdentifier : case TerminalTokens.TokenNameDOT : print(this.scanner.currentPosition - this.scanner.startPosition, false); currentTokenStartPosition = this.scanner.currentPosition; break; case TerminalTokens.TokenNameRPAREN: if (expectParenthesis) { currentTokenStartPosition = this.scanner.startPosition; } // $FALL-THROUGH$ - fall through default case... default: this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); return; } } while (this.scanner.currentPosition <= sourceEnd); } catch(InvalidInputException e) { throw new AbortFormatting(e); } }
7
            
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
0 4
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AbortFormatting e){ return failedToFormat(); }
0 0
runtime (Domain) AbortIncrementalBuildException
public class AbortIncrementalBuildException extends RuntimeException {

protected String qualifiedTypeName;
private static final long serialVersionUID = -8874662133883858502L; // backward compatible

public AbortIncrementalBuildException(String qualifiedTypeName) {
	this.qualifiedTypeName = qualifiedTypeName;
}
}
0 0
            
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
0 1
            
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (AbortIncrementalBuildException e) { // abort the incremental build and let the batch builder handle the problem if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... problem with " + e.qualifiedTypeName + //$NON-NLS-1$ ". Likely renamed inside its existing source file."); //$NON-NLS-1$ return false; }
0 0
runtime (Domain) AbortMethod
public class AbortMethod extends AbortType {

	private static final long serialVersionUID = -1480267398969840003L; // backward compatible

public AbortMethod(CompilationResult compilationResult, CategorizedProblem problem) {
	super(compilationResult, problem);
}
}
17
            
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; if (this.constant != Constant.NotAConstant) { if (valueRequired) { codeStream.generateConstant(this.constant, this.implicitConversion); } } else { switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // reading a field if (!valueRequired) break; FieldBinding codegenField = ((FieldBinding) this.binding).original(); Constant fieldConstant = codegenField.constant(); if (fieldConstant == Constant.NotAConstant) { // directly use inlined value for constant fields if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); if (codegenField.isStatic()) { codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { if ((this.bits & DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & DepthMASK) >> DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } } else { // managing private access if (!codegenField.isStatic()) { if ((this.bits & DepthMASK) != 0) { // internal error, per construction we should have found it // not yet supported currentScope.problemReporter().needImplementation(this); } else { generateReceiver(codeStream); } } else { codeStream.aconst_null(); } codeStream.generateEmulatedReadAccessForField(codegenField); } if (this.genericCast != null) codeStream.checkcast(this.genericCast); codeStream.generateImplicitConversion(this.implicitConversion); } else { // directly use the inlined value codeStream.generateConstant(fieldConstant, this.implicitConversion); } break; case Binding.LOCAL : // reading a local LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (!valueRequired) break; // outer local? if ((this.bits & DepthMASK) != 0) { // outer local can be reached either through a synthetic arg or a synthetic field VariableBinding[] path = currentScope.getEmulationPath(localBinding); codeStream.generateOuterAccess(path, this, localBinding, currentScope); } else { // regular local variable read codeStream.load(localBinding); } codeStream.generateImplicitConversion(this.implicitConversion); break; } } codeStream.recordPositionsFrom(pc, this.sourceStart); }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.isStatic()) { if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { // used to store the value codeStream.generateEmulationForField(codegenField); codeStream.aconst_null(); // used to retrieve the actual value codeStream.aconst_null(); codeStream.generateEmulatedReadAccessForField(codegenField); } } else { if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { if ((this.bits & DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & DepthMASK) >> DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } codeStream.dup(); TypeBinding someReceiverType = this.delegateThis != null ? this.delegateThis.type : this.actualReceiverType; TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, someReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { if ((this.bits & DepthMASK) != 0) { // internal error, per construction we should have found it // not yet supported currentScope.problemReporter().needImplementation(this); } // used to store the value codeStream.generateEmulationForField(codegenField); generateReceiver(codeStream); // used to retrieve the actual value codeStream.dup(); codeStream.generateEmulatedReadAccessForField(codegenField); } } break; case Binding.LOCAL : // assigning to a local variable (cannot assign to outer local) LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // using incr bytecode if possible Constant assignConstant; switch (localBinding.type.id) { case T_JavaLangString : codeStream.generateStringConcatenationAppend(currentScope, this, expression); if (valueRequired) { codeStream.dup(); } codeStream.store(localBinding, false); return; case T_int : assignConstant = expression.constant; if (localBinding.resolvedPosition == -1) { if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } if ((assignConstant != Constant.NotAConstant) && (assignConstant.typeID() != TypeIds.T_float) // only for integral types && (assignConstant.typeID() != TypeIds.T_double)) { // TODO (philippe) is this test needed ? switch (operator) { case PLUS : int increment = assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; case MINUS : increment = -assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; } } //$FALL-THROUGH$ default : if (localBinding.resolvedPosition == -1) { assignConstant = expression.constant; if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } codeStream.load(localBinding); } } // perform the actual compound operation int operationTypeID; switch(operationTypeID = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4) { case T_JavaLangString : case T_JavaLangObject : case T_undefined : codeStream.generateStringConcatenationAppend(currentScope, null, expression); break; default : // promote the array reference to the suitable operation type codeStream.generateImplicitConversion(this.implicitConversion); // generate the increment value (will by itself be promoted to the operation value) if (expression == IntLiteral.One){ // prefix operation codeStream.generateConstant(expression.constant, this.implicitConversion); } else { expression.generateCode(currentScope, codeStream, true); } // perform the operation codeStream.sendOperator(operator, operationTypeID); // cast the value back to the array reference type codeStream.generateImplicitConversion(assignmentImplicitConversion); } // store the result back into the variable switch (this.bits & RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) { fieldStore(currentScope, codeStream, codegenField, writeAccessor, this.actualReceiverType, this.delegateThis == null /* implicit this */, valueRequired); } else { // current stack is: // field receiver value if (valueRequired) { switch (codegenField.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2_x2(); break; default: codeStream.dup_x2(); break; } } // current stack is: // value field receiver value codeStream.generateEmulatedWriteAccessForField(codegenField); } return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (valueRequired) { switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.store(localBinding, false); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/StackMapFrameCodeStream.java
public void generateOuterAccess(Object[] mappingSequence, ASTNode invocationSite, Binding target, Scope scope) { int currentPosition = this.position; super.generateOuterAccess(mappingSequence, invocationSite, target, scope); if (currentPosition == this.position) { // no code has been generate during outer access => no enclosing instance is available throw new AbortMethod(scope.referenceCompilationUnit().compilationResult, null); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/CodeStream.java
protected void writePosition(BranchLabel label) { int offset = label.position - this.position + 1; if (Math.abs(offset) > 0x7FFF && !this.wideMode) { throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE, null); } this.writeSignedShort(offset); int[] forwardRefs = label.forwardReferences(); for (int i = 0, max = label.forwardReferenceCount(); i < max; i++) { this.writePosition(label, forwardRefs[i]); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/CodeStream.java
protected void writePosition(BranchLabel label, int forwardReference) { final int offset = label.position - forwardReference + 1; if (Math.abs(offset) > 0x7FFF && !this.wideMode) { throw new AbortMethod(CodeStream.RESTART_IN_WIDE_MODE, null); } if (this.wideMode) { if ((label.tagBits & BranchLabel.WIDE) != 0) { this.writeSignedWord(forwardReference, offset); } else { this.writeSignedShort(forwardReference, offset); } } else { this.writeSignedShort(forwardReference, offset); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
private void internalGenerateCode(ClassScope classScope, ClassFile classFile) { classFile.generateMethodInfoHeader(this.binding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttributes(this.binding); if ((!this.binding.isNative()) && (!this.binding.isAbstract())) { TypeDeclaration declaringType = classScope.referenceContext; int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); // initialize local positions - including initializer scope. ReferenceBinding declaringClass = this.binding.declaringClass; int enumOffset = declaringClass.isEnum() ? 2 : 0; // String name, int ordinal int argSlotSize = 1 + enumOffset; // this==aload0 if (declaringClass.isNestedType()){ this.scope.extraSyntheticArguments = declaringClass.syntheticOuterLocalVariables(); this.scope.computeLocalVariablePositions(// consider synthetic arguments if any declaringClass.getEnclosingInstancesSlotSize() + 1 + enumOffset, codeStream); argSlotSize += declaringClass.getEnclosingInstancesSlotSize(); argSlotSize += declaringClass.getOuterLocalVariablesSlotSize(); } else { this.scope.computeLocalVariablePositions(1 + enumOffset, codeStream); } if (this.arguments != null) { for (int i = 0, max = this.arguments.length; i < max; i++) { // arguments initialization for local variable debug attributes LocalVariableBinding argBinding; codeStream.addVisibleLocalVariable(argBinding = this.arguments[i].binding); argBinding.recordInitializationStartPC(0); switch(argBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : argSlotSize += 2; break; default : argSlotSize++; break; } } } MethodScope initializerScope = declaringType.initializerScope; initializerScope.computeLocalVariablePositions(argSlotSize, codeStream); // offset by the argument size (since not linked to method scope) boolean needFieldInitializations = this.constructorCall == null || this.constructorCall.accessMode != ExplicitConstructorCall.This; // post 1.4 target level, synthetic initializations occur prior to explicit constructor call boolean preInitSyntheticFields = this.scope.compilerOptions().targetJDK >= ClassFileConstants.JDK1_4; if (needFieldInitializations && preInitSyntheticFields){ generateSyntheticFieldInitializationsIfNecessary(this.scope, codeStream, declaringClass); codeStream.recordPositionsFrom(0, this.bodyStart); } // generate constructor call if (this.constructorCall != null) { this.constructorCall.generateCode(this.scope, codeStream); } // generate field initialization - only if not invoking another constructor call of the same class if (needFieldInitializations) { if (!preInitSyntheticFields){ generateSyntheticFieldInitializationsIfNecessary(this.scope, codeStream, declaringClass); } // generate user field initialization if (declaringType.fields != null) { for (int i = 0, max = declaringType.fields.length; i < max; i++) { FieldDeclaration fieldDecl; if (!(fieldDecl = declaringType.fields[i]).isStatic()) { fieldDecl.generateCode(initializerScope, codeStream); } } } } // generate statements if (this.statements != null) { for (int i = 0, max = this.statements.length; i < max; i++) { this.statements[i].generateCode(this.scope, codeStream); } } // if a problem got reported during code gen, then trigger problem method creation if (this.ignoreFurtherInvestigation) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } if ((this.bits & ASTNode.NeedFreeReturn) != 0) { codeStream.return_(); } // local variable attributes codeStream.exitUserScope(this.scope); codeStream.recordPositionsFrom(0, this.bodyEnd); try { classFile.completeCodeAttribute(codeAttributeOffset); } catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } attributeNumber++; if ((codeStream instanceof StackMapFrameCodeStream) && needFieldInitializations && declaringType.fields != null) { ((StackMapFrameCodeStream) codeStream).resetSecretLocals(); } } classFile.completeMethodInfo(this.binding, methodAttributeOffset, attributeNumber); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void generateCode(ClassFile classFile) { classFile.generateMethodInfoHeader(this.binding); int methodAttributeOffset = classFile.contentsOffset; int attributeNumber = classFile.generateMethodInfoAttributes(this.binding); if ((!this.binding.isNative()) && (!this.binding.isAbstract())) { int codeAttributeOffset = classFile.contentsOffset; classFile.generateCodeAttributeHeader(); CodeStream codeStream = classFile.codeStream; codeStream.reset(this, classFile); // initialize local positions this.scope.computeLocalVariablePositions(this.binding.isStatic() ? 0 : 1, codeStream); // arguments initialization for local variable debug attributes if (this.arguments != null) { for (int i = 0, max = this.arguments.length; i < max; i++) { LocalVariableBinding argBinding; codeStream.addVisibleLocalVariable(argBinding = this.arguments[i].binding); argBinding.recordInitializationStartPC(0); } } if (this.statements != null) { for (int i = 0, max = this.statements.length; i < max; i++) this.statements[i].generateCode(this.scope, codeStream); } // if a problem got reported during code gen, then trigger problem method creation if (this.ignoreFurtherInvestigation) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } if ((this.bits & ASTNode.NeedFreeReturn) != 0) { codeStream.return_(); } // local variable attributes codeStream.exitUserScope(this.scope); codeStream.recordPositionsFrom(0, this.declarationSourceEnd); try { classFile.completeCodeAttribute(codeAttributeOffset); } catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); } attributeNumber++; } else { checkArgumentsSize(); } classFile.completeMethodInfo(this.binding, methodAttributeOffset, attributeNumber); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; if (this.constant != Constant.NotAConstant) { if (valueRequired) { codeStream.generateConstant(this.constant, this.implicitConversion); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } else { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); Constant fieldConstant = codegenField.constant(); if (fieldConstant != Constant.NotAConstant) { // directly use inlined value for constant fields if (valueRequired) { codeStream.generateConstant(fieldConstant, this.implicitConversion); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (codegenField.isStatic()) { if (!valueRequired // if no valueRequired, still need possible side-effects of <clinit> invocation, if field belongs to different class && ((FieldBinding)this.binding).original().declaringClass == this.actualReceiverType.erasure() && ((this.implicitConversion & TypeIds.UNBOXING) == 0) && this.genericCast == null) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // managing private access if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if (!valueRequired && (this.implicitConversion & TypeIds.UNBOXING) == 0 && this.genericCast == null) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // managing enclosing instance access if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { generateReceiver(codeStream); } // managing private access if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } break; case Binding.LOCAL : // reading a local LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } if (!valueRequired && (this.implicitConversion & TypeIds.UNBOXING) == 0) { // if no valueRequired, optimize out entire gen codeStream.recordPositionsFrom(pc, this.sourceStart); return; } // outer local? if ((this.bits & ASTNode.DepthMASK) != 0) { // outer local can be reached either through a synthetic arg or a synthetic field VariableBinding[] path = currentScope.getEmulationPath(localBinding); codeStream.generateOuterAccess(path, this, localBinding, currentScope); } else { // regular local variable read codeStream.load(localBinding); } break; default: // type codeStream.recordPositionsFrom(pc, this.sourceStart); return; } } // required cast must occur even if no value is required if (this.genericCast != null) codeStream.checkcast(this.genericCast); if (valueRequired) { codeStream.generateImplicitConversion(this.implicitConversion); } else { boolean isUnboxing = (this.implicitConversion & TypeIds.UNBOXING) != 0; // conversion only generated if unboxing if (isUnboxing) codeStream.generateImplicitConversion(this.implicitConversion); switch (isUnboxing ? postConversionType(currentScope).id : this.resolvedType.id) { case T_long : case T_double : codeStream.pop2(); break; default : codeStream.pop(); } } codeStream.recordPositionsFrom(pc, this.sourceStart); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); if (codegenField.isStatic()) { if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { codeStream.aload_0(); } codeStream.dup(); if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } break; case Binding.LOCAL : // assigning to a local variable (cannot assign to outer local) LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // using incr bytecode if possible Constant assignConstant; switch (localBinding.type.id) { case T_JavaLangString : codeStream.generateStringConcatenationAppend(currentScope, this, expression); if (valueRequired) { codeStream.dup(); } codeStream.store(localBinding, false); return; case T_int : assignConstant = expression.constant; if (localBinding.resolvedPosition == -1) { if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } if ((assignConstant != Constant.NotAConstant) && (assignConstant.typeID() != TypeIds.T_float) // only for integral types && (assignConstant.typeID() != TypeIds.T_double)) { // TODO (philippe) is this test needed ? switch (operator) { case PLUS : int increment = assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; case MINUS : increment = -assignConstant.intValue(); if (increment != (short) increment) break; // not representable as a 16-bits value codeStream.iinc(localBinding.resolvedPosition, increment); if (valueRequired) { codeStream.load(localBinding); } return; } } //$FALL-THROUGH$ default : if (localBinding.resolvedPosition == -1) { assignConstant = expression.constant; if (valueRequired) { /* * restart code gen because we either: * - need the value * - the constant can have potential side-effect */ localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } else if (assignConstant == Constant.NotAConstant) { // we only need to generate the value of the expression's constant if it is not a constant expression expression.generateCode(currentScope, codeStream, false); } return; } codeStream.load(localBinding); } } // perform the actual compound operation int operationTypeID; switch(operationTypeID = (this.implicitConversion & TypeIds.IMPLICIT_CONVERSION_MASK) >> 4) { case T_JavaLangString : case T_JavaLangObject : case T_undefined : // we enter here if the single name reference is a field of type java.lang.String or if the type of the // operation is java.lang.Object // For example: o = o + ""; // where the compiled type of o is java.lang.Object. codeStream.generateStringConcatenationAppend(currentScope, null, expression); // no need for generic cast on previous #getfield since using Object string buffer methods. break; default : // promote the array reference to the suitable operation type if (this.genericCast != null) codeStream.checkcast(this.genericCast); codeStream.generateImplicitConversion(this.implicitConversion); // generate the increment value (will by itself be promoted to the operation value) if (expression == IntLiteral.One){ // prefix operation codeStream.generateConstant(expression.constant, this.implicitConversion); } else { expression.generateCode(currentScope, codeStream, true); } // perform the operation codeStream.sendOperator(operator, operationTypeID); // cast the value back to the array reference type codeStream.generateImplicitConversion(assignmentImplicitConversion); } // store the result back into the variable switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding codegenField = ((FieldBinding) this.binding).original(); fieldStore(currentScope, codeStream, codegenField, writeAccessor, this.actualReceiverType, true /* implicit this*/, valueRequired); // no need for generic cast as value got dupped return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; if (valueRequired) { switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.store(localBinding, false); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/SingleNameReference.java
public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) { switch (this.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field FieldBinding fieldBinding = (FieldBinding)this.binding; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185682 // check if postIncrement is the only usage of a private field reportOnlyUselesslyReadPrivateField(currentScope, fieldBinding, valueRequired); FieldBinding codegenField = fieldBinding.original(); if (codegenField.isStatic()) { if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getstatic, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } else { if ((this.bits & ASTNode.DepthMASK) != 0) { ReferenceBinding targetType = currentScope.enclosingSourceType().enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT); Object[] emulationPath = currentScope.getEmulationPath(targetType, true /*only exact match*/, false/*consider enclosing arg*/); codeStream.generateOuterAccess(emulationPath, this, targetType, currentScope); } else { codeStream.aload_0(); } codeStream.dup(); if ((this.syntheticAccessors == null) || (this.syntheticAccessors[SingleNameReference.READ] == null)) { TypeBinding constantPoolDeclaringClass = CodeStream.getConstantPoolDeclaringClass(currentScope, codegenField, this.actualReceiverType, true /* implicit this */); codeStream.fieldAccess(Opcodes.OPC_getfield, codegenField, constantPoolDeclaringClass); } else { codeStream.invoke(Opcodes.OPC_invokestatic, this.syntheticAccessors[SingleNameReference.READ], null /* default declaringClass */); } } TypeBinding operandType; if (this.genericCast != null) { codeStream.checkcast(this.genericCast); operandType = this.genericCast; } else { operandType = codegenField.type; } if (valueRequired) { if (codegenField.isStatic()) { switch (operandType.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value] switch (operandType.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2_x1(); break; default: codeStream.dup_x1(); break; } } } codeStream.generateImplicitConversion(this.implicitConversion); codeStream.generateConstant(postIncrement.expression.constant, this.implicitConversion); codeStream.sendOperator(postIncrement.operator, this.implicitConversion & TypeIds.COMPILE_TYPE_MASK); codeStream.generateImplicitConversion(postIncrement.preAssignImplicitConversion); fieldStore(currentScope, codeStream, codegenField, this.syntheticAccessors == null ? null : this.syntheticAccessors[SingleNameReference.WRITE], this.actualReceiverType, true /*implicit this*/, false); // no need for generic cast return; case Binding.LOCAL : // assigning to a local variable LocalVariableBinding localBinding = (LocalVariableBinding) this.binding; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=185682 // check if postIncrement is the only usage of this local Reference.reportOnlyUselesslyReadLocal(currentScope, localBinding, valueRequired); if (localBinding.resolvedPosition == -1) { if (valueRequired) { // restart code gen localBinding.useFlag = LocalVariableBinding.USED; throw new AbortMethod(CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE, null); } return; } // using incr bytecode if possible if (localBinding.type == TypeBinding.INT) { if (valueRequired) { codeStream.load(localBinding); } if (postIncrement.operator == OperatorIds.PLUS) { codeStream.iinc(localBinding.resolvedPosition, 1); } else { codeStream.iinc(localBinding.resolvedPosition, -1); } } else { codeStream.load(localBinding); if (valueRequired){ switch (localBinding.type.id) { case TypeIds.T_long : case TypeIds.T_double : codeStream.dup2(); break; default: codeStream.dup(); break; } } codeStream.generateImplicitConversion(this.implicitConversion); codeStream.generateConstant(postIncrement.expression.constant, this.implicitConversion); codeStream.sendOperator(postIncrement.operator, this.implicitConversion & TypeIds.COMPILE_TYPE_MASK); codeStream.generateImplicitConversion(postIncrement.preAssignImplicitConversion); codeStream.store(localBinding, false); } } }
2
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
0 7
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/MethodDeclaration.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch (AbortMethod e) { if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Clinit.java
catch (AbortMethod e) { // should never occur // the clinit referenceContext is the type declaration // All clinit problems will be reported against the type: AbortType instead of AbortMethod // reset the contentsOffset to the value before generating the clinit code // decrement the number of method info as well. // This is done in the addProblemMethod and addProblemConstructor for other // cases. if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode // restart method generation restart = true; } else { classFile.contentsOffset = clinitOffset; classFile.methodCount--; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = clinitOffset; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); // restart method generation restart = true; } else { // produce a problem method accounting for this fatal error classFile.contentsOffset = clinitOffset; classFile.methodCount--; restart = false; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // a fatal error was detected during code generation, need to restart code gen if possible if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) { // a branch target required a goto_w, restart code gen in wide mode. if (!restart) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetInWideMode(); // request wide mode restart = true; } else { // after restarting in wide mode, code generation failed again // report a problem restart = false; abort = true; } } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) { classFile.contentsOffset = problemResetPC; classFile.methodCount--; classFile.codeStream.resetForCodeGenUnusedLocals(); restart = true; } else { restart = false; abort = true; } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch (AbortMethod e) { // ========= abort on fatal error ============= this.ignoreFurtherInvestigation = true; }
0 0
runtime (Domain) AbortType
public class AbortType extends AbortCompilationUnit {

	private static final long serialVersionUID = -5882417089349134385L; // backward compatible

public AbortType(CompilationResult compilationResult, CategorizedProblem problem) {
	super(compilationResult, problem);
}
}
5
            
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
public void generateCode(ClassFile enclosingClassFile) { if ((this.bits & ASTNode.HasBeenGenerated) != 0) return; this.bits |= ASTNode.HasBeenGenerated; if (this.ignoreFurtherInvestigation) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); return; } try { // create the result for a compiled type ClassFile classFile = new CodeSnippetClassFile(this.binding, enclosingClassFile, false); // generate all fiels classFile.addFieldInfos(); if (this.binding.isMemberType()) { classFile.recordInnerClasses(this.binding); } else if (this.binding.isLocalType()) { enclosingClassFile.recordInnerClasses(this.binding); classFile.recordInnerClasses(this.binding); } TypeVariableBinding[] typeVariables = this.binding.typeVariables(); for (int i = 0, max = typeVariables.length; i < max; i++) { TypeVariableBinding typeVariableBinding = typeVariables[i]; if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) { Util.recordNestedType(classFile, typeVariableBinding); } } if (this.memberTypes != null) { for (int i = 0, max = this.memberTypes.length; i < max; i++) { TypeDeclaration memberType = this.memberTypes[i]; classFile.recordInnerClasses(memberType.binding); memberType.generateCode(this.scope, classFile); } } // generate all methods classFile.setForMethodInfos(); if (this.methods != null) { for (int i = 0, max = this.methods.length; i < max; i++) { this.methods[i].generateCode(this.scope, classFile); } } // generate all methods classFile.addSpecialMethods(); if (this.ignoreFurtherInvestigation){ // trigger problem type generation for code gen errors throw new AbortType(this.scope.referenceCompilationUnit().compilationResult, null); } // finalize the compiled type result classFile.addAttributes(); this.scope.referenceCompilationUnit().compilationResult.record(this.binding.constantPoolName(), classFile); } catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortType(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
public void generateCode(ClassFile enclosingClassFile) { if ((this.bits & ASTNode.HasBeenGenerated) != 0) return; this.bits |= ASTNode.HasBeenGenerated; if (this.ignoreFurtherInvestigation) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); return; } try { // create the result for a compiled type ClassFile classFile = ClassFile.getNewInstance(this.binding); classFile.initialize(this.binding, enclosingClassFile, false); if (this.binding.isMemberType()) { classFile.recordInnerClasses(this.binding); } else if (this.binding.isLocalType()) { enclosingClassFile.recordInnerClasses(this.binding); classFile.recordInnerClasses(this.binding); } TypeVariableBinding[] typeVariables = this.binding.typeVariables(); for (int i = 0, max = typeVariables.length; i < max; i++) { TypeVariableBinding typeVariableBinding = typeVariables[i]; if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) { Util.recordNestedType(classFile, typeVariableBinding); } } // generate all fiels classFile.addFieldInfos(); if (this.memberTypes != null) { for (int i = 0, max = this.memberTypes.length; i < max; i++) { TypeDeclaration memberType = this.memberTypes[i]; classFile.recordInnerClasses(memberType.binding); memberType.generateCode(this.scope, classFile); } } // generate all methods classFile.setForMethodInfos(); if (this.methods != null) { for (int i = 0, max = this.methods.length; i < max; i++) { this.methods[i].generateCode(this.scope, classFile); } } // generate all synthetic and abstract methods classFile.addSpecialMethods(); if (this.ignoreFurtherInvestigation) { // trigger problem type generation for code gen errors throw new AbortType(this.scope.referenceCompilationUnit().compilationResult, null); } // finalize the compiled type result classFile.addAttributes(); this.scope.referenceCompilationUnit().compilationResult.record( this.binding.constantPoolName(), classFile); } catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/CompilationUnitDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortType : throw new AbortType(this.compilationResult, problem); case AbortMethod : throw new AbortMethod(this.compilationResult, problem); default : throw new AbortCompilationUnit(this.compilationResult, problem); } }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
public void abort(int abortLevel, CategorizedProblem problem) { switch (abortLevel) { case AbortCompilation : throw new AbortCompilation(this.compilationResult, problem); case AbortCompilationUnit : throw new AbortCompilationUnit(this.compilationResult, problem); case AbortType : throw new AbortType(this.compilationResult, problem); default : throw new AbortMethod(this.compilationResult, problem); } }
0 0 10
            
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; CodeSnippetClassFile.createProblemType(this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { if (this.binding == null) return; ClassFile.createProblemType( this, this.scope.referenceCompilationUnit().compilationResult); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { this.ignoreFurtherInvestigation = true; return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
// in compiler/org/eclipse/jdt/internal/compiler/ast/TypeDeclaration.java
catch (AbortType e) { // silent abort }
0 0
runtime (Domain) AlignmentException
public class AlignmentException extends RuntimeException {

	public static final int LINE_TOO_LONG = 1;
	public static final int ALIGN_TOO_SMALL = 2;
	private static final long serialVersionUID = -3324134986466253314L; // backward compatible

	int reason;
	int value;
	public int relativeDepth;

	public AlignmentException(int reason, int relativeDepth) {
		this(reason, 0, relativeDepth);
	}

	public AlignmentException(int reason, int value, int relativeDepth) {
		this.reason = reason;
		this.value = value;
		this.relativeDepth = relativeDepth;
	}

	public String toString(){
		StringBuffer buffer = new StringBuffer(10);
		switch(this.reason){
			case LINE_TOO_LONG :
				buffer.append("LINE_TOO_LONG");	//$NON-NLS-1$
				break;
			case ALIGN_TOO_SMALL :
				buffer.append("ALIGN_TOO_SMALL");	//$NON-NLS-1$
				break;
		}
		buffer
			.append("<relativeDepth: ")	//$NON-NLS-1$
			.append(this.relativeDepth)
			.append(">\n");	//$NON-NLS-1$
		return buffer.toString();
	}
}
4
            
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
public void handleLineTooLong() { if (this.formatter.preferences.wrap_outer_expressions_when_nested) { handleLineTooLongSmartly(); return; } // search for closest breakable alignment, using tiebreak rules // look for outermost breakable one int relativeDepth = 0, outerMostDepth = -1; Alignment targetAlignment = this.currentAlignment; while (targetAlignment != null){ if (targetAlignment.tieBreakRule == Alignment.R_OUTERMOST && targetAlignment.couldBreak()){ outerMostDepth = relativeDepth; } targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (outerMostDepth >= 0) { throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth); } // look for innermost breakable one relativeDepth = 0; targetAlignment = this.currentAlignment; while (targetAlignment != null){ if (targetAlignment.couldBreak()){ throw new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth); } targetAlignment = targetAlignment.enclosing; relativeDepth++; } // did not find any breakable location - proceed }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
private void handleLineTooLongSmartly() { // search for closest breakable alignment, using tiebreak rules // look for outermost breakable one int relativeDepth = 0, outerMostDepth = -1; Alignment targetAlignment = this.currentAlignment; int previousKind = -1; int insideMessage = 0; boolean insideStringConcat = false; while (targetAlignment != null){ boolean couldBreak = targetAlignment.tieBreakRule == Alignment.R_OUTERMOST || (!insideStringConcat && insideMessage > 0 && targetAlignment.kind == Alignment.MESSAGE_ARGUMENTS && (!targetAlignment.wasReset() || previousKind != Alignment.MESSAGE_SEND)); if (couldBreak && targetAlignment.couldBreak()){ outerMostDepth = relativeDepth; } switch (targetAlignment.kind) { case Alignment.MESSAGE_ARGUMENTS: case Alignment.MESSAGE_SEND: insideMessage++; break; case Alignment.STRING_CONCATENATION: insideStringConcat = true; break; } previousKind = targetAlignment.kind; targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (outerMostDepth >= 0) { throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth); } // look for innermost breakable one relativeDepth = 0; targetAlignment = this.currentAlignment; AlignmentException alignmentException = null; int msgArgsDepth = -1; while (targetAlignment != null) { if (targetAlignment.kind == Alignment.MESSAGE_ARGUMENTS) { msgArgsDepth = relativeDepth; } if (alignmentException == null) { if (targetAlignment.couldBreak()) { // do not throw the exception immediately to have a chance to reset // previously broken alignments (see bug 203588) alignmentException = new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth); if (insideStringConcat) throw alignmentException; } } else if (targetAlignment.wasSplit) { // reset the nearest already broken outermost alignment. // Note that it's not done twice to avoid infinite loop while raising // the exception on an innermost alignment... if (!targetAlignment.wasReset()) { targetAlignment.reset(); if (msgArgsDepth > alignmentException.relativeDepth) { alignmentException.relativeDepth = msgArgsDepth; } throw alignmentException; } } targetAlignment = targetAlignment.enclosing; relativeDepth++; } if (alignmentException != null) { throw alignmentException; } // did not find any breakable location - proceed if (this.currentAlignment != null) { this.currentAlignment.blockAlign = false; this.currentAlignment.tooLong = true; } }
// in formatter/org/eclipse/jdt/internal/formatter/align/Alignment.java
public void checkColumn() { if ((this.mode & M_MULTICOLUMN) != 0 && this.fragmentCount > 0) { int currentIndentation = this.scribe.getNextIndentationLevel(this.scribe.column+(this.scribe.needSpace ? 1 : 0)); int fragmentIndentation = this.fragmentIndentations[this.fragmentIndex]; if (currentIndentation > fragmentIndentation) { this.fragmentIndentations[this.fragmentIndex] = currentIndentation; if (fragmentIndentation != 0) { for (int i = this.fragmentIndex+1; i < this.fragmentCount; i++) { this.fragmentIndentations[i] = 0; } this.needRedoColumnAlignment = true; } } // backtrack only once all fragments got checked if (this.needRedoColumnAlignment && this.fragmentIndex == this.fragmentCount-1) { // alignment too small // if (CodeFormatterVisitor.DEBUG){ // System.out.println("ALIGNMENT TOO SMALL"); // System.out.println(this); // } this.needRedoColumnAlignment = false; int relativeDepth = 0; Alignment targetAlignment = this.scribe.memberAlignment; while (targetAlignment != null){ if (targetAlignment == this){ throw new AlignmentException(AlignmentException.ALIGN_TOO_SMALL, relativeDepth); } targetAlignment = targetAlignment.enclosing; relativeDepth++; } } } }
0 0 31
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ startIndex = memberAlignment.chunkStartIndex; this.scribe.redoMemberAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(AlignmentException e){ this.scribe.redoAlignment(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { this.scribe.redoAlignment(e); }
1
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch (AlignmentException e) { if (arrayInitializerAlignment == null) throw e; this.scribe.redoAlignment(e); }
0
runtime (Domain) AnonymousMemberFound
static class AnonymousMemberFound extends RuntimeException {
		private static final long serialVersionUID = 1L;
	}
1
            
// 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; }
0 0 1
            
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (AnonymousMemberFound e) { return new Parser(this.problemReporter, true).parse(this.cu, compilationResult); }
0 0
unknown (Lib) ArithmeticException 0 0 0 1
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/BinaryExpression.java
catch (ArithmeticException e) { this.constant = Constant.NotAConstant; // 1.2 no longer throws an exception at compile-time //scope.problemReporter().compileTimeConstantThrowsArithmeticException(this); }
0 0
unknown (Lib) ArrayIndexOutOfBoundsException 4
            
// in model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java
public CharArrayBuffer append(char[] src, int start, int length) { if (start < 0) throw new ArrayIndexOutOfBoundsException(); if (length < 0) throw new ArrayIndexOutOfBoundsException(); if (src != null) { int srcLength = src.length; if (start > srcLength) throw new ArrayIndexOutOfBoundsException(); if (length + start > srcLength) throw new ArrayIndexOutOfBoundsException(); /** do length check here to allow exceptions to be thrown */ if (length > 0) { if (this.end == this.size) { int size2 = this.size * 2; System.arraycopy(this.buffer, 0, (this.buffer = new char[size2][]), 0, this.size); System.arraycopy(this.ranges, 0, (this.ranges = new int[size2][]), 0, this.size); this.size *= 2; } this.buffer[this.end] = src; this.ranges[this.end] = new int[] {start, length}; this.end++; } } return this; }
0 0 12
            
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (ArrayIndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/core/JavaConventions.java
catch (ArrayIndexOutOfBoundsException e) { return null; }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (ArrayIndexOutOfBoundsException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (ArrayIndexOutOfBoundsException e) { return "Cannot bind message for problem (id: " //$NON-NLS-1$ + (id & IProblem.IgnoreCategoriesMask) + ") \"" //$NON-NLS-1$ + new String(message) + "\" with arguments: {" //$NON-NLS-1$ + Util.toString(problemArguments) +"}"; //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
6
            
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
4
runtime (Domain) AssertionFailedException
public static class AssertionFailedException extends RuntimeException {
		
		private static final long serialVersionUID = -171699380721189572L;

		public AssertionFailedException(String message) {
			super(message);
		}
	}public static class AssertionFailedException extends RuntimeException {
		private static final long serialVersionUID = 1827352841030089703L;

	public AssertionFailedException(String message) {
		super(message);
	}
	}
31
            
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
public static IClasspathEntry elementDecode(Element element, IJavaProject project, Map unknownElements) { IPath projectPath = project.getProject().getFullPath(); NamedNodeMap attributes = element.getAttributes(); NodeList children = element.getChildNodes(); boolean[] foundChildren = new boolean[children.getLength()]; String kindAttr = removeAttribute(TAG_KIND, attributes); String pathAttr = removeAttribute(TAG_PATH, attributes); // ensure path is absolute IPath path = new Path(pathAttr); int kind = kindFromString(kindAttr); if (kind != IClasspathEntry.CPE_VARIABLE && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) { if (!(path.segmentCount() > 0 && path.segment(0).equals(ClasspathEntry.DOT_DOT))) { path = projectPath.append(path); } } // source attachment info (optional) IPath sourceAttachmentPath = element.hasAttribute(TAG_SOURCEPATH) ? new Path(removeAttribute(TAG_SOURCEPATH, attributes)) : null; if (kind != IClasspathEntry.CPE_VARIABLE && sourceAttachmentPath != null && !sourceAttachmentPath.isAbsolute()) { sourceAttachmentPath = projectPath.append(sourceAttachmentPath); } IPath sourceAttachmentRootPath = element.hasAttribute(TAG_ROOTPATH) ? new Path(removeAttribute(TAG_ROOTPATH, attributes)) : null; // exported flag (optional) boolean isExported = removeAttribute(TAG_EXPORTED, attributes).equals("true"); //$NON-NLS-1$ // inclusion patterns (optional) IPath[] inclusionPatterns = decodePatterns(attributes, TAG_INCLUDING); if (inclusionPatterns == null) inclusionPatterns = INCLUDE_ALL; // exclusion patterns (optional) IPath[] exclusionPatterns = decodePatterns(attributes, TAG_EXCLUDING); if (exclusionPatterns == null) exclusionPatterns = EXCLUDE_NONE; // access rules (optional) NodeList attributeList = getChildAttributes(TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = decodeAccessRules(attributeList); // backward compatibility if (accessRules == null) { accessRules = getAccessRules(inclusionPatterns, exclusionPatterns); } // combine access rules (optional) boolean combineAccessRestrictions = !removeAttribute(TAG_COMBINE_ACCESS_RULES, attributes).equals("false"); //$NON-NLS-1$ // extra attributes (optional) attributeList = getChildAttributes(TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = decodeExtraAttributes(attributeList); // custom output location IPath outputLocation = element.hasAttribute(TAG_OUTPUT) ? projectPath.append(removeAttribute(TAG_OUTPUT, attributes)) : null; String[] unknownAttributes = null; ArrayList unknownChildren = null; if (unknownElements != null) { // unknown attributes int unknownAttributeLength = attributes.getLength(); if (unknownAttributeLength != 0) { unknownAttributes = new String[unknownAttributeLength*2]; for (int i = 0; i < unknownAttributeLength; i++) { Node attribute = attributes.item(i); unknownAttributes[i*2] = attribute.getNodeName(); unknownAttributes[i*2 + 1] = attribute.getNodeValue(); } } // unknown children for (int i = 0, length = foundChildren.length; i < length; i++) { if (!foundChildren[i]) { Node node = children.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; if (unknownChildren == null) unknownChildren = new ArrayList(); StringBuffer buffer = new StringBuffer(); decodeUnknownNode(node, buffer, project); unknownChildren.add(buffer.toString()); } } } // recreate the CP entry IClasspathEntry entry = null; switch (kind) { case IClasspathEntry.CPE_PROJECT : entry = new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, combineAccessRestrictions, extraAttributes); break; case IClasspathEntry.CPE_LIBRARY : entry = JavaCore.newLibraryEntry( path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules, extraAttributes, isExported); break; case IClasspathEntry.CPE_SOURCE : // must be an entry in this project or specify another project String projSegment = path.segment(0); if (projSegment != null && projSegment.equals(project.getElementName())) { // this project entry = JavaCore.newSourceEntry( path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes); } else { if (path.segmentCount() == 1) { // another project entry = JavaCore.newProjectEntry( path, accessRules, combineAccessRestrictions, extraAttributes, isExported); } else { // an invalid source folder entry = JavaCore.newSourceEntry( path, inclusionPatterns, exclusionPatterns, outputLocation, extraAttributes); } } break; case IClasspathEntry.CPE_VARIABLE : entry = JavaCore.newVariableEntry( path, sourceAttachmentPath, sourceAttachmentRootPath, accessRules, extraAttributes, isExported); break; case IClasspathEntry.CPE_CONTAINER : entry = JavaCore.newContainerEntry( path, accessRules, extraAttributes, isExported); break; case ClasspathEntry.K_OUTPUT : if (!path.isAbsolute()) return null; entry = new ClasspathEntry( ClasspathEntry.K_OUTPUT, IClasspathEntry.CPE_LIBRARY, path, INCLUDE_ALL, EXCLUDE_NONE, null, // source attachment null, // source attachment root null, // custom output location false, null, // no access rules false, // no accessible files to combine NO_EXTRA_ATTRIBUTES); break; default : throw new AssertionFailedException(Messages.bind(Messages.classpath_unknownKind, kindAttr)); } if (unknownAttributes != null || unknownChildren != null) { UnknownXmlElements unknownXmlElements = new UnknownXmlElements(); unknownXmlElements.attributes = unknownAttributes; unknownXmlElements.children = unknownChildren; unknownElements.put(path, unknownXmlElements); } return entry; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newContainerEntry( IPath containerPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (containerPath == null) { throw new ClasspathEntry.AssertionFailedException("Container path cannot be null"); //$NON-NLS-1$ } else if (containerPath.segmentCount() < 1) { throw new ClasspathEntry.AssertionFailedException("Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$ } if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_CONTAINER, containerPath, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, true, // combine access rules extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newLibraryEntry( IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (path == null) throw new ClasspathEntry.AssertionFailedException("Library path cannot be null"); //$NON-NLS-1$ if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } boolean hasDotDot = ClasspathEntry.hasDotDot(path); if (!hasDotDot && !path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute: " + path); //$NON-NLS-1$ if (sourceAttachmentPath != null) { if (sourceAttachmentPath.isEmpty()) { sourceAttachmentPath = null; // treat empty path as none } else if (!sourceAttachmentPath.isAbsolute()) { throw new ClasspathEntry.AssertionFailedException("Source attachment path '" //$NON-NLS-1$ + sourceAttachmentPath + "' for IClasspathEntry must be absolute"); //$NON-NLS-1$ } } return new ClasspathEntry( IPackageFragmentRoot.K_BINARY, IClasspathEntry.CPE_LIBRARY, hasDotDot ? path : JavaProject.canonicalizedPath(path), ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns sourceAttachmentPath, sourceAttachmentRootPath, null, // specific output folder isExported, accessRules, false, // no access rules to combine extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) { if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ return newProjectEntry( path, ClasspathEntry.NO_ACCESS_RULES, true, ClasspathEntry.NO_EXTRA_ATTRIBUTES, isExported); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newProjectEntry( IPath path, IAccessRule[] accessRules, boolean combineAccessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns null, // source attachment null, // source attachment root null, // specific output folder isExported, accessRules, combineAccessRules, extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newSourceEntry(IPath path, IPath[] inclusionPatterns, IPath[] exclusionPatterns, IPath specificOutputLocation, IClasspathAttribute[] extraAttributes) { if (path == null) throw new ClasspathEntry.AssertionFailedException("Source path cannot be null"); //$NON-NLS-1$ if (!path.isAbsolute()) throw new ClasspathEntry.AssertionFailedException("Path for IClasspathEntry must be absolute"); //$NON-NLS-1$ if (exclusionPatterns == null) { exclusionPatterns = ClasspathEntry.EXCLUDE_NONE; } if (inclusionPatterns == null) { inclusionPatterns = ClasspathEntry.INCLUDE_ALL; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_SOURCE, path, inclusionPatterns, exclusionPatterns, null, // source attachment null, // source attachment root specificOutputLocation, // custom output location false, null, false, // no access rules to combine extraAttributes); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static IClasspathEntry newVariableEntry( IPath variablePath, IPath variableSourceAttachmentPath, IPath variableSourceAttachmentRootPath, IAccessRule[] accessRules, IClasspathAttribute[] extraAttributes, boolean isExported) { if (variablePath == null) throw new ClasspathEntry.AssertionFailedException("Variable path cannot be null"); //$NON-NLS-1$ if (variablePath.segmentCount() < 1) { throw new ClasspathEntry.AssertionFailedException("Illegal classpath variable path: \'" + variablePath.makeRelative().toString() + "\', must have at least one segment"); //$NON-NLS-1$//$NON-NLS-2$ } if (accessRules == null) { accessRules = ClasspathEntry.NO_ACCESS_RULES; } if (extraAttributes == null) { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } return new ClasspathEntry( IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_VARIABLE, variablePath, ClasspathEntry.INCLUDE_ALL, // inclusion patterns ClasspathEntry.EXCLUDE_NONE, // exclusion patterns variableSourceAttachmentPath, // source attachment variableSourceAttachmentRootPath, // source attachment root null, // specific output folder isExported, accessRules, false, // no access rules to combine extraAttributes); }
// 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, 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 compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
private FlowInfo addInfoFrom(FlowInfo inits, boolean handleInits) { if (this == DEAD_END) return this; if (inits == DEAD_END) return this; UnconditionalFlowInfo otherInits = inits.unconditionalInits(); if (handleInits) { // union of definitely assigned variables, this.definiteInits |= otherInits.definiteInits; // union of potentially set ones this.potentialInits |= otherInits.potentialInits; } // combine null information boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0, otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0; long a1, a2, a3, a4, na1, na2, na3, na4, b1, b2, b3, b4, nb1, nb2, nb3, nb4; if (otherHasNulls) { if (!thisHadNulls) { this.nullBit1 = otherInits.nullBit1; this.nullBit2 = otherInits.nullBit2; this.nullBit3 = otherInits.nullBit3; this.nullBit4 = otherInits.nullBit4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 1) { this.nullBit4 = ~0; } } } else { this.nullBit1 = (b1 = otherInits.nullBit1) | (a1 = this.nullBit1) & ((a3 = this.nullBit3) & (a4 = this.nullBit4) & (nb2 = ~(b2 = otherInits.nullBit2)) & (nb4 = ~(b4 = otherInits.nullBit4)) | ((na4 = ~a4) | (na3 = ~a3)) & ((na2 = ~(a2 = this.nullBit2)) & nb2 | a2 & (nb3 = ~(b3 = otherInits.nullBit3)) & nb4)); this.nullBit2 = b2 & (nb4 | nb3) | na3 & na4 & b2 | a2 & (nb3 & nb4 | (nb1 = ~b1) & (na3 | (na1 = ~a1)) | a1 & b2); this.nullBit3 = b3 & (nb1 & (b2 | a2 | na1) | b1 & (b4 | nb2 | a1 & a3) | na1 & na2 & na4) | a3 & nb2 & nb4 | nb1 & ((na2 & a4 | na1) & a3 | a1 & na2 & na4 & b2); this.nullBit4 = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2) | a1 & (a3 & nb2 & b4 | a2 & b2 & (b4 | a3 & na4 & nb3))) | b1 & (a3 & a4 & b4 | na2 & na4 & nb3 & b4 | a2 & ((b3 | a4) & b4 | na3 & a4 & b2 & b3) | na1 & (b4 | (a4 | a2) & b2 & b3)) | (na1 & (na3 & nb3 | na2 & nb2) | a1 & (nb2 & nb3 | a2 & a3)) & b4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 2) { this.nullBit4 = ~0; } } } this.tagBits |= NULL_FLAG_MASK; // in all cases - avoid forgetting extras } // treating extra storage if (this.extra != null || otherInits.extra != null) { int mergeLimit = 0, copyLimit = 0; if (this.extra != null) { if (otherInits.extra != null) { // both sides have extra storage int length, otherLength; if ((length = this.extra[0].length) < (otherLength = otherInits.extra[0].length)) { // current storage is shorter -> grow current for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, length); } mergeLimit = length; copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 3) { throw new AssertionFailedException("COVERAGE 3"); //$NON-NLS-1$ } } } else { // current storage is longer mergeLimit = otherLength; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 4) { throw new AssertionFailedException("COVERAGE 4"); //$NON-NLS-1$ } } } } } else if (otherInits.extra != null) { // no storage here, but other has extra storage. // shortcut regular copy because array copy is better int otherLength; this.extra = new long[extraLength][]; System.arraycopy(otherInits.extra[0], 0, (this.extra[0] = new long[otherLength = otherInits.extra[0].length]), 0, otherLength); System.arraycopy(otherInits.extra[1], 0, (this.extra[1] = new long[otherLength]), 0, otherLength); if (otherHasNulls) { for (int j = 2; j < extraLength; j++) { System.arraycopy(otherInits.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, otherLength); } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 5) { this.extra[5][otherLength - 1] = ~0; } } } else { for (int j = 2; j < extraLength; j++) { this.extra[j] = new long[otherLength]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 6) { throw new AssertionFailedException("COVERAGE 6"); //$NON-NLS-1$ } } } } int i; if (handleInits) { // manage definite assignment info for (i = 0; i < mergeLimit; i++) { this.extra[0][i] |= otherInits.extra[0][i]; this.extra[1][i] |= otherInits.extra[1][i]; } for (; i < copyLimit; i++) { this.extra[0][i] = otherInits.extra[0][i]; this.extra[1][i] = otherInits.extra[1][i]; } } // tweak limits for nulls if (!thisHadNulls) { if (copyLimit < mergeLimit) { copyLimit = mergeLimit; } mergeLimit = 0; } if (!otherHasNulls) { copyLimit = 0; mergeLimit = 0; } for (i = 0; i < mergeLimit; i++) { this.extra[1 + 1][i] = (b1 = otherInits.extra[1 + 1][i]) | (a1 = this.extra[1 + 1][i]) & ((a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & (nb2 = ~(b2 = otherInits.extra[2 + 1][i])) & (nb4 = ~(b4 = otherInits.extra[4 + 1][i])) | ((na4 = ~a4) | (na3 = ~a3)) & ((na2 = ~(a2 = this.extra[2 + 1][i])) & nb2 | a2 & (nb3 = ~(b3 = otherInits.extra[3 + 1][i])) & nb4)); this.extra[2 + 1][i] = b2 & (nb4 | nb3) | na3 & na4 & b2 | a2 & (nb3 & nb4 | (nb1 = ~b1) & (na3 | (na1 = ~a1)) | a1 & b2); this.extra[3 + 1][i] = b3 & (nb1 & (b2 | a2 | na1) | b1 & (b4 | nb2 | a1 & a3) | na1 & na2 & na4) | a3 & nb2 & nb4 | nb1 & ((na2 & a4 | na1) & a3 | a1 & na2 & na4 & b2); this.extra[4 + 1][i] = nb1 & (a4 & (na3 & nb3 | (a3 | na2) & nb2) | a1 & (a3 & nb2 & b4 | a2 & b2 & (b4 | a3 & na4 & nb3))) | b1 & (a3 & a4 & b4 | na2 & na4 & nb3 & b4 | a2 & ((b3 | a4) & b4 | na3 & a4 & b2 & b3) | na1 & (b4 | (a4 | a2) & b2 & b3)) | (na1 & (na3 & nb3 | na2 & nb2) | a1 & (nb2 & nb3 | a2 & a3)) & b4; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 7) { this.extra[5][i] = ~0; } } } for (; i < copyLimit; i++) { for (int j = 2; j < extraLength; j++) { this.extra[j][i] = otherInits.extra[j][i]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 8) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); return this; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public UnconditionalFlowInfo addPotentialNullInfoFrom( UnconditionalFlowInfo otherInits) { if ((this.tagBits & UNREACHABLE) != 0 || (otherInits.tagBits & UNREACHABLE) != 0 || (otherInits.tagBits & NULL_FLAG_MASK) == 0) { return this; } // if we get here, otherInits has some null info boolean thisHadNulls = (this.tagBits & NULL_FLAG_MASK) != 0, thisHasNulls = false; long a1, a2, a3, a4, na1, na2, na3, na4, b1, b2, b3, b4, nb1, nb2, nb3, nb4; if (thisHadNulls) { this.nullBit1 = (a1 = this.nullBit1) & ((a3 = this.nullBit3) & (a4 = this.nullBit4) & ((nb2 = ~(b2 = otherInits.nullBit2)) & (nb4 = ~(b4 = otherInits.nullBit4)) | (b1 = otherInits.nullBit1) & (b3 = otherInits.nullBit3)) | (na2 = ~(a2 = this.nullBit2)) & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2) | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2))); this.nullBit2 = b2 & (nb3 | (nb1 = ~b1)) | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1)); this.nullBit3 = b3 & (nb1 & b2 | a2 & (nb2 | a3) | na1 & nb2 | a1 & na2 & na4 & b1) | a3 & (nb2 & nb4 | na2 & a4 | na1) | a1 & na2 & na4 & b2; this.nullBit4 = na3 & (nb1 & nb3 & b4 | a4 & (nb3 | b1 & b2)) | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4)) | a3 & (a4 & (nb2 | b1 & b3) | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3)); if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 9) { this.nullBit4 = ~0; } } if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant thisHasNulls = true; } } else { this.nullBit1 = 0; this.nullBit2 = (b2 = otherInits.nullBit2) & ((nb3 = ~(b3 = otherInits.nullBit3)) | (nb1 = ~(b1 = otherInits.nullBit1))); this.nullBit3 = b3 & (nb1 | (nb2 = ~b2)); this.nullBit4 = ~b1 & ~b3 & (b4 = otherInits.nullBit4) | ~b2 & (b1 & ~b3 | ~b1 & b4); if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 10) { this.nullBit4 = ~0; } } if ((this.nullBit2 | this.nullBit3 | this.nullBit4) != 0) { // bit1 is redundant thisHasNulls = true; } } // extra storage management if (otherInits.extra != null) { int mergeLimit = 0, copyLimit = otherInits.extra[0].length; if (this.extra == null) { this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[copyLimit]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 11) { throw new AssertionFailedException("COVERAGE 11"); //$NON-NLS-1$ } } } else { mergeLimit = copyLimit; if (mergeLimit > this.extra[0].length) { mergeLimit = this.extra[0].length; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, this.extra[j] = new long[copyLimit], 0, mergeLimit); } if (! thisHadNulls) { mergeLimit = 0; // will do with a copy -- caveat: only valid because definite assignment bits copied above if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 12) { throw new AssertionFailedException("COVERAGE 12"); //$NON-NLS-1$ } } } } } // PREMATURE skip operations for fields int i; for (i = 0 ; i < mergeLimit ; i++) { this.extra[1 + 1][i] = (a1 = this.extra[1 + 1][i]) & ((a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & ((nb2 = ~(b2 = otherInits.extra[2 + 1][i])) & (nb4 = ~(b4 = otherInits.extra[4 + 1][i])) | (b1 = otherInits.extra[1 + 1][i]) & (b3 = otherInits.extra[3 + 1][i])) | (na2 = ~(a2 = this.extra[2 + 1][i])) & (b1 & b3 | ((na4 = ~a4) | (na3 = ~a3)) & nb2) | a2 & ((na4 | na3) & ((nb3 = ~b3) & nb4 | b1 & b2))); this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1)) | a2 & (nb3 & nb4 | b2 | na3 | (na1 = ~a1)); this.extra[3 + 1][i] = b3 & (nb1 & b2 | a2 & (nb2 | a3) | na1 & nb2 | a1 & na2 & na4 & b1) | a3 & (nb2 & nb4 | na2 & a4 | na1) | a1 & na2 & na4 & b2; this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4 | a4 & (nb3 | b1 & b2)) | nb2 & (na3 & b1 & nb3 | na2 & (nb1 & b4 | b1 & nb3 | a4)) | a3 & (a4 & (nb2 | b1 & b3) | a1 & a2 & (nb1 & b4 | na4 & (b2 | b1) & nb3)); if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant thisHasNulls = true; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 13) { this.nullBit4 = ~0; } } } for (; i < copyLimit; i++) { this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i]) & ((nb3 = ~(b3 = otherInits.extra[3 + 1][i])) | (nb1 = ~(b1 = otherInits.extra[1 + 1][i]))); this.extra[3 + 1][i] = b3 & (nb1 | (nb2 = ~b2)); this.extra[4 + 1][i] = ~b1 & ~b3 & (b4 = otherInits.extra[4 + 1][i]) | ~b2 & (b1 & ~b3 | ~b1 & b4); if ((this.extra[2 + 1][i] | this.extra[3 + 1][i] | this.extra[4 + 1][i]) != 0) { // bit1 is redundant thisHasNulls = true; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 14) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); if (thisHasNulls) { this.tagBits |= NULL_FLAG_MASK; } else { this.tagBits &= NULL_FLAG_MASK; } return this; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
protected static boolean isTrue(boolean expression, String message) { if (!expression) throw new AssertionFailedException("assertion failed: " + message); //$NON-NLS-1$ return expression; }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public void markAsComparedEqualToNonNull(LocalVariableBinding local) { // protected from non-object locals in calling methods if (this != DEAD_END) { this.tagBits |= NULL_FLAG_MASK; int position; long mask; long a1, a2, a3, a4, na2; // position is zero-based if ((position = local.id + this.maxFieldCount) < BitCacheSize) { // use bits if (((mask = 1L << position) & (a1 = this.nullBit1) & (na2 = ~(a2 = this.nullBit2)) & ~(a3 = this.nullBit3) & (a4 = this.nullBit4)) != 0) { this.nullBit4 &= ~mask; } else if ((mask & a1 & na2 & a3) == 0) { this.nullBit4 |= mask; if ((mask & a1) == 0) { if ((mask & a2 & (a3 ^ a4)) != 0) { this.nullBit2 &= ~mask; } else if ((mask & (a2 | a3 | a4)) == 0) { this.nullBit2 |= mask; } } } this.nullBit1 |= mask; this.nullBit3 |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 15) { this.nullBit4 = ~0; } } } else { // use extra vector int vectorIndex = (position / BitCacheSize) - 1; if (this.extra == null) { int length = vectorIndex + 1; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[length]; } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 16) { throw new AssertionFailedException("COVERAGE 16"); //$NON-NLS-1$ } } } else { int oldLength; if (vectorIndex >= (oldLength = this.extra[0].length)) { int newLength = vectorIndex + 1; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[newLength]), 0, oldLength); } if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 17) { throw new AssertionFailedException("COVERAGE 17"); //$NON-NLS-1$ } } } } // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][vectorIndex]/gc if (((mask = 1L << (position % BitCacheSize)) & (a1 = this.extra[1 + 1][vectorIndex]) & (na2 = ~(a2 = this.extra[2 + 1][vectorIndex])) & ~(a3 = this.extra[3 + 1][vectorIndex]) & (a4 = this.extra[4 + 1][vectorIndex])) != 0) { this.extra[4 + 1][vectorIndex] &= ~mask; } else if ((mask & a1 & na2 & a3) == 0) { this.extra[4 + 1][vectorIndex] |= mask; if ((mask & a1) == 0) { if ((mask & a2 & (a3 ^ a4)) != 0) { this.extra[2 + 1][vectorIndex] &= ~mask; } else if ((mask & (a2 | a3 | a4)) == 0) { this.extra[2 + 1][vectorIndex] |= mask; } } } this.extra[1 + 1][vectorIndex] |= mask; this.extra[3 + 1][vectorIndex] |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 18) { this.extra[5][vectorIndex] = ~0; } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public void markAsComparedEqualToNull(LocalVariableBinding local) { // protected from non-object locals in calling methods if (this != DEAD_END) { this.tagBits |= NULL_FLAG_MASK; int position; long mask; // position is zero-based if ((position = local.id + this.maxFieldCount) < BitCacheSize) { // use bits if (((mask = 1L << position) & this.nullBit1) != 0) { if ((mask & (~this.nullBit2 | this.nullBit3 | ~this.nullBit4)) != 0) { this.nullBit4 &= ~mask; } } else if ((mask & this.nullBit4) != 0) { this.nullBit3 &= ~mask; } else { if ((mask & this.nullBit2) != 0) { this.nullBit3 &= ~mask; this.nullBit4 |= mask; } else { this.nullBit3 |= mask; } } this.nullBit1 |= mask; this.nullBit2 |= mask; if (COVERAGE_TEST_FLAG) { if (CoverageTestId == 19) { this.nullBit4 = ~0; } } } else { // use extra vector int vectorIndex = (position / BitCacheSize) - 1; mask = 1L << (position % BitCacheSize); if (this.extra == null) { int length = vectorIndex + 1; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[length ]; } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 20) { throw new AssertionFailedException("COVERAGE 20"); //$NON-NLS-1$ } } } else { int oldLength; if (vectorIndex >= (oldLength = this.extra[0].length)) { int newLength = vectorIndex + 1; for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[newLength]), 0, oldLength); } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 21) { throw new AssertionFailedException("COVERAGE 21"); //$NON-NLS-1$ } } } } if ((mask & this.extra[1 + 1][vectorIndex]) != 0) { if ((mask & (~this.extra[2 + 1][vectorIndex] | this.extra[3 + 1][vectorIndex] | ~this.extra[4 + 1][vectorIndex])) != 0) { this.extra[4 + 1][vectorIndex] &= ~mask; } } else if ((mask & this.extra[4 + 1][vectorIndex]) != 0) { this.extra[3 + 1][vectorIndex] &= ~mask; } else { if ((mask & this.extra[2 + 1][vectorIndex]) != 0) { this.extra[3 + 1][vectorIndex] &= ~mask; this.extra[4 + 1][vectorIndex] |= mask; } else { this.extra[3 + 1][vectorIndex] |= mask; } } this.extra[1 + 1][vectorIndex] |= mask; this.extra[2 + 1][vectorIndex] |= mask; } } }
// in compiler/org/eclipse/jdt/internal/compiler/flow/UnconditionalFlowInfo.java
public UnconditionalFlowInfo mergedWith(UnconditionalFlowInfo otherInits) { if ((otherInits.tagBits & UNREACHABLE_OR_DEAD) != 0 && this != DEAD_END) { if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 28) { throw new AssertionFailedException("COVERAGE 28"); //$NON-NLS-1$ } } combineNullStatusChangeInAssertInfo(otherInits); return this; } if ((this.tagBits & UNREACHABLE_OR_DEAD) != 0) { if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 29) { throw new AssertionFailedException("COVERAGE 29"); //$NON-NLS-1$ } } otherInits.combineNullStatusChangeInAssertInfo(this); return (UnconditionalFlowInfo) otherInits.copy(); // make sure otherInits won't be affected } // intersection of definitely assigned variables, this.definiteInits &= otherInits.definiteInits; // union of potentially set ones this.potentialInits |= otherInits.potentialInits; // null combinations boolean thisHasNulls = (this.tagBits & NULL_FLAG_MASK) != 0, otherHasNulls = (otherInits.tagBits & NULL_FLAG_MASK) != 0, thisHadNulls = thisHasNulls; long a1, a2, a3, a4, na1, na2, na3, na4, nb1, nb2, nb3, nb4, b1, b2, b3, b4; if ((otherInits.tagBits & FlowInfo.UNREACHABLE_BY_NULLANALYSIS) != 0) { otherHasNulls = false; // skip merging, otherInits is unreachable by null analysis } else if ((this.tagBits & FlowInfo.UNREACHABLE_BY_NULLANALYSIS) != 0) { // directly copy if this is unreachable by null analysis this.nullBit1 = otherInits.nullBit1; this.nullBit2 = otherInits.nullBit2; this.nullBit3 = otherInits.nullBit3; this.nullBit4 = otherInits.nullBit4; thisHadNulls = false; thisHasNulls = otherHasNulls; this.tagBits = otherInits.tagBits; } else if (thisHadNulls) { if (otherHasNulls) { this.nullBit1 = (a2 = this.nullBit2) & (a3 = this.nullBit3) & (a4 = this.nullBit4) & (b1 = otherInits.nullBit1) & (nb2 = ~(b2 = otherInits.nullBit2)) | (a1 = this.nullBit1) & (b1 & (a3 & a4 & (b3 = otherInits.nullBit3) & (b4 = otherInits.nullBit4) | (na2 = ~a2) & nb2 & ((nb4 = ~b4) | (na4 = ~a4) | (na3 = ~a3) & (nb3 = ~b3)) | a2 & b2 & ((na4 | na3) & (nb4 | nb3))) | na2 & b2 & b3 & b4); this.nullBit2 = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4) | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1); this.nullBit3 = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4)) | a3 & (na2 & a4 | na1) | (a2 | na1) & b1 & nb2 & nb4 | a1 & na2 & na4 & (b2 | nb1); this.nullBit4 = na3 & (nb1 & nb3 & b4 | b1 & (nb2 & nb3 | a4 & b2 & nb4) | na1 & a4 & (nb3 | b1 & b2)) | a3 & a4 & (b3 & b4 | b1 & nb2) | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2 | a1 & (na3 & (nb3 & b4 | b1 & b2 & b3 & nb4 | na2 & (nb3 | nb2)) | na2 & b3 & b4 | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3); // the above formulae do not handle the state 0111, do it now explicitly: long ax = ~a1 & a2 & a3 & a4; long bx = ~b1 & b2 & b3 & b4; long x = ax|bx; if (x != 0) { // restore state 0111 for all variable ids in x: this.nullBit1 &= ~x; this.nullBit2 |= x; this.nullBit3 |= x; this.nullBit4 |= x; } if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 30) { this.nullBit4 = ~0; } } } else { // other has no null info a1 = this.nullBit1; this.nullBit1 = 0; this.nullBit2 = (a2 = this.nullBit2) & (na3 = ~(a3 = this.nullBit3) | (na1 = ~a1)); this.nullBit3 = a3 & ((na2 = ~a2) & (a4 = this.nullBit4) | na1) | a1 & na2 & ~a4; this.nullBit4 = (na3 | na2) & na1 & a4 | a1 & na3 & na2; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 31) { this.nullBit4 = ~0; } } } } else if (otherHasNulls) { // only other had nulls this.nullBit1 = 0; this.nullBit2 = (b2 = otherInits.nullBit2) & (nb3 = ~(b3 = otherInits.nullBit3) | (nb1 = ~(b1 = otherInits.nullBit1))); this.nullBit3 = b3 & ((nb2 = ~b2) & (b4 = otherInits.nullBit4) | nb1) | b1 & nb2 & ~b4; this.nullBit4 = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 32) { this.nullBit4 = ~0; } } thisHasNulls = // redundant with the three following ones this.nullBit2 != 0 || this.nullBit3 != 0 || this.nullBit4 != 0; } // treating extra storage if (this.extra != null || otherInits.extra != null) { int mergeLimit = 0, copyLimit = 0, resetLimit = 0; int i; if (this.extra != null) { if (otherInits.extra != null) { // both sides have extra storage int length, otherLength; if ((length = this.extra[0].length) < (otherLength = otherInits.extra[0].length)) { // current storage is shorter -> grow current for (int j = 0; j < extraLength; j++) { System.arraycopy(this.extra[j], 0, (this.extra[j] = new long[otherLength]), 0, length); } mergeLimit = length; copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 33) { throw new AssertionFailedException("COVERAGE 33"); //$NON-NLS-1$ } } } else { // current storage is longer mergeLimit = otherLength; resetLimit = length; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 34) { throw new AssertionFailedException("COVERAGE 34"); //$NON-NLS-1$ } } } } else { resetLimit = this.extra[0].length; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 35) { throw new AssertionFailedException("COVERAGE 35"); //$NON-NLS-1$ } } } } else if (otherInits.extra != null) { // no storage here, but other has extra storage. int otherLength = otherInits.extra[0].length; this.extra = new long[extraLength][]; for (int j = 0; j < extraLength; j++) { this.extra[j] = new long[otherLength]; } System.arraycopy(otherInits.extra[1], 0, this.extra[1], 0, otherLength); copyLimit = otherLength; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 36) { throw new AssertionFailedException("COVERAGE 36"); //$NON-NLS-1$ } } } // MACRO :'b,'es/nullBit\(.\)/extra[\1 + 1][i]/g // manage definite assignment for (i = 0; i < mergeLimit; i++) { this.extra[0][i] &= otherInits.extra[0][i]; this.extra[1][i] |= otherInits.extra[1][i]; } for (; i < copyLimit; i++) { this.extra[1][i] = otherInits.extra[1][i]; } for (; i < resetLimit; i++) { this.extra[0][i] = 0; } // refine null bits requirements if (!otherHasNulls) { if (resetLimit < mergeLimit) { resetLimit = mergeLimit; } copyLimit = 0; // no need to carry inexisting nulls mergeLimit = 0; } if (!thisHadNulls) { resetLimit = 0; // no need to reset anything } // compose nulls for (i = 0; i < mergeLimit; i++) { this.extra[1 + 1][i] = (a2 = this.extra[2 + 1][i]) & (a3 = this.extra[3 + 1][i]) & (a4 = this.extra[4 + 1][i]) & (b1 = otherInits.extra[1 + 1][i]) & (nb2 = ~(b2 = otherInits.extra[2 + 1][i])) | (a1 = this.extra[1 + 1][i]) & (b1 & (a3 & a4 & (b3 = otherInits.extra[3 + 1][i]) & (b4 = otherInits.extra[4 + 1][i]) | (na2 = ~a2) & nb2 & ((nb4 = ~b4) | (na4 = ~a4) | (na3 = ~a3) & (nb3 = ~b3)) | a2 & b2 & ((na4 | na3) & (nb4 | nb3))) | na2 & b2 & b3 & b4); this.extra[2 + 1][i] = b2 & (nb3 | (nb1 = ~b1) | a3 & (a4 | (na1 = ~a1)) & nb4) | a2 & (b2 | na4 & b3 & (b4 | nb1) | na3 | na1); this.extra[3 + 1][i] = b3 & (nb2 & b4 | nb1 | a3 & (na4 & nb4 | a4 & b4)) | a3 & (na2 & a4 | na1) | (a2 | na1) & b1 & nb2 & nb4 | a1 & na2 & na4 & (b2 | nb1); this.extra[4 + 1][i] = na3 & (nb1 & nb3 & b4 | b1 & (nb2 & nb3 | a4 & b2 & nb4) | na1 & a4 & (nb3 | b1 & b2)) | a3 & a4 & (b3 & b4 | b1 & nb2) | na2 & (nb1 & b4 | b1 & nb3 | na1 & a4) & nb2 | a1 & (na3 & (nb3 & b4 | b1 & b2 & b3 & nb4 | na2 & (nb3 | nb2)) | na2 & b3 & b4 | a2 & (nb1 & b4 | a3 & na4 & b1) & nb3); // the above formulae do not handle the state 0111, do it now explicitly: long ax = ~a1 & a2 & a3 & a4; long bx = ~b1 & b2 & b3 & b4; long x = ax|bx; if (x != 0) { // restore state 0111 for all variable ids in x: this.extra[2][i] &= ~x; this.extra[3][i] |= x; this.extra[4][i] |= x; this.extra[5][i] |= x; } thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0 ; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 37) { this.extra[5][i] = ~0; } } } for (; i < copyLimit; i++) { this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (b2 = otherInits.extra[2 + 1][i]) & (nb3 = ~(b3 = otherInits.extra[3 + 1][i]) | (nb1 = ~(b1 = otherInits.extra[1 + 1][i]))); this.extra[3 + 1][i] = b3 & ((nb2 = ~b2) & (b4 = otherInits.extra[4 + 1][i]) | nb1) | b1 & nb2 & ~b4; this.extra[4 + 1][i] = (nb3 | nb2) & nb1 & b4 | b1 & nb3 & nb2; thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 38) { this.extra[5][i] = ~0; } } } for (; i < resetLimit; i++) { a1 = this.extra[1 + 1][i]; this.extra[1 + 1][i] = 0; this.extra[2 + 1][i] = (a2 = this.extra[2 + 1][i]) & (na3 = ~(a3 = this.extra[3 + 1][i]) | (na1 = ~a1)); this.extra[3 + 1][i] = a3 & ((na2 = ~a2) & (a4 = this.extra[4 + 1][i]) | na1) | a1 & na2 & ~a4; this.extra[4 + 1][i] = (na3 | na2) & na1 & a4 | a1 & na3 & na2; thisHasNulls = thisHasNulls || this.extra[3][i] != 0 || this.extra[4][i] != 0 || this.extra[5][i] != 0; if (COVERAGE_TEST_FLAG) { if(CoverageTestId == 39) { this.extra[5][i] = ~0; } } } } combineNullStatusChangeInAssertInfo(otherInits); if (thisHasNulls) { this.tagBits |= NULL_FLAG_MASK; } else { this.tagBits &= ~NULL_FLAG_MASK; } return this; }
0 2
            
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
8
            
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (AssertionFailedException e) { // Catch the assertion failure and throw java model exception instead // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=55992 return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (ClasspathEntry.AssertionFailedException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_illegalEntryInClasspathFile, new String[] {javaProject.getElementName(), e.getMessage()})); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (ClasspathEntry.AssertionFailedException ase) { Util.log(ase, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
2
            
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
0
unknown (Lib) BackingStoreException 0 0 0 14
            
// in model/org/eclipse/jdt/internal/core/JavaCorePreferenceModifyListener.java
catch (BackingStoreException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e1) { // TODO (frederic) see if it's necessary to report this failure... }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(BackingStoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(BackingStoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e) { Util.log(e, "Could not save JavaCore preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (BackingStoreException e) { // ignore exception }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { projectOptions = new Hashtable(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // problem with pref store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // problem with pref store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (BackingStoreException e) { // fails silently }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while initializing user libraries"); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while flusing instance preferences"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while removing user library " + libName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (BackingStoreException e) { Util.log(e, "Exception while saving user library " + libName); //$NON-NLS-1$ }
0 0
unknown (Lib) BadLocationException 0 0 1
            
// in model/org/eclipse/jdt/internal/core/DocumentAdapter.java
public void replace(int offset, int length, String text) throws BadLocationException { super.replace(offset, length, text); this.buffer.replace(offset, length, text); }
14
            
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/SortElementsOperation.java
catch (BadLocationException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (BadLocationException e) { e.printStackTrace(); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (BadLocationException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { log(e); // bug in the formatter Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (BadLocationException e) { String errorMessage = Messages.bind(Messages.CaughtException, "BadLocationException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (BadLocationException e) { // can not happen return code; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (BadLocationException cannotHappen) { // can not happen }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/LineInformation.java
catch (BadLocationException e) { return -1; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/LineInformation.java
catch (BadLocationException e) { return -1; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { //JavaPlugin.log(e); // bug in the formatter Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
4
            
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
2
unknown (Lib) BadPositionCategoryException 0 0 0 2
            
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadPositionCategoryException cannotHappen) { // can not happen: category is correctly set up }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadPositionCategoryException cannotHappen) { // can not happen: category is correctly set up }
0 0
unknown (Lib) BuildException 6
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
public boolean execute() throws BuildException { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.usingJDTCompiler"), Project.MSG_VERBOSE); //$NON-NLS-1$ Commandline cmd = setupJavacCommand(); try { Class c = Class.forName(compilerClass); Constructor batchCompilerConstructor = c.getConstructor(new Class[] { PrintWriter.class, PrintWriter.class, Boolean.TYPE, Map.class}); Object batchCompilerInstance = batchCompilerConstructor.newInstance(new Object[] {new PrintWriter(System.out), new PrintWriter(System.err), Boolean.TRUE, this.customDefaultOptions}); Method compile = c.getMethod("compile", new Class[] {String[].class}); //$NON-NLS-1$ Object result = compile.invoke(batchCompilerInstance, new Object[] { cmd.getArguments()}); final boolean resultValue = ((Boolean) result).booleanValue(); if (!resultValue && this.logFileName != null) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.error.compilationFailed", this.logFileName)); //$NON-NLS-1$ } return resultValue; } catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ } catch (Exception ex) { throw new BuildException(ex); } }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
public void execute() throws BuildException { if (this.file == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.cannot.be.null")); //$NON-NLS-1$ } if (this.property == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.property.argument.cannot.be.null")); //$NON-NLS-1$ } try { boolean hasDebugAttributes = false; if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(this.file)) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } else { ZipFile jarFile = null; try { jarFile = new ZipFile(this.file); } catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ } for (Enumeration entries = jarFile.entries(); !hasDebugAttributes && entries.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entry.getName())) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, entry.getName(), IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } } } if (hasDebugAttributes) { getProject().setUserProperty(this.property, "has debug"); //$NON-NLS-1$ } } catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ } }
4
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
3
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
public boolean execute() throws BuildException { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.usingJDTCompiler"), Project.MSG_VERBOSE); //$NON-NLS-1$ Commandline cmd = setupJavacCommand(); try { Class c = Class.forName(compilerClass); Constructor batchCompilerConstructor = c.getConstructor(new Class[] { PrintWriter.class, PrintWriter.class, Boolean.TYPE, Map.class}); Object batchCompilerInstance = batchCompilerConstructor.newInstance(new Object[] {new PrintWriter(System.out), new PrintWriter(System.err), Boolean.TRUE, this.customDefaultOptions}); Method compile = c.getMethod("compile", new Class[] {String[].class}); //$NON-NLS-1$ Object result = compile.invoke(batchCompilerInstance, new Object[] { cmd.getArguments()}); final boolean resultValue = ((Boolean) result).booleanValue(); if (!resultValue && this.logFileName != null) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.error.compilationFailed", this.logFileName)); //$NON-NLS-1$ } return resultValue; } catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ } catch (Exception ex) { throw new BuildException(ex); } }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
protected Commandline setupJavacCommand() throws BuildException { Commandline cmd = new Commandline(); this.customDefaultOptions = new CompilerOptions().getMap(); Class javacClass = Javac.class; /* * Read in the compiler arguments first since we might need to modify * the classpath if any access rules were specified */ String [] compilerArgs = processCompilerArguments(javacClass); /* * This option is used to never exit at the end of the ant task. */ cmd.createArgument().setValue("-noExit"); //$NON-NLS-1$ if (this.bootclasspath != null) { cmd.createArgument().setValue("-bootclasspath"); //$NON-NLS-1$ if (this.bootclasspath.size() != 0) { /* * Set the bootclasspath for the Eclipse compiler. */ cmd.createArgument().setPath(this.bootclasspath); } else { cmd.createArgument().setValue(Util.EMPTY_STRING); } } /* * Eclipse compiler doesn't support -extdirs. * It is emulated using the classpath. We add extdirs entries after the * bootclasspath. */ if (this.extdirs != null) { cmd.createArgument().setValue("-extdirs"); //$NON-NLS-1$ cmd.createArgument().setPath(this.extdirs); } Path classpath = new Path(this.project); /* * The java runtime is already handled, so we simply want to retrieve the * ant runtime and the compile classpath. */ classpath.append(getCompileClasspath()); /* * Set the classpath for the Eclipse compiler. */ cmd.createArgument().setValue("-classpath"); //$NON-NLS-1$ createClasspathArgument(cmd, classpath); // For -sourcepath, use the "sourcepath" value if present. // Otherwise default to the "srcdir" value. Path sourcepath = null; // retrieve the method getSourcepath() using reflect // This is done to improve the compatibility to ant 1.5 Method getSourcepathMethod = null; try { getSourcepathMethod = javacClass.getMethod("getSourcepath", null); //$NON-NLS-1$ } catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) } Path compileSourcePath = null; if (getSourcepathMethod != null) { try { compileSourcePath = (Path) getSourcepathMethod.invoke(this.attributes, null); } catch (IllegalAccessException e) { // should never happen } catch (InvocationTargetException e) { // should never happen } } if (compileSourcePath != null) { sourcepath = compileSourcePath; } else { sourcepath = this.src; } cmd.createArgument().setValue("-sourcepath"); //$NON-NLS-1$ createClasspathArgument(cmd, sourcepath); final String javaVersion = JavaEnvUtils.getJavaVersion(); String memoryParameterPrefix = javaVersion.equals(JavaEnvUtils.JAVA_1_1) ? "-J-" : "-J-X";//$NON-NLS-1$//$NON-NLS-2$ if (this.memoryInitialSize != null) { if (!this.attributes.isForkedJavac()) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryInitialSize"), Project.MSG_WARN); //$NON-NLS-1$ } else { cmd.createArgument().setValue(memoryParameterPrefix + "ms" + this.memoryInitialSize); //$NON-NLS-1$ } } if (this.memoryMaximumSize != null) { if (!this.attributes.isForkedJavac()) { this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryMaximumSize"), Project.MSG_WARN); //$NON-NLS-1$ } else { cmd.createArgument().setValue(memoryParameterPrefix + "mx" + this.memoryMaximumSize); //$NON-NLS-1$ } } if (this.debug) { // retrieve the method getSourcepath() using reflect // This is done to improve the compatibility to ant 1.5 Method getDebugLevelMethod = null; try { getDebugLevelMethod = javacClass.getMethod("getDebugLevel", null); //$NON-NLS-1$ } catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x } String debugLevel = null; if (getDebugLevelMethod != null) { try { debugLevel = (String) getDebugLevelMethod.invoke(this.attributes, null); } catch (IllegalAccessException e) { // should never happen } catch (InvocationTargetException e) { // should never happen } } if (debugLevel != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.DO_NOT_GENERATE); if (debugLevel.length() != 0) { if (debugLevel.indexOf("vars") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } if (debugLevel.indexOf("lines") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } if (debugLevel.indexOf("source") != -1) {//$NON-NLS-1$ this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.GENERATE); } } } else { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.GENERATE); } } else { this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute , CompilerOptions.DO_NOT_GENERATE); } /* * Handle the nowarn option. If none, then we generate all warnings. */ if (this.attributes.getNowarn()) { // disable all warnings Object[] entries = this.customDefaultOptions.entrySet().toArray(); for (int i = 0, max = entries.length; i < max; i++) { Map.Entry entry = (Map.Entry) entries[i]; if (!(entry.getKey() instanceof String)) continue; if (!(entry.getValue() instanceof String)) continue; if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) { this.customDefaultOptions.put(entry.getKey(), CompilerOptions.IGNORE); } } this.customDefaultOptions.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING); if (this.deprecation) { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED); } } else if (this.deprecation) { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED); } else { this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED); this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED); } /* * destDir option. */ if (this.destDir != null) { cmd.createArgument().setValue("-d"); //$NON-NLS-1$ cmd.createArgument().setFile(this.destDir.getAbsoluteFile()); } /* * verbose option */ if (this.verbose) { cmd.createArgument().setValue("-verbose"); //$NON-NLS-1$ } /* * failnoerror option */ if (!this.attributes.getFailonerror()) { cmd.createArgument().setValue("-proceedOnError"); //$NON-NLS-1$ } /* * target option. */ if (this.target != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_TargetPlatform, this.target); } /* * source option */ String source = this.attributes.getSource(); if (source != null) { this.customDefaultOptions.put(CompilerOptions.OPTION_Source, source); } if (compilerArgs != null) { /* * Add extra argument on the command line */ final int length = compilerArgs.length; if (length != 0) { for (int i = 0, max = length; i < max; i++) { String arg = compilerArgs[i]; if (this.logFileName == null && "-log".equals(arg) && ((i + 1) < max)) { //$NON-NLS-1$ this.logFileName = compilerArgs[i + 1]; } cmd.createArgument().setValue(arg); } } } /* * encoding option. javac task encoding property must be the last encoding on the command * line as compiler arg might also specify an encoding. */ if (this.encoding != null) { cmd.createArgument().setValue("-encoding"); //$NON-NLS-1$ cmd.createArgument().setValue(this.encoding); } /* * Eclipse compiler doesn't have a -sourcepath option. This is * handled through the javac task that collects all source files in * srcdir option. */ logAndAddFilesToCompile(cmd); return cmd; }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
public void execute() throws BuildException { if (this.file == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.cannot.be.null")); //$NON-NLS-1$ } if (this.property == null) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.property.argument.cannot.be.null")); //$NON-NLS-1$ } try { boolean hasDebugAttributes = false; if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(this.file)) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } else { ZipFile jarFile = null; try { jarFile = new ZipFile(this.file); } catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ } for (Enumeration entries = jarFile.entries(); !hasDebugAttributes && entries.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entry.getName())) { IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, entry.getName(), IClassFileReader.ALL); hasDebugAttributes = checkClassFile(classFileReader); } } } if (hasDebugAttributes) { getProject().setUserProperty(this.property, "has debug"); //$NON-NLS-1$ } } catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ } }
0 0 0
unknown (Lib) ClassCastException 1
            
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void checkNewChild(ASTNode node, ASTNode newChild, boolean cycleCheck, Class nodeType) { if (newChild.ast != node.ast) { // new child is from a different AST throw new IllegalArgumentException(); } if (newChild.getParent() != null) { // new child currently has a different parent throw new IllegalArgumentException(); } if (cycleCheck && newChild == node.getRoot()) { // inserting new child would create a cycle throw new IllegalArgumentException(); } Class childClass = newChild.getClass(); if (nodeType != null && !nodeType.isAssignableFrom(childClass)) { // new child is not of the right type throw new ClassCastException(); } if ((newChild.typeAndFlags & PROTECT) != 0) { // new child node is protected => cannot be parented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } }
0 0 65
            
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (ClassCastException e){ // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_annotation = Alignment.M_NO_ALIGNMENT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_enum_constants = Alignment.NONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (ClassCastException e) { this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_resources_in_try = Alignment.M_NEXT_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.alignment_for_union_type_in_multicatch = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_annotation_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_anonymous_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_array_initializer = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_block = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_block_in_case = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_constructor_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_enum_constant = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_enum_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_method_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.continuation_indentation = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.continuation_indentation_for_array_initializer = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_after_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_after_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_field = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_first_class_body_declaration = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_member_type = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_method = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_new_chunk = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_before_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_between_import_groups = 1; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_between_type_declarations = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.blank_lines_at_beginning_of_method_body = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.comment_line_length = 80; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.indentation_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.number_of_empty_lines_to_preserve = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.tab_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch(ClassCastException e) { this.page_width = 80; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ClassCastException e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ClassCastException e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/FieldBinding.java
catch (ClassCastException e) { return null; }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/MethodBinding.java
catch (ClassCastException e) { return null; }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
6
            
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
0
checked (Domain) ClassFormatException
public class ClassFormatException extends Exception {

	public static final int ERROR_MALFORMED_UTF8 = 1;
	public static final int ERROR_TRUNCATED_INPUT = 2;
	public static final int INVALID_CONSTANT_POOL_ENTRY = 3;
	public static final int TOO_MANY_BYTES = 4;
	public static final int INVALID_ARGUMENTS_FOR_INVOKEINTERFACE = 5;
	public static final int INVALID_BYTECODE = 6;

	/**
	 * @since 3.0
	 */
	public static final int INVALID_TAG_CONSTANT = 7;

	/**
	 * @since 3.0
	 */
	public static final int INVALID_MAGIC_NUMBER = 8;

	private static final long serialVersionUID = 6582900558320612988L; // backward compatible

	/**
	 * Constructor for ClassFormatException.
	 * @param errorID the given error ID
	 */
	public ClassFormatException(int errorID) {
		// TODO (olivier) what is the errorID?
	}

	/**
	 * Constructor for ClassFormatException.
	 * @param message the message for the exception
	 */
	public ClassFormatException(String message) {
		super(message);
	}

	/**
	 * Constructor for ClassFormatException.
	 * @param message the message for the exception
	 * @param  cause  the cause of the exception
	 * @since 3.5
	 */
	public ClassFormatException(String message, Throwable cause) {
		super(message, cause);
	}
}public class ClassFormatException extends Exception {

	public static final int ErrBadMagic = 1;
	public static final int ErrBadMinorVersion = 2;
	public static final int ErrBadMajorVersion = 3;
	public static final int ErrBadConstantClass = 4;
	public static final int ErrBadConstantString = 5;
	public static final int ErrBadConstantNameAndType = 6;
	public static final int ErrBadConstantFieldRef = 7;
	public static final int ErrBadConstantMethodRef = 8;
	public static final int ErrBadConstantInterfaceMethodRef = 9;
	public static final int ErrBadConstantPoolIndex = 10;
	public static final int ErrBadSuperclassName = 11;
	public static final int ErrInterfaceCannotBeFinal = 12;
	public static final int ErrInterfaceMustBeAbstract = 13;
	public static final int ErrBadModifiers = 14;
	public static final int ErrClassCannotBeAbstractFinal = 15;
	public static final int ErrBadClassname = 16;
	public static final int ErrBadFieldInfo = 17;
	public static final int ErrBadMethodInfo = 17;
	public static final int ErrEmptyConstantPool = 18;
	public static final int ErrMalformedUtf8 = 19;
	public static final int ErrUnknownConstantTag = 20;
	public static final int ErrTruncatedInput = 21;
	public static final int ErrMethodMustBeAbstract = 22;
	public static final int ErrMalformedAttribute = 23;
	public static final int ErrBadInterface = 24;
	public static final int ErrInterfaceMustSubclassObject = 25;
	public static final int ErrIncorrectInterfaceMethods = 26;
	public static final int ErrInvalidMethodName = 27;
	public static final int ErrInvalidMethodSignature = 28;

	private static final long serialVersionUID = 6667458511042774540L; // backward compatible

	private int errorCode;
	private int bufferPosition;
	private RuntimeException nestedException;
	private char[] fileName;

	public ClassFormatException(RuntimeException e, char[] fileName) {
		this.nestedException = e;
		this.fileName = fileName;
	}
	public ClassFormatException(int code) {
		this.errorCode = code;
	}
	public ClassFormatException(int code, int bufPos) {
		this.errorCode = code;
		this.bufferPosition = bufPos;
	}
	/**
	 * @return int
	 */
	public int getErrorCode() {
		return this.errorCode;
	}
	/**
	 * @return int
	 */
	public int getBufferPosition() {
		return this.bufferPosition;
	}
	/**
	 * Returns the underlying <code>Throwable</code> that caused the failure.
	 *
	 * @return the wrappered <code>Throwable</code>, or <code>null</code>
	 *         if the direct case of the failure was at the Java model layer
	 */
	public Throwable getException() {
		return this.nestedException;
	}
	public void printStackTrace() {
		printStackTrace(System.err);
	}
	/**
	 * Prints this exception's stack trace to the given print stream.
	 *
	 * @param output
	 *            the print stream
	 * @since 3.0
	 */
	public void printStackTrace(PrintStream output) {
		synchronized (output) {
			super.printStackTrace(output);
			Throwable throwable = getException();
			if (throwable != null) {
				if (this.fileName != null) {
					output.print("Caused in "); //$NON-NLS-1$
					output.print(this.fileName);
					output.print(" by: "); //$NON-NLS-1$
				} else {
					output.print("Caused by: "); //$NON-NLS-1$
				}
				throwable.printStackTrace(output);
			}
		}
	}
	/**
	 * Prints this exception's stack trace to the given print writer.
	 *
	 * @param output
	 *            the print writer
	 * @since 3.0
	 */
	public void printStackTrace(PrintWriter output) {
		synchronized (output) {
			super.printStackTrace(output);
			Throwable throwable = getException();
			if (throwable != null) {
				if (this.fileName != null) {
					output.print("Caused in "); //$NON-NLS-1$
					output.print(this.fileName);
					output.print(" by: "); //$NON-NLS-1$
				} else {
					output.print("Caused by: "); //$NON-NLS-1$
				}
				throwable.printStackTrace(output);
			}
		}
	}
}
69
            
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeFieldType(char[] signature) throws ClassFormatException { if (signature == null) return null; int arrayDim = 0; for (int i = 0, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[][] decodeParameterTypes(char[] signature, boolean firstIsSynthetic) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return null; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } char[][] parameterTypes = new char[3][]; int parameterTypesCounter = 0; int arrayDim = 0; for (int i = 1; i < indexOfClosingParen; i++) { if (parameterTypesCounter == parameterTypes.length) { // resize System.arraycopy(parameterTypes, 0, (parameterTypes = new char[parameterTypesCounter * 2][]), 0, parameterTypesCounter); } switch(signature[i]) { case 'B': parameterTypes[parameterTypesCounter++] = BYTE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'C': parameterTypes[parameterTypesCounter++] = CHAR; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'D': parameterTypes[parameterTypesCounter++] = DOUBLE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'F': parameterTypes[parameterTypesCounter++] = FLOAT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'I': parameterTypes[parameterTypesCounter++] = INT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'J': parameterTypes[parameterTypesCounter++] = LONG; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (firstIsSynthetic && parameterTypesCounter == 0) { // skip first synthetic parameter firstIsSynthetic = false; } else { parameterTypes[parameterTypesCounter++] = replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); } i = indexOfSemiColon; arrayDim = 0; break; case 'S': parameterTypes[parameterTypesCounter++] = SHORT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'Z': parameterTypes[parameterTypesCounter++] = BOOLEAN; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } if (parameterTypes.length != parameterTypesCounter) { System.arraycopy(parameterTypes, 0, parameterTypes = new char[parameterTypesCounter][], 0, parameterTypesCounter); } return parameterTypes; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeReturnType(char[] signature) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); int arrayDim = 0; for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private int extractArgCount(char[] signature, char[] className) throws ClassFormatException { int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return 0; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } int parameterTypesCounter = 0; for (int i = 1; i < indexOfClosingParen; i++) { switch(signature[i]) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': parameterTypesCounter++; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); // verify if first parameter is synthetic if (className != null && parameterTypesCounter == 0) { char[] classSignature = Signature.createCharArrayTypeSignature(className, true); int length = indexOfSemiColon-i+1; if (classSignature.length > (length+1)) { // synthetic means that parameter type has same signature than given class for (int j=i, k=0; j<indexOfSemiColon; j++, k++) { if (!(signature[j] == classSignature[k] || (signature[j] == '/' && classSignature[k] == '.' ))) { parameterTypesCounter++; break; } } } else { parameterTypesCounter++; } className = null; // do not verify following parameters } else { parameterTypesCounter++; } i = indexOfSemiColon; break; case '[': break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return parameterTypesCounter; }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, ClassFileBytesDisassembler.DEFAULT); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, mode); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/CodeAttribute.java
public void traverse(IBytecodeVisitor visitor) throws ClassFormatException { int pc = this.codeOffset; int opcode, index, _const, branchOffset; IConstantPoolEntry constantPoolEntry; while (true) { opcode = u1At(this.classFileBytes, 0, pc); switch(opcode) { case IOpcodeMnemonics.NOP : visitor._nop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ACONST_NULL : visitor._aconst_null(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_M1 : visitor._iconst_m1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_0 : visitor._iconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_1 : visitor._iconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_2 : visitor._iconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_3 : visitor._iconst_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_4 : visitor._iconst_4(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_5 : visitor._iconst_5(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_0 : visitor._lconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_1 : visitor._lconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_0 : visitor._fconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_1 : visitor._fconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_2 : visitor._fconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_0 : visitor._dconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_1 : visitor._dconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BIPUSH : visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); pc+=2; break; case IOpcodeMnemonics.SIPUSH : visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); pc+=3; break; case IOpcodeMnemonics.LDC : index = u1At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); pc+=2; break; case IOpcodeMnemonics.LDC_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.LDC2_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Long) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ILOAD : index = u1At(this.classFileBytes, 1, pc); visitor._iload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._lload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._fload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._dload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ALOAD : index = u1At(this.classFileBytes, 1, pc); visitor._aload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ILOAD_0 : visitor._iload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_1 : visitor._iload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_2 : visitor._iload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_3 : visitor._iload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_0 : visitor._lload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_1 : visitor._lload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_2 : visitor._lload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_3 : visitor._lload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_0 : visitor._fload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_1 : visitor._fload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_2 : visitor._fload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_3 : visitor._fload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_0 : visitor._dload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_1 : visitor._dload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_2 : visitor._dload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_3 : visitor._dload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_0 : visitor._aload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_1 : visitor._aload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_2 : visitor._aload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_3 : visitor._aload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IALOAD : visitor._iaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LALOAD : visitor._laload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FALOAD : visitor._faload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DALOAD : visitor._daload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AALOAD : visitor._aaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BALOAD : visitor._baload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CALOAD : visitor._caload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SALOAD : visitor._saload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE : index = u1At(this.classFileBytes, 1, pc); visitor._istore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._lstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._fstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._dstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ASTORE : index = u1At(this.classFileBytes, 1, pc); visitor._astore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ISTORE_0 : visitor._istore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_1 : visitor._istore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_2 : visitor._istore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_3 : visitor._istore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_0 : visitor._lstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_1 : visitor._lstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_2 : visitor._lstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_3 : visitor._lstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_0 : visitor._fstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_1 : visitor._fstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_2 : visitor._fstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_3 : visitor._fstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_0 : visitor._dstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_1 : visitor._dstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_2 : visitor._dstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_3 : visitor._dstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_0 : visitor._astore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_1 : visitor._astore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_2 : visitor._astore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_3 : visitor._astore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IASTORE : visitor._iastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LASTORE : visitor._lastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FASTORE : visitor._fastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DASTORE : visitor._dastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AASTORE : visitor._aastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BASTORE : visitor._bastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CASTORE : visitor._castore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SASTORE : visitor._sastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP : visitor._pop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP2 : visitor._pop2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP : visitor._dup(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X1 : visitor._dup_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X2 : visitor._dup_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2 : visitor._dup2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X1 : visitor._dup2_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X2 : visitor._dup2_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SWAP : visitor._swap(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IADD : visitor._iadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LADD : visitor._ladd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FADD : visitor._fadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DADD : visitor._dadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISUB : visitor._isub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSUB : visitor._lsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSUB : visitor._fsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSUB : visitor._dsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMUL : visitor._imul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LMUL : visitor._lmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FMUL : visitor._fmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DMUL : visitor._dmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IDIV : visitor._idiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LDIV : visitor._ldiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FDIV : visitor._fdiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DDIV : visitor._ddiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IREM : visitor._irem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LREM : visitor._lrem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FREM : visitor._frem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DREM : visitor._drem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.INEG : visitor._ineg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LNEG : visitor._lneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FNEG : visitor._fneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DNEG : visitor._dneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHL : visitor._ishl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHL : visitor._lshl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHR : visitor._ishr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHR : visitor._lshr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IUSHR : visitor._iushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LUSHR : visitor._lushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IAND : visitor._iand(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LAND : visitor._land(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IOR : visitor._ior(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LOR : visitor._lor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IXOR : visitor._ixor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LXOR : visitor._lxor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IINC : index = u1At(this.classFileBytes, 1, pc); _const = i1At(this.classFileBytes, 2, pc); visitor._iinc(pc - this.codeOffset, index, _const); pc+=3; break; case IOpcodeMnemonics.I2L : visitor._i2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2F : visitor._i2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2D : visitor._i2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2I : visitor._l2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2F : visitor._l2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2D : visitor._l2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2I : visitor._f2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2L : visitor._f2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2D : visitor._f2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2I : visitor._d2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2L : visitor._d2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2F : visitor._d2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2B : visitor._i2b(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2C : visitor._i2c(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2S : visitor._i2s(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCMP : visitor._lcmp(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPL : visitor._fcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPG : visitor._fcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPL : visitor._dcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPG : visitor._dcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IFEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._iflt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifle(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmplt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmple(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._goto(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.JSR : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._jsr(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.RET : index = u1At(this.classFileBytes, 1, pc); visitor._ret(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.TABLESWITCH : int startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 pc++; } int defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int low = i4At(this.classFileBytes, 0, pc); pc += 4; int high = i4At(this.classFileBytes, 0, pc); pc += 4; int length = high - low + 1; int[] jumpOffsets = new int[length]; for (int i = 0; i < length; i++) { jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); break; case IOpcodeMnemonics.LOOKUPSWITCH : startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { pc++; } defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int npairs = (int) u4At(this.classFileBytes, 0, pc); int[][] offset_pairs = new int[npairs][2]; pc += 4; for (int i = 0; i < npairs; i++) { offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); pc += 4; offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); break; case IOpcodeMnemonics.IRETURN : visitor._ireturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LRETURN : visitor._lreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FRETURN : visitor._freturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DRETURN : visitor._dreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ARETURN : visitor._areturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.RETURN : visitor._return(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.GETSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.GETFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEVIRTUAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESPECIAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEINTERFACE : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_InterfaceMethodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } byte count = (byte) u1At(this.classFileBytes, 3, pc); int extraArgs = u1At(this.classFileBytes, 4, pc); if (extraArgs != 0) { throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); } visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); pc += 5; break; case IOpcodeMnemonics.INVOKEDYNAMIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_NameAndType) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokedynamic( pc - this.codeOffset, index, this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoNameIndex()), this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoDescriptorIndex())); pc += 5; break; case IOpcodeMnemonics.NEW : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._new(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.NEWARRAY : int atype = u1At(this.classFileBytes, 1, pc); visitor._newarray(pc - this.codeOffset, atype); pc+=2; break; case IOpcodeMnemonics.ANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ARRAYLENGTH : visitor._arraylength(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ATHROW : visitor._athrow(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CHECKCAST : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INSTANCEOF : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.MONITORENTER : visitor._monitorenter(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.MONITOREXIT : visitor._monitorexit(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.WIDE : opcode = u1At(this.classFileBytes, 1, pc); if (opcode == IOpcodeMnemonics.IINC) { index = u2At(this.classFileBytes, 2, pc); _const = i2At(this.classFileBytes, 4, pc); visitor._wide(pc - this.codeOffset, opcode, index, _const); pc += 6; } else { index = u2At(this.classFileBytes, 2, pc); visitor._wide(pc - this.codeOffset , opcode, index); pc += 4; } break; case IOpcodeMnemonics.MULTIANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } int dimensions = u1At(this.classFileBytes, 3, pc); visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); pc+=4; break; case IOpcodeMnemonics.IFNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNONNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnonnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._goto_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.JSR_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._jsr_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.BREAKPOINT : visitor._breakpoint(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP1 : visitor._impdep1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP2 : visitor._impdep2(pc - this.codeOffset); pc++; break; default: throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); } if (pc >= (this.codeLength + this.codeOffset)) { break; } } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/FieldInfo.java
public void throwFormatException() throws ClassFormatException { throw new ClassFormatException(ClassFormatException.ErrBadFieldInfo); }
4
            
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
54
            
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeFieldType(char[] signature) throws ClassFormatException { if (signature == null) return null; int arrayDim = 0; for (int i = 0, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[][] decodeParameterTypes(char[] signature, boolean firstIsSynthetic) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return null; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } char[][] parameterTypes = new char[3][]; int parameterTypesCounter = 0; int arrayDim = 0; for (int i = 1; i < indexOfClosingParen; i++) { if (parameterTypesCounter == parameterTypes.length) { // resize System.arraycopy(parameterTypes, 0, (parameterTypes = new char[parameterTypesCounter * 2][]), 0, parameterTypesCounter); } switch(signature[i]) { case 'B': parameterTypes[parameterTypesCounter++] = BYTE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'C': parameterTypes[parameterTypesCounter++] = CHAR; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'D': parameterTypes[parameterTypesCounter++] = DOUBLE; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'F': parameterTypes[parameterTypesCounter++] = FLOAT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'I': parameterTypes[parameterTypesCounter++] = INT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'J': parameterTypes[parameterTypesCounter++] = LONG; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (firstIsSynthetic && parameterTypesCounter == 0) { // skip first synthetic parameter firstIsSynthetic = false; } else { parameterTypes[parameterTypesCounter++] = replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); } i = indexOfSemiColon; arrayDim = 0; break; case 'S': parameterTypes[parameterTypesCounter++] = SHORT; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case 'Z': parameterTypes[parameterTypesCounter++] = BOOLEAN; if (arrayDim > 0) convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim); arrayDim = 0; break; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } if (parameterTypes.length != parameterTypesCounter) { System.arraycopy(parameterTypes, 0, parameterTypes = new char[parameterTypesCounter][], 0, parameterTypesCounter); } return parameterTypes; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private char[] decodeReturnType(char[] signature) throws ClassFormatException { if (signature == null) return null; int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); int arrayDim = 0; for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) { switch(signature[i]) { case 'B': if (arrayDim > 0) return convertToArrayType(BYTE, arrayDim); return BYTE; case 'C': if (arrayDim > 0) return convertToArrayType(CHAR, arrayDim); return CHAR; case 'D': if (arrayDim > 0) return convertToArrayType(DOUBLE, arrayDim); return DOUBLE; case 'F': if (arrayDim > 0) return convertToArrayType(FLOAT, arrayDim); return FLOAT; case 'I': if (arrayDim > 0) return convertToArrayType(INT, arrayDim); return INT; case 'J': if (arrayDim > 0) return convertToArrayType(LONG, arrayDim); return LONG; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); if (arrayDim > 0) { return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim); } return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)); case 'S': if (arrayDim > 0) return convertToArrayType(SHORT, arrayDim); return SHORT; case 'Z': if (arrayDim > 0) return convertToArrayType(BOOLEAN, arrayDim); return BOOLEAN; case 'V': return VOID; case '[': arrayDim++; break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private int extractArgCount(char[] signature, char[] className) throws ClassFormatException { int indexOfClosingParen = CharOperation.lastIndexOf(')', signature); if (indexOfClosingParen == 1) { // there is no parameter return 0; } if (indexOfClosingParen == -1) { throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } int parameterTypesCounter = 0; for (int i = 1; i < indexOfClosingParen; i++) { switch(signature[i]) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': parameterTypesCounter++; break; case 'L': int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1); if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); // verify if first parameter is synthetic if (className != null && parameterTypesCounter == 0) { char[] classSignature = Signature.createCharArrayTypeSignature(className, true); int length = indexOfSemiColon-i+1; if (classSignature.length > (length+1)) { // synthetic means that parameter type has same signature than given class for (int j=i, k=0; j<indexOfSemiColon; j++, k++) { if (!(signature[j] == classSignature[k] || (signature[j] == '/' && classSignature[k] == '.' ))) { parameterTypesCounter++; break; } } } else { parameterTypesCounter++; } className = null; // do not verify following parameters } else { parameterTypesCounter++; } i = indexOfSemiColon; break; case '[': break; default: throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature); } } return parameterTypesCounter; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
private void extractReferenceFromConstantPool(byte[] contents, ClassFileReader reader) throws ClassFormatException { int[] constantPoolOffsets = reader.getConstantPoolOffsets(); int constantPoolCount = constantPoolOffsets.length; for (int i = 1; i < constantPoolCount; i++) { int tag = reader.u1At(constantPoolOffsets[i]); /** * u1 tag * u2 class_index * u2 name_and_type_index */ char[] name = null; char[] type = null; switch (tag) { case ClassFileConstants.FieldRefTag : // add reference to the class/interface and field name and type name = extractName(constantPoolOffsets, reader, i); addFieldReference(name); break; case ClassFileConstants.MethodRefTag : // add reference to the class and method name and type case ClassFileConstants.InterfaceMethodRefTag : // add reference to the interface and method name and type name = extractName(constantPoolOffsets, reader, i); type = extractType(constantPoolOffsets, reader, i); if (CharOperation.equals(INIT, name)) { // get class name and see if it's a local type or not char[] className = extractClassName(constantPoolOffsets, reader, i); boolean localType = false; if (className != null) { for (int c = 0, max = className.length; c < max; c++) { switch (className[c]) { case '/': className[c] = '.'; break; case '$': localType = true; break; } } } // add a constructor reference, use class name to extract arg count if it's a local type to remove synthetic parameter addConstructorReference(className, extractArgCount(type, localType?className:null)); } else { // add a method reference addMethodReference(name, extractArgCount(type, null)); } break; case ClassFileConstants.ClassTag : // add a type reference name = extractClassReference(constantPoolOffsets, reader, i); if (name.length > 0 && name[0] == '[') break; // skip over array references name = replace('/', '.', name); // so that it looks like java.lang.String addTypeReference(name); // also add a simple reference on each segment of the qualification (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24741) char[][] qualification = CharOperation.splitOn('.', name); for (int j = 0, length = qualification.length; j < length; j++) { addNameReference(qualification[j]); } break; } } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, ClassFileBytesDisassembler.DEFAULT); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
public String disassemble(byte[] classFileBytes, String lineSeparator, int mode) throws ClassFormatException { try { return disassemble(new ClassFileReader(classFileBytes, IClassFileReader.ALL), lineSeparator, mode); } catch (ArrayIndexOutOfBoundsException e) { throw new ClassFormatException(e.getMessage(), e); } }
// in model/org/eclipse/jdt/internal/core/util/CodeAttribute.java
public void traverse(IBytecodeVisitor visitor) throws ClassFormatException { int pc = this.codeOffset; int opcode, index, _const, branchOffset; IConstantPoolEntry constantPoolEntry; while (true) { opcode = u1At(this.classFileBytes, 0, pc); switch(opcode) { case IOpcodeMnemonics.NOP : visitor._nop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ACONST_NULL : visitor._aconst_null(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_M1 : visitor._iconst_m1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_0 : visitor._iconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_1 : visitor._iconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_2 : visitor._iconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_3 : visitor._iconst_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_4 : visitor._iconst_4(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ICONST_5 : visitor._iconst_5(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_0 : visitor._lconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCONST_1 : visitor._lconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_0 : visitor._fconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_1 : visitor._fconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCONST_2 : visitor._fconst_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_0 : visitor._dconst_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCONST_1 : visitor._dconst_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BIPUSH : visitor._bipush(pc - this.codeOffset, (byte) i1At(this.classFileBytes, 1, pc)); pc+=2; break; case IOpcodeMnemonics.SIPUSH : visitor._sipush(pc - this.codeOffset, (short) i2At(this.classFileBytes, 1, pc)); pc+=3; break; case IOpcodeMnemonics.LDC : index = u1At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc(pc - this.codeOffset, index, constantPoolEntry); pc+=2; break; case IOpcodeMnemonics.LDC_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Float && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Integer && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_String && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.LDC2_W : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Double && constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Long) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._ldc2_w(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ILOAD : index = u1At(this.classFileBytes, 1, pc); visitor._iload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._lload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._fload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DLOAD : index = u1At(this.classFileBytes, 1, pc); visitor._dload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ALOAD : index = u1At(this.classFileBytes, 1, pc); visitor._aload(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ILOAD_0 : visitor._iload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_1 : visitor._iload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_2 : visitor._iload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ILOAD_3 : visitor._iload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_0 : visitor._lload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_1 : visitor._lload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_2 : visitor._lload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LLOAD_3 : visitor._lload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_0 : visitor._fload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_1 : visitor._fload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_2 : visitor._fload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FLOAD_3 : visitor._fload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_0 : visitor._dload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_1 : visitor._dload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_2 : visitor._dload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DLOAD_3 : visitor._dload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_0 : visitor._aload_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_1 : visitor._aload_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_2 : visitor._aload_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ALOAD_3 : visitor._aload_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IALOAD : visitor._iaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LALOAD : visitor._laload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FALOAD : visitor._faload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DALOAD : visitor._daload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AALOAD : visitor._aaload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BALOAD : visitor._baload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CALOAD : visitor._caload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SALOAD : visitor._saload(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE : index = u1At(this.classFileBytes, 1, pc); visitor._istore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.LSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._lstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.FSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._fstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.DSTORE : index = u1At(this.classFileBytes, 1, pc); visitor._dstore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ASTORE : index = u1At(this.classFileBytes, 1, pc); visitor._astore(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.ISTORE_0 : visitor._istore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_1 : visitor._istore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_2 : visitor._istore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISTORE_3 : visitor._istore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_0 : visitor._lstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_1 : visitor._lstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_2 : visitor._lstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSTORE_3 : visitor._lstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_0 : visitor._fstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_1 : visitor._fstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_2 : visitor._fstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSTORE_3 : visitor._fstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_0 : visitor._dstore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_1 : visitor._dstore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_2 : visitor._dstore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSTORE_3 : visitor._dstore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_0 : visitor._astore_0(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_1 : visitor._astore_1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_2 : visitor._astore_2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ASTORE_3 : visitor._astore_3(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IASTORE : visitor._iastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LASTORE : visitor._lastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FASTORE : visitor._fastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DASTORE : visitor._dastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.AASTORE : visitor._aastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.BASTORE : visitor._bastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CASTORE : visitor._castore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SASTORE : visitor._sastore(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP : visitor._pop(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.POP2 : visitor._pop2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP : visitor._dup(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X1 : visitor._dup_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP_X2 : visitor._dup_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2 : visitor._dup2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X1 : visitor._dup2_x1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DUP2_X2 : visitor._dup2_x2(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.SWAP : visitor._swap(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IADD : visitor._iadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LADD : visitor._ladd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FADD : visitor._fadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DADD : visitor._dadd(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISUB : visitor._isub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSUB : visitor._lsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FSUB : visitor._fsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DSUB : visitor._dsub(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMUL : visitor._imul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LMUL : visitor._lmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FMUL : visitor._fmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DMUL : visitor._dmul(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IDIV : visitor._idiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LDIV : visitor._ldiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FDIV : visitor._fdiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DDIV : visitor._ddiv(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IREM : visitor._irem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LREM : visitor._lrem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FREM : visitor._frem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DREM : visitor._drem(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.INEG : visitor._ineg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LNEG : visitor._lneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FNEG : visitor._fneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DNEG : visitor._dneg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHL : visitor._ishl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHL : visitor._lshl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ISHR : visitor._ishr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LSHR : visitor._lshr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IUSHR : visitor._iushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LUSHR : visitor._lushr(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IAND : visitor._iand(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LAND : visitor._land(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IOR : visitor._ior(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LOR : visitor._lor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IXOR : visitor._ixor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LXOR : visitor._lxor(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IINC : index = u1At(this.classFileBytes, 1, pc); _const = i1At(this.classFileBytes, 2, pc); visitor._iinc(pc - this.codeOffset, index, _const); pc+=3; break; case IOpcodeMnemonics.I2L : visitor._i2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2F : visitor._i2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2D : visitor._i2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2I : visitor._l2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2F : visitor._l2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.L2D : visitor._l2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2I : visitor._f2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2L : visitor._f2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.F2D : visitor._f2d(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2I : visitor._d2i(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2L : visitor._d2l(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.D2F : visitor._d2f(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2B : visitor._i2b(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2C : visitor._i2c(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.I2S : visitor._i2s(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LCMP : visitor._lcmp(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPL : visitor._fcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FCMPG : visitor._fcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPL : visitor._dcmpl(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DCMPG : visitor._dcmpg(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IFEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._iflt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifle(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmplt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpge(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPGT : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmpgt(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ICMPLE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_icmple(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPEQ : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpeq(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IF_ACMPNE : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._if_acmpne(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._goto(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.JSR : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._jsr(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.RET : index = u1At(this.classFileBytes, 1, pc); visitor._ret(pc - this.codeOffset, index); pc+=2; break; case IOpcodeMnemonics.TABLESWITCH : int startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { // faster than % 4 pc++; } int defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int low = i4At(this.classFileBytes, 0, pc); pc += 4; int high = i4At(this.classFileBytes, 0, pc); pc += 4; int length = high - low + 1; int[] jumpOffsets = new int[length]; for (int i = 0; i < length; i++) { jumpOffsets[i] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._tableswitch(startpc - this.codeOffset, defaultOffset, low, high, jumpOffsets); break; case IOpcodeMnemonics.LOOKUPSWITCH : startpc = pc; pc++; while (((pc - this.codeOffset) & 0x03) != 0) { pc++; } defaultOffset = i4At(this.classFileBytes, 0, pc); pc += 4; int npairs = (int) u4At(this.classFileBytes, 0, pc); int[][] offset_pairs = new int[npairs][2]; pc += 4; for (int i = 0; i < npairs; i++) { offset_pairs[i][0] = i4At(this.classFileBytes, 0, pc); pc += 4; offset_pairs[i][1] = i4At(this.classFileBytes, 0, pc); pc += 4; } visitor._lookupswitch(startpc - this.codeOffset, defaultOffset, npairs, offset_pairs); break; case IOpcodeMnemonics.IRETURN : visitor._ireturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.LRETURN : visitor._lreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.FRETURN : visitor._freturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.DRETURN : visitor._dreturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ARETURN : visitor._areturn(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.RETURN : visitor._return(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.GETSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTSTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putstatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.GETFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._getfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.PUTFIELD : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Fieldref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._putfield(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEVIRTUAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokevirtual(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESPECIAL : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokespecial(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKESTATIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Methodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokestatic(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INVOKEINTERFACE : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_InterfaceMethodref) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } byte count = (byte) u1At(this.classFileBytes, 3, pc); int extraArgs = u1At(this.classFileBytes, 4, pc); if (extraArgs != 0) { throw new ClassFormatException(ClassFormatException.INVALID_ARGUMENTS_FOR_INVOKEINTERFACE); } visitor._invokeinterface(pc - this.codeOffset, index, count, constantPoolEntry); pc += 5; break; case IOpcodeMnemonics.INVOKEDYNAMIC : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_NameAndType) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._invokedynamic( pc - this.codeOffset, index, this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoNameIndex()), this.constantPool.decodeEntry(constantPoolEntry.getNameAndTypeInfoDescriptorIndex())); pc += 5; break; case IOpcodeMnemonics.NEW : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._new(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.NEWARRAY : int atype = u1At(this.classFileBytes, 1, pc); visitor._newarray(pc - this.codeOffset, atype); pc+=2; break; case IOpcodeMnemonics.ANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._anewarray(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.ARRAYLENGTH : visitor._arraylength(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.ATHROW : visitor._athrow(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.CHECKCAST : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._checkcast(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.INSTANCEOF : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } visitor._instanceof(pc - this.codeOffset, index, constantPoolEntry); pc+=3; break; case IOpcodeMnemonics.MONITORENTER : visitor._monitorenter(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.MONITOREXIT : visitor._monitorexit(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.WIDE : opcode = u1At(this.classFileBytes, 1, pc); if (opcode == IOpcodeMnemonics.IINC) { index = u2At(this.classFileBytes, 2, pc); _const = i2At(this.classFileBytes, 4, pc); visitor._wide(pc - this.codeOffset, opcode, index, _const); pc += 6; } else { index = u2At(this.classFileBytes, 2, pc); visitor._wide(pc - this.codeOffset , opcode, index); pc += 4; } break; case IOpcodeMnemonics.MULTIANEWARRAY : index = u2At(this.classFileBytes, 1, pc); constantPoolEntry = this.constantPool.decodeEntry(index); if (constantPoolEntry.getKind() != IConstantPoolConstant.CONSTANT_Class) { throw new ClassFormatException(ClassFormatException.INVALID_CONSTANT_POOL_ENTRY); } int dimensions = u1At(this.classFileBytes, 3, pc); visitor._multianewarray(pc - this.codeOffset, index, dimensions, constantPoolEntry); pc+=4; break; case IOpcodeMnemonics.IFNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.IFNONNULL : branchOffset = i2At(this.classFileBytes, 1, pc); visitor._ifnonnull(pc - this.codeOffset , branchOffset); pc+=3; break; case IOpcodeMnemonics.GOTO_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._goto_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.JSR_W : branchOffset = i4At(this.classFileBytes, 1, pc); visitor._jsr_w(pc - this.codeOffset, branchOffset); pc+=5; break; case IOpcodeMnemonics.BREAKPOINT : visitor._breakpoint(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP1 : visitor._impdep1(pc - this.codeOffset); pc++; break; case IOpcodeMnemonics.IMPDEP2 : visitor._impdep2(pc - this.codeOffset); pc++; break; default: throw new ClassFormatException(ClassFormatException.INVALID_BYTECODE); } if (pc >= (this.codeLength + this.codeOffset)) { break; } } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file) throws ClassFormatException, IOException { return read(file, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getFileByteContent(file); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, file.getAbsolutePath().toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName) throws ClassFormatException, IOException { return read(stream, fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getInputStreamAsByteArray(stream, -1); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, fileName.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename) throws ClassFormatException, java.io.IOException { return read(zip, filename, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { java.util.zip.ZipEntry ze = zip.getEntry(filename); if (ze == null) return null; byte classFileBytes[] = Util.getZipEntryByteContent(ze, zip); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, filename.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName) throws ClassFormatException, java.io.IOException { return read(fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { return read(new File(fileName), fullyInitialize); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
private void initialize() throws ClassFormatException { try { for (int i = 0, max = this.fieldsCount; i < max; i++) { this.fields[i].initialize(); } for (int i = 0, max = this.methodsCount; i < max; i++) { this.methods[i].initialize(); } if (this.innerInfos != null) { for (int i = 0, max = this.innerInfos.length; i < max; i++) { this.innerInfos[i].initialize(); } } if (this.annotations != null) { for (int i = 0, max = this.annotations.length; i < max; i++) { this.annotations[i].initialize(); } } this.getEnclosingMethod(); reset(); } catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/FieldInfo.java
public void throwFormatException() throws ClassFormatException { throw new ClassFormatException(ClassFormatException.ErrBadFieldInfo); }
25
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type return null; }
// in eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (ClassFormatException e) { // treat as if file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch(ClassFormatException e) { // treat as if class file is missing }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (ClassFormatException e) { // invalid class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (ClassFormatException e) { //e.printStackTrace(); return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (ClassFormatException e) { // ignore this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown if (JavaCore.getPlugin().isDebugging()) { cfe.printStackTrace(System.err); } return null; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (ClassFormatException cfe) { //the structure remains unknown return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (ClassFormatException e) { // treat as if class file is missing }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(ClassFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Disassembler.java
catch(ClassFormatException e) { dumpTab(tabNumber + 2, buffer); buffer.append(Messages.classformat_classformatexception); writeNewLine(buffer, lineSeparator, tabNumber + 1); }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(ClassFormatException e) { return null; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (ClassFormatException e) { return true; }
2
            
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(ClassFormatException e) { throw e; }
0
unknown (Lib) ClassNotFoundException 0 0 0 3
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (ClassNotFoundException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (ClassNotFoundException e) { // ignored }
1
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (ClassNotFoundException cnfe) { throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$ }
0
unknown (Lib) CloneNotSupportedException 0 0 11
            
// in model/org/eclipse/jdt/internal/core/util/HashSetOfCharArrayArray.java
public Object clone() throws CloneNotSupportedException { HashSetOfCharArrayArray result = (HashSetOfCharArrayArray) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.set.length; result.set = new char[length][][]; System.arraycopy(this.set, 0, result.set, 0, length); return result; }
// in model/org/eclipse/jdt/internal/core/util/HashSetOfArray.java
public Object clone() throws CloneNotSupportedException { HashSetOfArray result = (HashSetOfArray) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.set.length; result.set = new Object[length][]; System.arraycopy(this.set, 0, result.set, 0, length); return result; }
// in model/org/eclipse/jdt/internal/core/util/HashtableOfArrayToObject.java
public Object clone() throws CloneNotSupportedException { HashtableOfArrayToObject result = (HashtableOfArrayToObject) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new Object[length][]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new Object[length]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/HashtableOfObjectToIntArray.java
public Object clone() throws CloneNotSupportedException { HashtableOfObjectToIntArray result = (HashtableOfObjectToIntArray) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new Object[length]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new int[length][]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/HashtableOfObjectToInt.java
public Object clone() throws CloneNotSupportedException { HashtableOfObjectToInt result = (HashtableOfObjectToInt) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new Object[length]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new int[length]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleLookupTable.java
public Object clone() throws CloneNotSupportedException { SimpleLookupTable result = (SimpleLookupTable) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new Object[length]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new Object[length]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/HashtableOfObject.java
public Object clone() throws CloneNotSupportedException { HashtableOfObject result = (HashtableOfObject) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new char[length][]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new Object[length]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/HashtableOfIntValues.java
public Object clone() throws CloneNotSupportedException { HashtableOfIntValues result = (HashtableOfIntValues) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.keyTable.length; result.keyTable = new char[length][]; System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); length = this.valueTable.length; result.valueTable = new int[length]; System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSetOfCharArray.java
public Object clone() throws CloneNotSupportedException { SimpleSetOfCharArray result = (SimpleSetOfCharArray) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.values.length; result.values = new char[length][]; System.arraycopy(this.values, 0, result.values, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/HashSetOfInt.java
public Object clone() throws CloneNotSupportedException { HashSetOfInt result = (HashSetOfInt) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.set.length; result.set = new int[length]; System.arraycopy(this.set, 0, result.set, 0, length); return result; }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSet.java
public Object clone() throws CloneNotSupportedException { SimpleSet result = (SimpleSet) super.clone(); result.elementSize = this.elementSize; result.threshold = this.threshold; int length = this.values.length; result.values = new Object[length]; System.arraycopy(this.values, 0, result.values, 0, length); return result; }
3
            
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (CloneNotSupportedException e1) { // ignore (implementation of HashtableOfArrayToObject supports cloning) }
// in model/org/eclipse/jdt/internal/core/builder/State.java
catch (CloneNotSupportedException e) { this.references = new SimpleLookupTable(lastState.references.elementSize); Object[] keyTable = lastState.references.keyTable; Object[] valueTable = lastState.references.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.references.put(keyTable[i], valueTable[i]); this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize); keyTable = lastState.typeLocators.keyTable; valueTable = lastState.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) if (keyTable[i] != null) this.typeLocators.put(keyTable[i], valueTable[i]); }
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
1
            
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
1
runtime (Domain) CompletionNodeFound
public class CompletionNodeFound extends RuntimeException {

	public ASTNode astNode;
	public Binding qualifiedBinding;
	public Scope scope;
	public boolean insideTypeAnnotation = false;

	private static final long serialVersionUID = 6981437684184091462L; // backward compatible

public CompletionNodeFound() {
	this(null, null, null, false); // we found a problem in the completion node
}
public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope) {
	this(astNode, qualifiedBinding, scope, false);
}
public CompletionNodeFound(ASTNode astNode, Binding qualifiedBinding, Scope scope, boolean insideTypeAnnotation) {
	this.astNode = astNode;
	this.qualifiedBinding = qualifiedBinding;
	this.scope = scope;
	this.insideTypeAnnotation = insideTypeAnnotation;
}
public CompletionNodeFound(ASTNode astNode, Scope scope) {
	this(astNode, null, scope, false);
}
public CompletionNodeFound(ASTNode astNode, Scope scope, boolean insideTypeAnnotation) {
	this(astNode, null, scope, insideTypeAnnotation);
}
}
51
            
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { if (this.fieldTypeCompletionNode != null) { throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope); } if(this.isCompletionNode) { throw new CompletionNodeFound(this, scope); } else { return super.getTypeBinding(scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java
public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { if (this.fieldTypeCompletionNode != null) { throw new CompletionNodeFound(this.fieldTypeCompletionNode, scope); } if(this.isCompletionNode) { throw new CompletionNodeFound(this, enclosingType, scope); } else { return super.resolveTypeEnclosing(scope, enclosingType); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java
public TypeBinding resolveType(BlockScope scope) { if (super.resolveType(scope) == null) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, this.targetType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodTypeParameter.java
public void resolveStatements() { throw new CompletionNodeFound(this, this.scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMessageSend.java
public TypeBinding resolveType(BlockScope scope) { if (this.arguments != null) { int argsLength = this.arguments.length; for (int a = argsLength; --a >= 0;) this.arguments[a].resolveType(scope); } if (this.receiver.isImplicitThis()) throw new CompletionNodeFound(this, null, scope); this.actualReceiverType = this.receiver.resolveType(scope); if (this.actualReceiverType == null || this.actualReceiverType.isBaseType()) throw new CompletionNodeFound(); if (this.actualReceiverType.isArrayType()) this.actualReceiverType = scope.getJavaLangObject(); throw new CompletionNodeFound(this, this.actualReceiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMemberAccess.java
public TypeBinding resolveType(BlockScope scope) { this.actualReceiverType = this.receiver.resolveType(scope); if ((this.actualReceiverType == null || !this.actualReceiverType.isValidBinding()) && this.receiver instanceof MessageSend) { MessageSend messageSend = (MessageSend) this.receiver; if(messageSend.receiver instanceof ThisReference) { Expression[] arguments = messageSend.arguments; int length = arguments == null ? 0 : arguments.length; TypeBinding[] argBindings = new TypeBinding[length]; for (int i = 0; i < length; i++) { argBindings[i] = arguments[i].resolvedType; if(argBindings[i] == null || !argBindings[i].isValidBinding()) { throw new CompletionNodeFound(); } } ProblemMethodBinding problemMethodBinding = new ProblemMethodBinding(messageSend.selector, argBindings, ProblemReasons.NotFound); throw new CompletionNodeFound(this, problemMethodBinding, scope); } } if (this.actualReceiverType == null || this.actualReceiverType.isBaseType() || !this.actualReceiverType.isValidBinding()) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, this.actualReceiverType, scope); // array types are passed along to find the length field }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.parent.getTypeOrPackage(this.tokens); // step up from the ClassScope if (!binding.isValidBinding()) { scope.problemReporter().invalidType(this, (TypeBinding) binding); if (binding.problemId() == ProblemReasons.NotFound) { throw new CompletionNodeFound(this, binding, scope); } throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, binding, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnArgumentName.java
public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { super.bind(scope, typeBinding, used); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnArgumentName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMarkerAnnotationName.java
public TypeBinding resolveType(BlockScope scope) { if(this.type instanceof QualifiedTypeReference) { QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) this.type; Binding binding = scope.parent.getTypeOrPackage(qualifiedTypeReference.tokens); // step up from the ClassScope if (!binding.isValidBinding()) { scope.problemReporter().invalidType(this, (TypeBinding) binding); throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, binding, scope); } throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnSingleNameReference.java
public TypeBinding resolveType(BlockScope scope) { if(scope instanceof MethodScope) { throw new CompletionNodeFound(this, scope, ((MethodScope)scope).insideTypeAnnotation); } throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodName.java
public void resolve(ClassScope upperScope) { super.resolve(upperScope); throw new CompletionNodeFound(this, upperScope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnStringLiteral.java
public TypeBinding resolveType(ClassScope scope) { throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnStringLiteral.java
public TypeBinding resolveType(BlockScope scope) { throw new CompletionNodeFound(this, null, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnFieldName.java
public void resolve(MethodScope initializationScope) { super.resolve(initializationScope); throw new CompletionNodeFound(this, initializationScope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnKeyword1.java
protected TypeBinding getTypeBinding(Scope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java
public TypeBinding resolveType(BlockScope scope) { // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.tokens, this); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } if (this.binding.problemId() == ProblemReasons.NotFound) { throw new CompletionNodeFound(this, this.binding, scope); } throw new CompletionNodeFound(); } throw new CompletionNodeFound(this, this.binding, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadoc.java
private void internalResolve(Scope scope) { if (this.completionNode != null) { if (this.completionNode instanceof CompletionOnJavadocTag) { ((CompletionOnJavadocTag)this.completionNode).filterPossibleTags(scope); } else { boolean resolve = true; if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { resolve = ((CompletionOnJavadocParamNameReference)this.completionNode).token != null; } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { resolve = ((CompletionOnJavadocTypeParamReference)this.completionNode).token != null; } if (resolve) { switch (scope.kind) { case Scope.CLASS_SCOPE: this.completionNode.resolveType((ClassScope)scope); break; case Scope.METHOD_SCOPE: this.completionNode.resolveType((MethodScope) scope); break; } } if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { CompletionOnJavadocParamNameReference paramNameReference = (CompletionOnJavadocParamNameReference) this.completionNode; if (scope.kind == Scope.METHOD_SCOPE) { paramNameReference.missingParams = missingParamTags(paramNameReference.binding, (MethodScope)scope); } if (paramNameReference.token == null || paramNameReference.token.length == 0) { paramNameReference.missingTypeParams = missingTypeParameterTags(paramNameReference.binding, scope); } } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { CompletionOnJavadocTypeParamReference typeParamReference = (CompletionOnJavadocTypeParamReference) this.completionNode; typeParamReference.missingParams = missingTypeParameterTags(typeParamReference.resolvedType, scope); } } Binding qualifiedBinding = null; if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference typeRef = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (typeRef.packageBinding == null) { qualifiedBinding = typeRef.resolvedType; } else { qualifiedBinding = typeRef.packageBinding; } } else if (this.completionNode instanceof CompletionOnJavadocMessageSend) { CompletionOnJavadocMessageSend msg = (CompletionOnJavadocMessageSend) this.completionNode; if (!msg.receiver.isThis()) qualifiedBinding = msg.receiver.resolvedType; } else if (this.completionNode instanceof CompletionOnJavadocAllocationExpression) { CompletionOnJavadocAllocationExpression alloc = (CompletionOnJavadocAllocationExpression) this.completionNode; qualifiedBinding = alloc.type.resolvedType; } throw new CompletionNodeFound(this.completionNode, qualifiedBinding, scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnBranchStatementLabel.java
public void resolve(BlockScope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnAnnotationMemberValuePair.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); if (this.resolvedType == null || !this.resolvedType.isValidBinding()) { throw new CompletionNodeFound(); } else { throw new CompletionNodeFound(this.completedMemberValuePair, scope); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMessageSendName.java
public TypeBinding resolveType(BlockScope scope) { if (this.receiver.isImplicitThis()) throw new CompletionNodeFound(); this.actualReceiverType = this.receiver.resolveType(scope); if (this.actualReceiverType == null || this.actualReceiverType.isBaseType() || this.actualReceiverType.isArrayType()) throw new CompletionNodeFound(); // resolve type arguments if (this.typeArguments != null) { int length = this.typeArguments.length; this.genericTypeArguments = new TypeBinding[length]; for (int i = 0; i < length; i++) { this.genericTypeArguments[i] = this.typeArguments[i].resolveType(scope, true /* check bounds*/); } } throw new CompletionNodeFound(this, this.actualReceiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnKeyword3.java
public TypeBinding resolveType(BlockScope scope) { throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java
public void resolve(BlockScope scope) { ReferenceBinding receiverType = scope.enclosingSourceType(); if (this.arguments != null) { int argsLength = this.arguments.length; for (int a = argsLength; --a >= 0;) this.arguments[a].resolveType(scope); } if (this.accessMode != This && receiverType != null) { if (receiverType.isHierarchyInconsistent()) throw new CompletionNodeFound(); receiverType = receiverType.superclass(); } if (receiverType == null) throw new CompletionNodeFound(); else throw new CompletionNodeFound(this, receiverType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; if (this.arguments != null) { int argsLength = this.arguments.length; int length = this.arguments.length; argumentTypes = new TypeBinding[length]; for (int a = argsLength; --a >= 0;) { argumentTypes[a] = this.arguments[a].resolveType(scope); } } final boolean isDiamond = this.type != null && (this.type.bits & ASTNode.IsDiamond) != 0; if (this.enclosingInstance != null) { TypeBinding enclosingType = this.enclosingInstance.resolveType(scope); if (enclosingType == null) { // try to propose something even if enclosing type cannot be resolved. // Eg.: new Test<>().new Test<>(#cursor# if (this.enclosingInstance instanceof AllocationExpression) { TypeReference enclosingInstanceType = ((AllocationExpression) this.enclosingInstance).type; if (enclosingInstanceType != null) { enclosingType = enclosingInstanceType.resolvedType; } } } if (enclosingType == null || !(enclosingType instanceof ReferenceBinding)) { throw new CompletionNodeFound(); } this.resolvedType = ((SingleTypeReference) this.type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingType); if (isDiamond && (this.resolvedType instanceof ParameterizedTypeBinding)) { TypeBinding [] inferredTypes = inferElidedTypes(((ParameterizedTypeBinding) this.resolvedType).genericType(), null, argumentTypes, scope); if (inferredTypes != null) { this.resolvedType = this.type.resolvedType = scope.environment().createParameterizedType(((ParameterizedTypeBinding) this.resolvedType).genericType(), inferredTypes, ((ParameterizedTypeBinding) this.resolvedType).enclosingType()); } else { // inference failed. Resolved type will be of the form Test<> this.bits |= ASTNode.IsDiamond; } } if (!(this.resolvedType instanceof ReferenceBinding)) throw new CompletionNodeFound(); // no need to continue if its an array or base type if (this.resolvedType.isInterface()) // handle the anonymous class definition case this.resolvedType = scope.getJavaLangObject(); } else { this.resolvedType = this.type.resolveType(scope, true /* check bounds*/); if (isDiamond && (this.resolvedType instanceof ParameterizedTypeBinding)) { TypeBinding [] inferredTypes = inferElidedTypes(((ParameterizedTypeBinding) this.resolvedType).genericType(), null, argumentTypes, scope); if (inferredTypes != null) { this.resolvedType = this.type.resolvedType = scope.environment().createParameterizedType(((ParameterizedTypeBinding) this.resolvedType).genericType(), inferredTypes, ((ParameterizedTypeBinding) this.resolvedType).enclosingType()); } else { // inference failed. Resolved type will be of the form Test<> this.bits |= ASTNode.IsDiamond; } } if (!(this.resolvedType instanceof ReferenceBinding)) throw new CompletionNodeFound(); // no need to continue if its an array or base type } throw new CompletionNodeFound(this, this.resolvedType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnMethodReturnType.java
public void resolveStatements() { throw new CompletionNodeFound(this, this.scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnLocalName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new CompletionNodeFound(this, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); throw new CompletionNodeFound(this, this.resolvedType, scope); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); throw new CompletionNodeFound(this, this.resolvedType, scope); }
0 0 4
            
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ System.out.println(e.astNode.toString()); if(this.parser.assistNodeParent != null) { System.out.print("COMPLETION - Parent Node : "); //$NON-NLS-1$ System.out.println(this.parser.assistNodeParent); } } this.lookupEnvironment.unitBeingCompleted = parsedUnit; // better resilient to further error reporting contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, parsedUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e) { // completionNodeFound = true; if (e.astNode != null) { // if null then we found a problem in the completion node contextAccepted = complete( e.astNode, this.parser.assistNodeParent, this.parser.enclosingNode, compilationUnit, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (CompletionNodeFound e){ // internal failure - bugs 5618 (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
0 0
unknown (Lib) CoreException 15
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void verifyArchiveContent(IPath path) throws CoreException { if (isInvalidArchive(path)) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); } ZipFile file = getZipFile(path); closeZipFile(file); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public ZipFile getZipFile(IPath path) throws CoreException { if (isInvalidArchive(path)) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); ZipCache zipCache; ZipFile zipFile; if ((zipCache = (ZipCache)this.zipFiles.get()) != null && (zipFile = zipCache.getCache(path)) != null) { return zipFile; } File localFile = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource file = root.findMember(path); if (file != null) { // internal resource URI location; if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } localFile = Util.toLocalFile(location, null/*no progress availaible*/); if (localFile == null) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } else { // external resource -> it is ok to use toFile() localFile= path.toFile(); } try { if (ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile ); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile = new ZipFile(localFile); if (zipCache != null) { zipCache.setCache(path, zipFile); } return zipFile; } catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveBuiltState(PerProjectInfo info) throws CoreException { if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_saveStateProgress, info.project.getName())); File file = getSerializationFile(info.project); if (file == null) return; long t = System.currentTimeMillis(); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { out.writeUTF(JavaCore.PLUGIN_ID); out.writeUTF("STATE"); //$NON-NLS-1$ if (info.savedState == null) { out.writeBoolean(false); } else { out.writeBoolean(true); JavaBuilder.writeState(info.savedState, out); } } finally { out.close(); } } catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } if (JavaBuilder.DEBUG) { t = System.currentTimeMillis() - t; System.out.println(Messages.bind(Messages.build_saveStateComplete, String.valueOf(t))); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathListCache(String cacheName) throws CoreException { File file = getClasspathListFile(cacheName); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Set pathCache = getClasspathListCache(cacheName); synchronized (pathCache) { out.writeInt(pathCache.size()); Iterator entries = pathCache.iterator(); while (entries.hasNext()) { IPath path = (IPath) entries.next(); out.writeUTF(path.toPortableString()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariablesAndContainers(ISaveContext context) throws CoreException { File file = getVariableAndContainersFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeInt(VARIABLES_AND_CONTAINERS_FILE_VERSION); new VariablesAndContainersSaveHelper(out).save(context); } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void saving(ISaveContext context) throws CoreException { long start = -1; if (VERBOSE) start = System.currentTimeMillis(); // save variable and container values on snapshot/full save saveVariablesAndContainers(context); if (VERBOSE) traceVariableAndContainers("Saved", start); //$NON-NLS-1$ switch(context.getKind()) { case ISaveContext.FULL_SAVE : { // save non-chaining jar and invalid jar caches on full save saveClasspathListCache(NON_CHAINING_JARS_CACHE); saveClasspathListCache(INVALID_ARCHIVES_CACHE); // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) context.needDelta(); // clean up indexes on workspace full save // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) IndexManager manager = this.indexManager; if (manager != null // don't force initialization of workspace scope as we could be shutting down // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93941) && this.workspaceScope != null) { manager.cleanUpIndexes(); } } //$FALL-THROUGH$ case ISaveContext.SNAPSHOT : { // clean up external folders on full save or snapshot this.externalFoldersManager.cleanUp(null); } } IProject savedProject = context.getProject(); if (savedProject != null) { if (!JavaProject.hasJavaNature(savedProject)) return; // ignore PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); saveState(info, context); return; } ArrayList vStats= null; // lazy initialized ArrayList values = null; synchronized(this.perProjectInfos) { values = new ArrayList(this.perProjectInfos.values()); } Iterator iterator = values.iterator(); while (iterator.hasNext()) { try { PerProjectInfo info = (PerProjectInfo) iterator.next(); saveState(info, context); } catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); } } if (vStats != null) { IStatus[] stats= new IStatus[vStats.size()]; vStats.toArray(stats); throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Messages.build_cannotSaveStates, null)); } // save external libs timestamps this.deltaState.saveExternalLibTimeStamps(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void saveExternalLibTimeStamps() throws CoreException { if (this.externalTimeStamps == null) return; // cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 ) HashSet toRemove = new HashSet(); if (this.roots != null) { Enumeration keys = this.externalTimeStamps.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (this.roots.get(key) == null) { toRemove.add(key); } } } File timestamps = getTimeStampsFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps))); out.writeInt(this.externalTimeStamps.size() - toRemove.size()); Iterator entries = this.externalTimeStamps.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IPath key = (IPath) entry.getKey(); if (!toRemove.contains(key)) { out.writeUTF(key.toPortableString()); Long timestamp = (Long) entry.getValue(); out.writeLong(timestamp.longValue()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// 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 dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(boolean ignoreComments) throws CoreException { int curr= 0; do { try { curr= this.scanner.getNextToken(); if (curr == TerminalTokens.TokenNameEOF) { throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$ } } catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); } } while (ignoreComments && isComment(curr)); return curr; }
8
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
174
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { if (VERBOSE) { Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$ Util.verbose(scope.toString()); } if (participants == null) { if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$ return; } /* initialize progress monitor */ int length = participants.length; if (monitor != null) monitor.beginTask(Messages.engine_searching, 100 * length); IndexManager indexManager = JavaModelManager.getIndexManager(); requestor.beginReporting(); for (int i = 0; i < length; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); SearchParticipant participant = participants[i]; try { if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()})); participant.beginSearching(); requestor.enterParticipant(participant); PathCollector pathCollector = new PathCollector(); indexManager.performConcurrentJob( new PatternSearchJob(pattern, participant, scope, pathCollector), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor==null ? null : new SubProgressMonitor(monitor, 50)); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // locate index matches if any (note that all search matches could have been issued during index querying) if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()})); String[] indexMatchPaths = pathCollector.getPaths(); if (indexMatchPaths != null) { pathCollector = null; // release int indexMatchLength = indexMatchPaths.length; SearchDocument[] indexMatches = new SearchDocument[indexMatchLength]; for (int j = 0; j < indexMatchLength; j++) { indexMatches[j] = participant.getDocument(indexMatchPaths[j]); } SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant); participant.locateMatches(matches, pattern, scope, requestor, monitor==null ? null : new SubProgressMonitor(monitor, 50)); } } finally { requestor.exitParticipant(participant); participant.doneSearching(); } } } finally { requestor.endReporting(); if (monitor != null) monitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (VERBOSE) { Util.verbose("BasicSearchEngine.search(SearchPattern, SearchParticipant[], IJavaSearchScope, SearchRequestor, IProgressMonitor)"); //$NON-NLS-1$ } findMatches(pattern, participants, scope, requestor, monitor); }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchParticipant.java
public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { MatchLocator matchLocator = new MatchLocator( pattern, requestor, scope, monitor ); /* eliminating false matches and locating them */ if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); matchLocator.locateMatches(indexMatches); }
// in search/org/eclipse/jdt/internal/core/search/matching/ClassFileMatchLocator.java
public void locateMatches(MatchLocator locator, ClassFile classFile, IBinaryType info) throws CoreException { SearchPattern pattern = locator.pattern; // check annotations references matchAnnotations(pattern, locator, classFile, info); // check class definition BinaryType binaryType = (BinaryType) classFile.getType(); if (matchBinary(pattern, info, null)) { binaryType = new ResolvedBinaryType((JavaElement) binaryType.getParent(), binaryType.getElementName(), binaryType.getKey()); locator.reportBinaryMemberDeclaration(null, binaryType, null, info, SearchMatch.A_ACCURATE); return; } // Define arrays to store methods/fields from binary type if necessary IBinaryMethod[] binaryMethods = info.getMethods(); int bMethodsLength = binaryMethods == null ? 0 : binaryMethods.length; IBinaryMethod[] unresolvedMethods = null; char[][] binaryMethodSignatures = null; boolean hasUnresolvedMethods = false; // Get fields from binary type info IBinaryField[] binaryFields = info.getFields(); int bFieldsLength = binaryFields == null ? 0 : binaryFields.length; IBinaryField[] unresolvedFields = null; boolean hasUnresolvedFields = false; // Report as many accurate matches as possible int accuracy = SearchMatch.A_ACCURATE; boolean mustResolve = pattern.mustResolve; if (mustResolve) { BinaryTypeBinding binding = locator.cacheBinaryType(binaryType, info); if (binding != null) { // filter out element not in hierarchy scope if (!locator.typeInHierarchy(binding)) return; // Search matches on resolved methods MethodBinding[] availableMethods = binding.availableMethods(); int aMethodsLength = availableMethods == null ? 0 : availableMethods.length; hasUnresolvedMethods = bMethodsLength != aMethodsLength; for (int i = 0; i < aMethodsLength; i++) { MethodBinding method = availableMethods[i]; char[] methodSignature = method.genericSignature(); if (methodSignature == null) methodSignature = method.signature(); // Report the match if possible int level = locator.patternLocator.resolveLevel(method); if (level != PatternLocator.IMPOSSIBLE_MATCH) { IMethod methodHandle = binaryType.getMethod( new String(method.isConstructor() ? binding.compoundName[binding.compoundName.length-1] : method.selector), CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(methodSignature)))); accuracy = level == PatternLocator.ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE; locator.reportBinaryMemberDeclaration(null, methodHandle, method, info, accuracy); } // Remove method from unresolved list if (hasUnresolvedMethods) { if (binaryMethodSignatures == null) { // Store binary method signatures to avoid multiple computation binaryMethodSignatures = new char[bMethodsLength][]; for (int j=0; j<bMethodsLength; j++) { IBinaryMethod binaryMethod = binaryMethods[j]; char[] signature = binaryMethod.getGenericSignature(); if (signature == null) signature = binaryMethod.getMethodDescriptor(); binaryMethodSignatures[j] = signature; } } for (int j=0; j<bMethodsLength; j++) { if (CharOperation.equals(binaryMethods[j].getSelector(), method.selector) && CharOperation.equals(binaryMethodSignatures[j], methodSignature)) { if (unresolvedMethods == null) { System.arraycopy(binaryMethods, 0, unresolvedMethods = new IBinaryMethod[bMethodsLength], 0, bMethodsLength); } unresolvedMethods[j] = null; break; } } } } // Search matches on resolved fields FieldBinding[] availableFields = binding.availableFields(); int aFieldsLength = availableFields == null ? 0 : availableFields.length; hasUnresolvedFields = bFieldsLength != aFieldsLength; for (int i = 0; i < aFieldsLength; i++) { FieldBinding field = availableFields[i]; // Report the match if possible int level = locator.patternLocator.resolveLevel(field); if (level != PatternLocator.IMPOSSIBLE_MATCH) { IField fieldHandle = binaryType.getField(new String(field.name)); accuracy = level == PatternLocator.ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE; locator.reportBinaryMemberDeclaration(null, fieldHandle, field, info, accuracy); } // Remove the field from unresolved list if (hasUnresolvedFields) { for (int j=0; j<bFieldsLength; j++) { if ( CharOperation.equals(binaryFields[j].getName(), field.name)) { if (unresolvedFields == null) { System.arraycopy(binaryFields, 0, unresolvedFields = new IBinaryField[bFieldsLength], 0, bFieldsLength); } unresolvedFields[j] = null; break; } } } } // If all methods/fields were accurate then returns now if (!hasUnresolvedMethods && !hasUnresolvedFields) { return; } } accuracy = SearchMatch.A_INACCURATE; } // Report inaccurate methods if (mustResolve) binaryMethods = unresolvedMethods; bMethodsLength = binaryMethods == null ? 0 : binaryMethods.length; for (int i=0; i < bMethodsLength; i++) { IBinaryMethod method = binaryMethods[i]; if (method == null) continue; // impossible match or already reported as accurate if (matchBinary(pattern, method, info)) { char[] name; if (method.isConstructor()) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=329727 // We don't need the enclosing type name for the constructor name name = info.getSourceName(); } else { name = method.getSelector(); } String selector = new String(name); char[] methodSignature = binaryMethodSignatures == null ? null : binaryMethodSignatures[i]; if (methodSignature == null) { methodSignature = method.getGenericSignature(); if (methodSignature == null) methodSignature = method.getMethodDescriptor(); } String[] parameterTypes = CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(methodSignature))); IMethod methodHandle = binaryType.getMethod(selector, parameterTypes); methodHandle = new ResolvedBinaryMethod(binaryType, selector, parameterTypes, methodHandle.getKey()); locator.reportBinaryMemberDeclaration(null, methodHandle, null, info, accuracy); } } // Report inaccurate fields if (mustResolve) binaryFields = unresolvedFields; bFieldsLength = binaryFields == null ? 0 : binaryFields.length; for (int i=0; i<bFieldsLength; i++) { IBinaryField field = binaryFields[i]; if (field == null) continue; // impossible match or already reported as accurate if (matchBinary(pattern, field, info)) { String fieldName = new String(field.getName()); IField fieldHandle = binaryType.getField(fieldName); fieldHandle = new ResolvedBinaryField(binaryType, fieldName, fieldHandle.getKey()); locator.reportBinaryMemberDeclaration(null, fieldHandle, null, info, accuracy); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/ClassFileMatchLocator.java
private void matchAnnotations(SearchPattern pattern, MatchLocator locator, ClassFile classFile, IBinaryType binaryType) throws CoreException { // Only process TypeReference patterns switch (pattern.kind) { case TYPE_REF_PATTERN: break; case OR_PATTERN: SearchPattern[] patterns = ((OrPattern) pattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { matchAnnotations(patterns[i], locator, classFile, binaryType); } // $FALL-THROUGH$ - fall through default to return default: return; } TypeReferencePattern typeReferencePattern = (TypeReferencePattern) pattern; // Look for references in class annotations IBinaryAnnotation[] annotations = binaryType.getAnnotations(); BinaryType classFileBinaryType = (BinaryType) classFile.getType(); BinaryTypeBinding binaryTypeBinding = null; if (checkAnnotations(typeReferencePattern, annotations, binaryType.getTagBits())) { classFileBinaryType = new ResolvedBinaryType((JavaElement) classFileBinaryType.getParent(), classFileBinaryType.getElementName(), classFileBinaryType.getKey()); TypeReferenceMatch match = new TypeReferenceMatch(classFileBinaryType, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } // Look for references in methods annotations MethodInfo[] methods = (MethodInfo[]) binaryType.getMethods(); if (methods != null) { for (int i = 0, max = methods.length; i < max; i++) { MethodInfo method = methods[i]; if (checkAnnotations(typeReferencePattern, method.getAnnotations(), method.getTagBits())) { binaryTypeBinding = locator.cacheBinaryType(classFileBinaryType, binaryType); IMethod methodHandle = classFileBinaryType.getMethod( new String(method.isConstructor() ? binaryTypeBinding.compoundName[binaryTypeBinding.compoundName.length-1] : method.getSelector()), CharOperation.toStrings(Signature.getParameterTypes(convertClassFileFormat(method.getMethodDescriptor())))); TypeReferenceMatch match = new TypeReferenceMatch(methodHandle, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } } } // Look for references in fields annotations FieldInfo[] fields = (FieldInfo[]) binaryType.getFields(); if (fields != null) { for (int i = 0, max = fields.length; i < max; i++) { FieldInfo field = fields[i]; if (checkAnnotations(typeReferencePattern, field.getAnnotations(), field.getTagBits())) { IField fieldHandle = classFileBinaryType.getField(new String(field.getName())); TypeReferenceMatch match = new TypeReferenceMatch(fieldHandle, SearchMatch.A_ACCURATE, -1, 0, false, locator.getParticipant(), locator.currentPossibleMatch.resource); // TODO 3.4 M7 (frederic) - bug 209996: see how create the annotation handle from the binary and put it in the local element match.setLocalElement(null); locator.report(match); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { PatternLocator weakestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { int newLevel = this.patternLocators[i].matchLevel(importRef); if (newLevel == IMPOSSIBLE_MATCH) return; if (weakestPattern == null || newLevel < level) { weakestPattern = this.patternLocators[i]; level = newLevel; } } weakestPattern.matchReportImportRef(importRef, binding, element, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { PatternLocator weakestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { if (this.patternLocators[i].referenceType() == 0) return; // impossible match int newLevel = this.patternLocators[i].resolveLevel(reference); if (newLevel == IMPOSSIBLE_MATCH) return; if (weakestPattern == null || newLevel < level) { weakestPattern = this.patternLocators[i]; level = newLevel; } } weakestPattern.matchReportReference(reference, element, localElement, otherElements, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/AndLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected IBinaryType getBinaryInfo(ClassFile classFile, IResource resource) throws CoreException { BinaryType binaryType = (BinaryType) classFile.getType(); if (classFile.isOpen()) return (IBinaryType) binaryType.getElementInfo(); // reuse the info from the java model cache // create a temporary info IBinaryType info; try { PackageFragment pkg = (PackageFragment) classFile.getParent(); PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent(); if (root.isArchive()) { // class file in a jar String classFileName = classFile.getElementName(); String classFilePath = Util.concatWith(pkg.names, classFileName, '/'); ZipFile zipFile = null; try { zipFile = ((JarPackageFragmentRoot) root).getJar(); info = ClassFileReader.read(zipFile, classFilePath); } finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } } else { // class file in a directory info = Util.newClassFileReader(resource); } if (info == null) throw binaryType.newNotPresentException(); return info; } catch (ClassFormatException e) { //e.printStackTrace(); return null; } catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMatches, int start, int length) throws CoreException { initialize(javaProject, length); // create and resolve binding (equivalent to beginCompilation() in Compiler) boolean mustResolvePattern = this.pattern.mustResolve; boolean mustResolve = mustResolvePattern; this.patternLocator.mayBeGeneric = this.options.sourceLevel >= ClassFileConstants.JDK1_5; boolean bindingsWereCreated = mustResolve; try { for (int i = start, maxUnits = start + length; i < maxUnits; i++) { PossibleMatch possibleMatch = possibleMatches[i]; try { if (!parseAndBuildBindings(possibleMatch, mustResolvePattern)) continue; // Currently we only need to resolve over pattern flag if there's potential parameterized types if (this.patternLocator.mayBeGeneric) { // If pattern does not resolve then rely on possible match node set resolution // which may have been modified while locator was adding possible matches to it if (!mustResolvePattern && !mustResolve) { mustResolve = possibleMatch.nodeSet.mustResolve; bindingsWereCreated = mustResolve; } } else { // Reset matching node resolution with pattern one if there's no potential parameterized type // to minimize side effect on previous search behavior possibleMatch.nodeSet.mustResolve = mustResolvePattern; } // possible match node resolution has been merged with pattern one, so rely on it to know // whether we need to process compilation unit now or later if (!possibleMatch.nodeSet.mustResolve) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } process(possibleMatch, bindingsWereCreated); if (this.numberOfMatches>0 && this.matchesToProcess[this.numberOfMatches-1] == possibleMatch) { // forget last possible match as it was processed this.numberOfMatches--; } } } finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); } } if (mustResolve) this.lookupEnvironment.completeTypeBindings(); // create hierarchy resolver if needed IType focusType = getFocusType(); if (focusType == null) { this.hierarchyResolver = null; } else if (!createHierarchyResolver(focusType, possibleMatches)) { // focus type is not visible, use the super type names instead of the bindings if (computeSuperTypeNames(focusType) == null) return; } } catch (AbortCompilation e) { bindingsWereCreated = false; } if (!mustResolve) { return; } // possible match resolution for (int i = 0; i < this.numberOfMatches; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); PossibleMatch possibleMatch = this.matchesToProcess[i]; this.matchesToProcess[i] = null; // release reference to processed possible match try { process(possibleMatch, bindingsWereCreated); } catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatchSet matchSet, int expected) throws CoreException { PossibleMatch[] possibleMatches = matchSet.getPossibleMatches(javaProject.getPackageFragmentRoots()); int length = possibleMatches.length; // increase progress from duplicate matches not stored in matchSet while adding... if (this.progressMonitor != null && expected>length) { this.progressWorked += expected-length; this.progressMonitor.worked( expected-length); } // locate matches (processed matches are limited to avoid problem while using VM default memory heap size) for (int index = 0; index < length;) { int max = Math.min(MAX_AT_ONCE, length - index); locateMatches(javaProject, possibleMatches, index, max); index += max; } this.patternLocator.clear(); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public void locateMatches(SearchDocument[] searchDocuments) throws CoreException { if (this.patternLocator == null) return; int docsLength = searchDocuments.length; int progressLength = docsLength; if (BasicSearchEngine.VERBOSE) { System.out.println("Locating matches in documents ["); //$NON-NLS-1$ for (int i = 0; i < docsLength; i++) System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$ System.out.println("]"); //$NON-NLS-1$ } IJavaProject[] javaModelProjects = null; if (this.searchPackageDeclaration) { javaModelProjects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); progressLength += javaModelProjects.length; } // init infos for progress increasing int n = progressLength<1000 ? Math.min(Math.max(progressLength/200+1, 2),4) : 5 *(progressLength/1000); this.progressStep = progressLength < n ? 1 : progressLength / n; // step should not be 0 this.progressWorked = 0; // extract working copies ArrayList copies = new ArrayList(); for (int i = 0; i < docsLength; i++) { SearchDocument document = searchDocuments[i]; if (document instanceof WorkingCopyDocument) { copies.add(((WorkingCopyDocument)document).workingCopy); } } int copiesLength = copies.size(); this.workingCopies = new org.eclipse.jdt.core.ICompilationUnit[copiesLength]; copies.toArray(this.workingCopies); JavaModelManager manager = JavaModelManager.getJavaModelManager(); this.bindings = new SimpleLookupTable(); try { // optimize access to zip files during search operation manager.cacheZipFiles(this); // initialize handle factory (used as a cache of handles so as to optimize space) if (this.handleFactory == null) this.handleFactory = new HandleFactory(); if (this.progressMonitor != null) { this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$ } // initialize pattern for polymorphic search (i.e. method reference pattern) this.patternLocator.initializePolymorphicSearch(this); JavaProject previousJavaProject = null; PossibleMatchSet matchSet = new PossibleMatchSet(); Util.sort(searchDocuments, new Util.Comparer() { public int compare(Object a, Object b) { return ((SearchDocument)a).getPath().compareTo(((SearchDocument)b).getPath()); } }); int displayed = 0; // progress worked displayed String previousPath = null; SearchParticipant searchParticipant = null; for (int i = 0; i < docsLength; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // skip duplicate paths SearchDocument searchDocument = searchDocuments[i]; if (searchParticipant == null) { searchParticipant = searchDocument.getParticipant(); } searchDocuments[i] = null; // free current document String pathString = searchDocument.getPath(); if (i > 0 && pathString.equals(previousPath)) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; } previousPath = pathString; Openable openable; org.eclipse.jdt.core.ICompilationUnit workingCopy = null; if (searchDocument instanceof WorkingCopyDocument) { workingCopy = ((WorkingCopyDocument)searchDocument).workingCopy; openable = (Openable) workingCopy; } else { openable = this.handleFactory.createOpenable(pathString, this.scope); } if (openable == null) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; // match is outside classpath } // create new parser and lookup environment if this is a new project IResource resource = null; JavaProject javaProject = (JavaProject) openable.getJavaProject(); resource = workingCopy != null ? workingCopy.getResource() : openable.getResource(); if (resource == null) resource = javaProject.getProject(); // case of a file in an external jar or external folder if (!javaProject.equals(previousJavaProject)) { // locate matches in previous project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, i-displayed); displayed = i; } catch (JavaModelException e) { // problem with classpath in this project -> skip it } matchSet.reset(); } previousJavaProject = javaProject; } matchSet.add(new PossibleMatch(this, resource, openable, searchDocument,this.pattern.mustResolve)); } // last project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, docsLength-displayed); } catch (JavaModelException e) { // problem with classpath in last project -> ignore } } if (this.searchPackageDeclaration) { locatePackageDeclarations(searchParticipant, javaModelProjects); } } finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchParticipant participant, IJavaProject[] projects) throws CoreException { locatePackageDeclarations(this.pattern, participant, projects); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); try { if (BasicSearchEngine.VERBOSE) System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.parser.nodeSet = possibleMatch.nodeSet; CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult); if (parsedUnit != null) { if (!parsedUnit.isEmpty()) { if (mustResolve) { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } if (hasAlreadyDefinedType(parsedUnit)) return false; // skip type has it is hidden so not visible getMethodBodies(parsedUnit, possibleMatch.nodeSet); if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) { // special case: possible match node set force resolution although pattern does not // => we need to build types for this compilation unit this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } } // add the possibleMatch with its parsedUnit to matchesToProcess possibleMatch.parsedUnit = parsedUnit; int size = this.matchesToProcess.length; if (this.numberOfMatches == size) System.arraycopy(this.matchesToProcess, 0, this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0, this.numberOfMatches); this.matchesToProcess[this.numberOfMatches++] = possibleMatch; } } finally { this.parser.nodeSet = null; } return true; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void process(PossibleMatch possibleMatch, boolean bindingsWereCreated) throws CoreException { this.currentPossibleMatch = possibleMatch; CompilationUnitDeclaration unit = possibleMatch.parsedUnit; try { if (unit.isEmpty()) { if (this.currentPossibleMatch.openable instanceof ClassFile) { ClassFile classFile = (ClassFile) this.currentPossibleMatch.openable; IBinaryType info = null; try { info = getBinaryInfo(classFile, classFile.resource()); } catch (CoreException ce) { // Do nothing } if (info != null) { boolean mayBeGeneric = this.patternLocator.mayBeGeneric; this.patternLocator.mayBeGeneric = false; // there's no longer generic in class files try { new ClassFileMatchLocator().locateMatches(this, classFile, info); } finally { this.patternLocator.mayBeGeneric = mayBeGeneric; } } } return; } if (hasAlreadyDefinedType(unit)) return; // skip type has it is hidden so not visible // Move getMethodBodies to #parseAndBuildings(...) method to allow possible match resolution management //getMethodBodies(unit); boolean mustResolve = (this.pattern.mustResolve || possibleMatch.nodeSet.mustResolve); if (bindingsWereCreated && mustResolve) { if (unit.types != null) { if (BasicSearchEngine.VERBOSE) System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.lookupEnvironment.unitBeingCompleted = unit; reduceParseTree(unit); if (unit.scope != null) { // fault in fields & methods unit.scope.faultInTypes(); } unit.resolve(); } else if (unit.isPackageInfo()) { if (BasicSearchEngine.VERBOSE) System.out.println("Resolving " + this.currentPossibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ unit.resolve(); } } reportMatching(unit, mustResolve); } catch (AbortCompilation e) { // could not resolve: report inaccurate matches reportMatching(unit, false); // do not resolve when cu has errors if (!(e instanceof AbortCompilationUnit)) { // problem with class path throw e; } } finally { this.lookupEnvironment.unitBeingCompleted = null; this.currentPossibleMatch = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void report(SearchMatch match) throws CoreException { if (match == null) { if (BasicSearchEngine.VERBOSE) { System.out.println("Cannot report a null match!!!"); //$NON-NLS-1$ } return; } if (filterEnum(match)){ if (BasicSearchEngine.VERBOSE) { System.out.println("Filtered package with name enum"); //$NON-NLS-1$ } return; } long start = -1; if (BasicSearchEngine.VERBOSE) { start = System.currentTimeMillis(); System.out.println("Reporting match"); //$NON-NLS-1$ System.out.println("\tResource: " + match.getResource());//$NON-NLS-1$ System.out.println("\tPositions: [offset=" + match.getOffset() + ", length=" + match.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ try { if (this.parser != null && match.getOffset() > 0 && match.getLength() > 0 && !(match.getElement() instanceof BinaryMember)) { String selection = new String(this.parser.scanner.source, match.getOffset(), match.getLength()); System.out.println("\tSelection: -->" + selection + "<--"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } try { JavaElement javaElement = (JavaElement)match.getElement(); System.out.println("\tJava element: "+ javaElement.toStringWithAncestors()); //$NON-NLS-1$ if (!javaElement.exists()) { System.out.println("\t\tWARNING: this element does NOT exist!"); //$NON-NLS-1$ } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } if (match instanceof ReferenceMatch) { try { ReferenceMatch refMatch = (ReferenceMatch) match; JavaElement local = (JavaElement) refMatch.getLocalElement(); if (local != null) { System.out.println("\tLocal element: "+ local.toStringWithAncestors()); //$NON-NLS-1$ } if (match instanceof TypeReferenceMatch) { IJavaElement[] others = ((TypeReferenceMatch) refMatch).getOtherElements(); if (others != null) { int length = others.length; if (length > 0) { System.out.println("\tOther elements:"); //$NON-NLS-1$ for (int i=0; i<length; i++) { JavaElement other = (JavaElement) others[i]; System.out.println("\t\t- "+ other.toStringWithAncestors()); //$NON-NLS-1$ } } } } } catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area } } System.out.println(match.getAccuracy() == SearchMatch.A_ACCURATE ? "\tAccuracy: EXACT_MATCH" //$NON-NLS-1$ : "\tAccuracy: POTENTIAL_MATCH"); //$NON-NLS-1$ System.out.print("\tRule: "); //$NON-NLS-1$ if (match.isExact()) { System.out.print("EXACT"); //$NON-NLS-1$ } else if (match.isEquivalent()) { System.out.print("EQUIVALENT"); //$NON-NLS-1$ } else if (match.isErasure()) { System.out.print("ERASURE"); //$NON-NLS-1$ } else { System.out.print("INVALID RULE"); //$NON-NLS-1$ } if (match instanceof MethodReferenceMatch) { MethodReferenceMatch methodReferenceMatch = (MethodReferenceMatch) match; if (methodReferenceMatch.isSuperInvocation()) { System.out.print("+SUPER INVOCATION"); //$NON-NLS-1$ } if (methodReferenceMatch.isImplicit()) { System.out.print("+IMPLICIT"); //$NON-NLS-1$ } if (methodReferenceMatch.isSynthetic()) { System.out.print("+SYNTHETIC"); //$NON-NLS-1$ } } System.out.println("\n\tRaw: "+match.isRaw()); //$NON-NLS-1$ } this.requestor.acceptSearchMatch(match); if (BasicSearchEngine.VERBOSE) this.resultCollectorTime += System.currentTimeMillis()-start; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateTypeReference(SearchMatch match, ASTNode typeRef, char[] name) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; int sourceStart = typeRef.sourceStart; int sourceEnd = typeRef.sourceEnd; // Compute source positions of the qualified reference if (name != null) { Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); int token = -1; int currentPosition; do { currentPosition = scanner.currentPosition; try { token = scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } if (token == TerminalTokens.TokenNameIdentifier && this.pattern.matchesName(name, scanner.getCurrentTokenSource())) { int length = scanner.currentPosition-currentPosition; match.setOffset(currentPosition); match.setLength(length); report(match); return; } } while (token != TerminalTokens.TokenNameEOF); } // Report match match.setOffset(sourceStart); match.setLength(sourceEnd-sourceStart+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateParameterizedMethodReference(SearchMatch match, ASTNode statement, TypeReference[] typeArguments) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; // If there's type arguments, look for end (i.e. char '>') of last one. int start = match.getOffset(); if (typeArguments != null && typeArguments.length > 0) { boolean isErasureMatch= (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).isErasureMatch() : ((JavaSearchPattern)this.pattern).isErasureMatch(); if (!isErasureMatch) { // Initialize scanner Scanner scanner = this.parser.scanner; char[] source = this.currentPossibleMatch.getContents(); scanner.setSource(source); // Search previous opening '<' start = typeArguments[0].sourceStart; int end = statement.sourceEnd; scanner.resetTo(start, end); int lineStart = start; try { linesUp: while (true) { while (scanner.source[scanner.currentPosition] != '\n') { scanner.currentPosition--; if (scanner.currentPosition == 0) break linesUp; } lineStart = scanner.currentPosition+1; scanner.resetTo(lineStart, end); while (!scanner.atEnd()) { if (scanner.getNextToken() == TerminalTokens.TokenNameLESS) { start = scanner.getCurrentTokenStartPosition(); break linesUp; } } end = lineStart - 2; scanner.currentPosition = end; } } catch (InvalidInputException ex) { // give up } } } // Report match match.setOffset(start); match.setLength(statement.sourceEnd-start+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateParameterizedTypeReference(SearchMatch match, TypeReference typeRef, int index, TypeReference[] typeArguments) throws CoreException { if (match.getRule() == 0) return; if (!encloses((IJavaElement)match.getElement())) return; // If there's type arguments, look for end (i.e. char '>') of last one. int end = typeRef.sourceEnd; if (typeArguments != null) { boolean shouldMatchErasure= (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).isErasureMatch() : ((JavaSearchPattern)this.pattern).isErasureMatch(); boolean hasSignatures = (this.pattern instanceof OrPattern) ? ((OrPattern)this.pattern).hasSignatures() : ((JavaSearchPattern)this.pattern).hasSignatures(); if (shouldMatchErasure || !hasSignatures) { // if pattern is erasure only, then select the end of the reference if (typeRef instanceof QualifiedTypeReference && index >= 0) { long[] positions = ((QualifiedTypeReference) typeRef).sourcePositions; end = (int) positions[index]; } else if (typeRef instanceof ArrayTypeReference) { end = ((ArrayTypeReference) typeRef).originalSourceEnd; } } else { // Initialize scanner Scanner scanner = this.parser.scanner; char[] source = this.currentPossibleMatch.getContents(); scanner.setSource(source); // Set scanner position at end of last type argument scanner.resetTo(end, source.length-1); int depth = 0; for (int i=typeArguments.length-1; i>=0; i--) { if (typeArguments[i] != null) { long lastTypeArgInfo = findLastTypeArgumentInfo(typeArguments[i]); depth = (int) (lastTypeArgInfo >>> 32)+1; scanner.resetTo(((int)lastTypeArgInfo)+1, scanner.eofPosition-1); break; } } // Now, scan to search next closing '>' while (depth-- > 0) { while (!scanner.atEnd()) { if (scanner.getNextChar() == '>') { end = scanner.currentPosition - 1; break; } } } } } // Report match match.setLength(end-match.getOffset()+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateEnumConstructorReference(SearchMatch match, FieldDeclaration field, AllocationExpression allocation) throws CoreException { // Verify that field declaration is really an enum constant if (allocation == null || allocation.enumConstant == null) { report(match); return; } // Get scan area int sourceStart = match.getOffset()+match.getLength(); if (allocation.arguments != null && allocation.arguments.length > 0) { sourceStart = allocation.arguments[allocation.arguments.length-1].sourceEnd+1; } int sourceEnd = field.declarationSourceEnd; if (allocation instanceof QualifiedAllocationExpression) { QualifiedAllocationExpression qualifiedAllocation = (QualifiedAllocationExpression) allocation; if (qualifiedAllocation.anonymousType != null) { sourceEnd = qualifiedAllocation.anonymousType.sourceStart - 1; } } // Scan to find last closing parenthesis Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); try { int token = scanner.getNextToken(); while (token != TerminalTokens.TokenNameEOF) { if (token == TerminalTokens.TokenNameRPAREN) { sourceEnd = scanner.getCurrentTokenEndPosition(); } token = scanner.getNextToken(); } } catch (InvalidInputException iie) { // give up } // Report match match.setLength(sourceEnd-match.getOffset()+1); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportAccurateFieldReference(SearchMatch[] matches, QualifiedNameReference qNameRef) throws CoreException { if (matches == null) return; // there's nothing to accurate in this case int matchesLength = matches.length; int sourceStart = qNameRef.sourceStart; int sourceEnd = qNameRef.sourceEnd; char[][] tokens = qNameRef.tokens; // compute source positions of the qualified reference Scanner scanner = this.parser.scanner; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(sourceStart, sourceEnd); int sourceLength = sourceEnd-sourceStart+1; int refSourceStart = -1, refSourceEnd = -1; int length = tokens.length; int token = -1; int previousValid = -1; int i = 0; int index = 0; do { int currentPosition = scanner.currentPosition; // read token try { token = scanner.getNextToken(); } catch (InvalidInputException e) { //ignore } if (token != TerminalTokens.TokenNameEOF) { char[] currentTokenSource = scanner.getCurrentTokenSource(); boolean equals = false; while (i < length && !(equals = this.pattern.matchesName(tokens[i++], currentTokenSource))){/*empty*/} if (equals && (previousValid == -1 || previousValid == i - 2)) { previousValid = i - 1; if (refSourceStart == -1) refSourceStart = currentPosition; refSourceEnd = scanner.currentPosition - 1; } else { i = 0; refSourceStart = -1; previousValid = -1; } // read '.' try { token = scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } } SearchMatch match = matches[index]; if (match != null && match.getRule() != 0) { if (!encloses((IJavaElement)match.getElement())) return; // accept reference if (refSourceStart != -1) { match.setOffset(refSourceStart); match.setLength(refSourceEnd-refSourceStart+1); report(match); } else { match.setOffset(sourceStart); match.setLength(sourceLength); report(match); } i = 0; } refSourceStart = -1; previousValid = -1; if (index < matchesLength - 1) { index++; } } while (token != TerminalTokens.TokenNameEOF); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportBinaryMemberDeclaration(IResource resource, IMember binaryMember, Binding binaryMemberBinding, IBinaryType info, int accuracy) throws CoreException { ClassFile classFile = (ClassFile) binaryMember.getClassFile(); ISourceRange range = classFile.isOpen() ? binaryMember.getNameRange() : SourceMapper.UNKNOWN_RANGE; if (range.getOffset() == -1) { BinaryType type = (BinaryType) classFile.getType(); String sourceFileName = type.sourceFileName(info); if (sourceFileName != null) { SourceMapper mapper = classFile.getSourceMapper(); if (mapper != null) { char[] contents = mapper.findSource(type, sourceFileName); if (contents != null) range = mapper.mapSource(type, contents, info, binaryMember); } } } if (resource == null) resource = this.currentPossibleMatch.resource; SearchMatch match = newDeclarationMatch(binaryMember, binaryMemberBinding, accuracy, range.getOffset(), range.getLength(), getParticipant(), resource); report(match); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(AbstractMethodDeclaration method, TypeDeclaration type, IJavaElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException { IJavaElement enclosingElement = null; // report method declaration itself if (accuracy > -1) { enclosingElement = createHandle(method, parent); if (enclosingElement != null) { // skip if unable to find method // compute source positions of the selector Scanner scanner = this.parser.scanner; int nameSourceStart = method.sourceStart; scanner.setSource(this.currentPossibleMatch.getContents()); scanner.resetTo(nameSourceStart, method.sourceEnd); try { scanner.getNextToken(); } catch (InvalidInputException e) { // ignore } if (encloses(enclosingElement)) { SearchMatch match = null; if (method.isDefaultConstructor()) { // Use type for match associated element as default constructor does not exist in source int offset = type.sourceStart; match = this.patternLocator.newDeclarationMatch(type, parent, type.binding, accuracy, type.sourceEnd-offset+1, this); } else { int length = scanner.currentPosition - nameSourceStart; match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.binding, accuracy, length, this); } if (match != null) { report(match); } } } } // handle nodes for the local type first if ((method.bits & ASTNode.HasLocalType) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } // Traverse method declaration to report matches both in local types declaration // and in local variables declaration ASTNode[] nodes = typeInHierarchy ? nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd) : null; boolean report = (this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0 && encloses(enclosingElement); MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, report ? nodes : null, nodeSet, this); try { method.traverse(declarationVisitor, (ClassScope) null); } catch (WrappedCoreException e) { throw e.coreException; } // Report all nodes and remove them if (nodes != null) { int length = nodes.length; for (int i = 0; i < length; i++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]); if (report && level != null) { this.patternLocator.matchReportReference(nodes[i], enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), method.binding, level.intValue(), this); } } } } // report the type parameters TypeParameter[] typeParameters = method.typeParameters(); if (typeParameters != null) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (enclosingElement != null) { reportMatching(typeParameters, enclosingElement, parent, method.binding, nodeSet); } } // report annotations if (method.annotations != null) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (enclosingElement != null) { reportMatching(method.annotations, enclosingElement, null, method.binding, nodeSet, true, true); } } // references in this method if (typeInHierarchy) { ASTNode[] nodes = nodeSet.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd); if (nodes != null) { if ((this.matchContainer & PatternLocator.METHOD_CONTAINER) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(method, parent); } if (encloses(enclosingElement)) { if (this.pattern.mustResolve) { // Visit only if the pattern must resolve MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, nodes, nodeSet, this); method.traverse(declarationVisitor, (ClassScope) null); int length = nodes.length; for (int i = 0; i < length; i++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(nodes[i]); if (level != null) { // ensure that the reference has not been already reported while visiting this.patternLocator.matchReportReference(nodes[i], enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), method.binding, level.intValue(), this); } } } else { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (level != null) { // ensure that the reference has not been already reported while visiting this.patternLocator.matchReportReference(node, enclosingElement, null, null, method.binding, level.intValue(), this); } } } return; } } // Remove all remaining nodes for (int i = 0, l = nodes.length; i < l; i++) { nodeSet.matchingNodes.removeKey(nodes[i]); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(Annotation[] annotations, IJavaElement enclosingElement, IJavaElement[] otherElements, Binding elementBinding, MatchingNodeSet nodeSet, boolean matchedContainer, boolean enclosesElement) throws CoreException { for (int i=0, al=annotations.length; i<al; i++) { Annotation annotationType = annotations[i]; IJavaElement localAnnotation = null; IJavaElement[] otherAnnotations = null; int length = otherElements == null ? 0 : otherElements.length; boolean handlesCreated = false; // Look for annotation type ref TypeReference typeRef = annotationType.type; Integer level = (Integer) nodeSet.matchingNodes.removeKey(typeRef); if (level != null && enclosesElement && matchedContainer) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; this.patternLocator.matchReportReference(typeRef, enclosingElement, localAnnotation, otherAnnotations, elementBinding, level.intValue(), this); } // Look for attribute ref MemberValuePair[] pairs = annotationType.memberValuePairs(); for (int j = 0, pl = pairs.length; j < pl; j++) { MemberValuePair pair = pairs[j]; level = (Integer) nodeSet.matchingNodes.removeKey(pair); if (level != null && enclosesElement) { ASTNode reference = (annotationType instanceof SingleMemberAnnotation) ? (ASTNode) annotationType: pair; if (!handlesCreated) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; } this.patternLocator.matchReportReference(reference, enclosingElement, localAnnotation, otherAnnotations, pair.binding, level.intValue(), this); } } // Look for reference inside annotation ASTNode[] nodes = nodeSet.matchingNodes(annotationType.sourceStart, annotationType.declarationSourceEnd); if (nodes != null) { if (!matchedContainer) { for (int j = 0, nl = nodes.length; j < nl; j++) { nodeSet.matchingNodes.removeKey(nodes[j]); } } else { for (int j = 0, nl = nodes.length; j < nl; j++) { ASTNode node = nodes[j]; level = (Integer) nodeSet.matchingNodes.removeKey(node); if (enclosesElement) { if (!handlesCreated) { localAnnotation = createHandle(annotationType, (IAnnotatable) enclosingElement); if (length > 0) { otherAnnotations = new IJavaElement[length]; for (int o=0; o<length; o++) { otherAnnotations[o] = createHandle(annotationType, (IAnnotatable) otherElements[o]); } } handlesCreated = true; } this.patternLocator.matchReportReference(node, enclosingElement, localAnnotation, otherAnnotations, elementBinding, level.intValue(), this); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(CompilationUnitDeclaration unit, boolean mustResolve) throws CoreException { MatchingNodeSet nodeSet = this.currentPossibleMatch.nodeSet; boolean locatorMustResolve = this.patternLocator.mustResolve; if (nodeSet.mustResolve) this.patternLocator.mustResolve = true; if (BasicSearchEngine.VERBOSE) { System.out.println("Report matching: "); //$NON-NLS-1$ int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize; System.out.print(" - node set: accurate="+ size); //$NON-NLS-1$ size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize; System.out.println(", possible="+size); //$NON-NLS-1$ System.out.print(" - must resolve: "+mustResolve); //$NON-NLS-1$ System.out.print(" (locator: "+this.patternLocator.mustResolve); //$NON-NLS-1$ System.out.println(", nodeSet: "+nodeSet.mustResolve+')'); //$NON-NLS-1$ System.out.println(" - fine grain flags="+ JavaSearchPattern.getFineGrainFlagString(this.patternLocator.fineGrain())); //$NON-NLS-1$ } if (mustResolve) { this.unitScope= unit.scope.compilationUnitScope(); // move the possible matching nodes that exactly match the search pattern to the matching nodes set Object[] nodes = nodeSet.possibleMatchingNodesSet.values; for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = (ASTNode) nodes[i]; if (node == null) continue; if (node instanceof ImportReference) { // special case for import refs: they don't know their binding // import ref cannot be in the hierarchy of a type if (this.hierarchyResolver != null) continue; ImportReference importRef = (ImportReference) node; Binding binding = (importRef.bits & ASTNode.OnDemand) != 0 ? this.unitScope.getImport(CharOperation.subarray(importRef.tokens, 0, importRef.tokens.length), true, importRef.isStatic()) : this.unitScope.getImport(importRef.tokens, false, importRef.isStatic()); this.patternLocator.matchLevelAndReportImportRef(importRef, binding, this); } else { nodeSet.addMatch(node, this.patternLocator.resolveLevel(node)); } } nodeSet.possibleMatchingNodesSet = new SimpleSet(3); if (BasicSearchEngine.VERBOSE) { int size = nodeSet.matchingNodes==null ? 0 : nodeSet.matchingNodes.elementSize; System.out.print(" - node set: accurate="+size); //$NON-NLS-1$ size = nodeSet.possibleMatchingNodesSet==null ? 0 : nodeSet.possibleMatchingNodesSet.elementSize; System.out.println(", possible="+size); //$NON-NLS-1$ } } else { this.unitScope = null; } if (nodeSet.matchingNodes.elementSize == 0) return; // no matching nodes were found this.methodHandles = new HashSet(); boolean matchedUnitContainer = (this.matchContainer & PatternLocator.COMPILATION_UNIT_CONTAINER) != 0; // report references in javadoc if (unit.javadoc != null) { ASTNode[] nodes = nodeSet.matchingNodes(unit.javadoc.sourceStart, unit.javadoc.sourceEnd); if (nodes != null) { if (!matchedUnitContainer) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { IJavaElement element = createPackageDeclarationHandle(unit); for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (encloses(element)) { this.patternLocator.matchReportReference(node, element, null, null, null/*no binding*/, level.intValue(), this); } } } } } if (matchedUnitContainer) { ImportReference pkg = unit.currentPackage; if (pkg != null && pkg.annotations != null) { IJavaElement element = createPackageDeclarationHandle(unit); if (element != null) { reportMatching(pkg.annotations, element, null, null, nodeSet, true, encloses(element)); } } ImportReference[] imports = unit.imports; if (imports != null) { for (int i = 0, l = imports.length; i < l; i++) { ImportReference importRef = imports[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(importRef); if (level != null) { this.patternLocator.matchReportImportRef(importRef, null /*no binding*/, createImportHandle(importRef), level.intValue(), this); } } } } TypeDeclaration[] types = unit.types; if (types != null) { for (int i = 0, l = types.length; i < l; i++) { if (nodeSet.matchingNodes.elementSize == 0) return; // reported all the matching nodes TypeDeclaration type = types[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(type); int accuracy = (level != null && matchedUnitContainer) ? level.intValue() : -1; reportMatching(type, null, accuracy, nodeSet, 1); } } // Clear handle cache this.methodHandles = null; this.bindings.removeKey(this.pattern); this.patternLocator.mustResolve = locatorMustResolve; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(FieldDeclaration field, FieldDeclaration[] otherFields, TypeDeclaration type, IJavaElement parent, int accuracy, boolean typeInHierarchy, MatchingNodeSet nodeSet) throws CoreException { IJavaElement enclosingElement = null; if (accuracy > -1) { enclosingElement = createHandle(field, type, parent); if (encloses(enclosingElement)) { int offset = field.sourceStart; SearchMatch match = newDeclarationMatch(enclosingElement, field.binding, accuracy, offset, field.sourceEnd-offset+1); if (field.initialization instanceof AllocationExpression) { reportAccurateEnumConstructorReference(match, field, (AllocationExpression) field.initialization); } else { report(match); } } } // handle the nodes for the local type first if ((field.bits & ASTNode.HasLocalType) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } // Traverse field declaration(s) to report matches both in local types declaration // and in local variables declaration int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position; ASTNode[] nodes = typeInHierarchy ? nodeSet.matchingNodes(field.sourceStart, fieldEnd) : null; boolean report = (this.matchContainer & PatternLocator.FIELD_CONTAINER) != 0 && encloses(enclosingElement); MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, report ? nodes : null, nodeSet, this); try { field.traverse(declarationVisitor, (MethodScope) null); } catch (WrappedCoreException e) { throw e.coreException; } // Report all nodes and remove them if (nodes != null) { int length = nodes.length; for (int i = 0; i < length; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (report && level != null) { if (node instanceof TypeDeclaration) { // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174) AllocationExpression allocation = ((TypeDeclaration)node).allocation; if (allocation != null && allocation.enumConstant != null) { node = field; } } this.patternLocator.matchReportReference(node, enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), field.binding, level.intValue(), this); } } } } // report annotations IJavaElement[] otherElements = null; if (field.annotations != null) { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } if (otherFields != null) { otherElements = createHandles(otherFields, type, parent); } reportMatching(field.annotations, enclosingElement, otherElements, field.binding, nodeSet, true, true); } if (typeInHierarchy) { // Look at field declaration if (field.endPart1Position != 0) { // not necessary if field is an initializer ASTNode[] nodes = nodeSet.matchingNodes(field.declarationSourceStart, field.endPart1Position); if (nodes != null) { if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { if (enclosingElement == null) enclosingElement = createHandle(field, type, parent); if (encloses(enclosingElement)) { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (otherFields != null && otherElements == null) { otherElements = createHandles(otherFields, type, parent); } this.patternLocator.matchReportReference(node, enclosingElement, null, otherElements, field.binding, level.intValue(), this); } } } } } // Look in initializer int fieldEnd = field.endPart2Position == 0 ? field.declarationSourceEnd : field.endPart2Position; ASTNode[] nodes = nodeSet.matchingNodes(field.sourceStart, fieldEnd); if (nodes != null) { if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) { nodeSet.matchingNodes.removeKey(nodes[i]); } } else { if (enclosingElement == null) { enclosingElement = createHandle(field, type, parent); } if (encloses(enclosingElement)) { MemberDeclarationVisitor declarationVisitor = new MemberDeclarationVisitor(enclosingElement, nodes, nodeSet, this); field.traverse(declarationVisitor, (MethodScope) null); int length = nodes.length; for (int i = 0; i < length; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (level != null) { // ensure that the reference has not been already reported while visiting if (node instanceof TypeDeclaration) { // use field declaration to report match (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=88174) AllocationExpression allocation = ((TypeDeclaration)node).allocation; if (allocation != null && allocation.enumConstant != null) { node = field; } } this.patternLocator.matchReportReference(node, enclosingElement, declarationVisitor.getLocalElement(i), declarationVisitor.getOtherElements(i), field.binding, level.intValue(), this); } } return; } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(TypeDeclaration type, IJavaElement parent, int accuracy, MatchingNodeSet nodeSet, int occurrenceCount) throws CoreException { // create type handle IJavaElement enclosingElement = parent; if (enclosingElement == null) { enclosingElement = createTypeHandle(new String(type.name)); } else if (enclosingElement instanceof IType) { enclosingElement = ((IType) parent).getType(new String(type.name)); } else if (enclosingElement instanceof IMember) { IMember member = (IMember) parent; if (member.isBinary()) { enclosingElement = ((IClassFile)this.currentPossibleMatch.openable).getType(); } else { enclosingElement = member.getType(new String(type.name), occurrenceCount); } } if (enclosingElement == null) return; boolean enclosesElement = encloses(enclosingElement); // report the type declaration if (accuracy > -1 && enclosesElement) { int offset = type.sourceStart; SearchMatch match = this.patternLocator.newDeclarationMatch(type, enclosingElement, type.binding, accuracy, type.sourceEnd-offset+1, this); report(match); } boolean matchedClassContainer = (this.matchContainer & PatternLocator.CLASS_CONTAINER) != 0; // report the type parameters if (type.typeParameters != null) { reportMatching(type.typeParameters, enclosingElement, parent, type.binding, nodeSet); } // report annotations if (type.annotations != null) { reportMatching(type.annotations, enclosingElement, null, type.binding, nodeSet, matchedClassContainer, enclosesElement); } // report references in javadoc if (type.javadoc != null) { ASTNode[] nodes = nodeSet.matchingNodes(type.declarationSourceStart, type.sourceStart); if (nodes != null) { if (!matchedClassContainer) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); if (enclosesElement) { this.patternLocator.matchReportReference(node, enclosingElement, null, null, type.binding, level.intValue(), this); } } } } } // super types if ((type.bits & ASTNode.IsAnonymousType) != 0) { TypeReference superType = type.allocation.type; if (superType != null) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(superType); if (level != null && matchedClassContainer) this.patternLocator.matchReportReference(superType, enclosingElement, null, null, type.binding, level.intValue(), this); } } else { TypeReference superClass = type.superclass; if (superClass != null) { reportMatchingSuper(superClass, enclosingElement, type.binding, nodeSet, matchedClassContainer); } TypeReference[] superInterfaces = type.superInterfaces; if (superInterfaces != null) { for (int i = 0, l = superInterfaces.length; i < l; i++) { reportMatchingSuper(superInterfaces[i], enclosingElement, type.binding, nodeSet, matchedClassContainer); } } } // filter out element not in hierarchy scope boolean typeInHierarchy = type.binding == null || typeInHierarchy(type.binding); matchedClassContainer = matchedClassContainer && typeInHierarchy; // Visit fields FieldDeclaration[] fields = type.fields; if (fields != null) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported FieldDeclaration[] otherFields = null; int first = -1; int length = fields.length; for (int i = 0; i < length; i++) { FieldDeclaration field = fields[i]; boolean last = field.endPart2Position == 0 || field.declarationEnd == field.endPart2Position; // Store first index of multiple field declaration if (!last) { if (first == -1) { first = i; } } if (first >= 0) { // Store all multiple fields but first one for other elements if (i > first) { if (otherFields == null) { otherFields = new FieldDeclaration[length-i]; } otherFields[i-1-first] = field; } // On last field, report match with all other elements if (last) { for (int j=first; j<=i; j++) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(fields[j]); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(fields[j], otherFields, type, enclosingElement, value, typeInHierarchy, nodeSet); } first = -1; otherFields = null; } } else { // Single field, report normally Integer level = (Integer) nodeSet.matchingNodes.removeKey(field); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(field, null, type, enclosingElement, value, typeInHierarchy, nodeSet); } } } // Visit methods AbstractMethodDeclaration[] methods = type.methods; if (methods != null) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported for (int i = 0, l = methods.length; i < l; i++) { AbstractMethodDeclaration method = methods[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(method); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(method, type, enclosingElement, value, typeInHierarchy, nodeSet); } } // Visit types TypeDeclaration[] memberTypes = type.memberTypes; if (memberTypes != null) { for (int i = 0, l = memberTypes.length; i < l; i++) { if (nodeSet.matchingNodes.elementSize == 0) return; // end as all matching nodes were reported TypeDeclaration memberType = memberTypes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(memberType); int value = (level != null && matchedClassContainer) ? level.intValue() : -1; reportMatching(memberType, enclosingElement, value, nodeSet, 1); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatching(TypeParameter[] typeParameters, IJavaElement enclosingElement, IJavaElement parent, Binding binding, MatchingNodeSet nodeSet) throws CoreException { if (typeParameters == null) return; for (int i=0, l=typeParameters.length; i<l; i++) { TypeParameter typeParameter = typeParameters[i]; if (typeParameter != null) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(typeParameter); if (level != null) { if (level.intValue() > -1 && encloses(enclosingElement)) { int offset = typeParameter.sourceStart; SearchMatch match = this.patternLocator.newDeclarationMatch(typeParameter, enclosingElement, binding, level.intValue(), typeParameter.sourceEnd-offset+1, this); report(match); } } if (typeParameter.type != null) { level = (Integer) nodeSet.matchingNodes.removeKey(typeParameter.type); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeParameter.type, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeParameter.type instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference paramSTR = (ParameterizedSingleTypeReference) typeParameter.type; if (paramSTR.typeArguments != null) { int length = paramSTR.typeArguments.length; for (int k=0; k<length; k++) { TypeReference typeArgument = paramSTR.typeArguments[k]; level = (Integer) nodeSet.matchingNodes.removeKey(typeArgument); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeArgument, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeArgument instanceof Wildcard) { TypeReference wildcardBound = ((Wildcard) typeArgument).bound; if (wildcardBound != null) { level = (Integer) nodeSet.matchingNodes.removeKey(wildcardBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(wildcardBound, enclosingElement, localElement, null, binding, level.intValue(), this); } } } } } } } if (typeParameter.bounds != null) { for (int j=0, b=typeParameter.bounds.length; j<b; j++) { TypeReference typeParameterBound = typeParameter.bounds[j]; level = (Integer) nodeSet.matchingNodes.removeKey(typeParameterBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeParameterBound, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeParameterBound instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference paramSTR = (ParameterizedSingleTypeReference) typeParameterBound; if (paramSTR.typeArguments != null) { int length = paramSTR.typeArguments.length; for (int k=0; k<length; k++) { TypeReference typeArgument = paramSTR.typeArguments[k]; level = (Integer) nodeSet.matchingNodes.removeKey(typeArgument); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(typeArgument, enclosingElement, localElement, null, binding, level.intValue(), this); } if (typeArgument instanceof Wildcard) { TypeReference wildcardBound = ((Wildcard) typeArgument).bound; if (wildcardBound != null) { level = (Integer) nodeSet.matchingNodes.removeKey(wildcardBound); if (level != null) { IJavaElement localElement = createHandle(typeParameter, enclosingElement); this.patternLocator.matchReportReference(wildcardBound, enclosingElement, localElement, null, binding, level.intValue(), this); } } } } } } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void reportMatchingSuper(TypeReference superReference, IJavaElement enclosingElement, Binding elementBinding, MatchingNodeSet nodeSet, boolean matchedClassContainer) throws CoreException { ASTNode[] nodes = null; if (superReference instanceof ParameterizedSingleTypeReference || superReference instanceof ParameterizedQualifiedTypeReference) { long lastTypeArgumentInfo = findLastTypeArgumentInfo(superReference); nodes = nodeSet.matchingNodes(superReference.sourceStart, (int)lastTypeArgumentInfo); } if (nodes != null) { if ((this.matchContainer & PatternLocator.CLASS_CONTAINER) == 0) { for (int i = 0, l = nodes.length; i < l; i++) nodeSet.matchingNodes.removeKey(nodes[i]); } else { if (encloses(enclosingElement)) for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); this.patternLocator.matchReportReference(node, enclosingElement, null, null, elementBinding, level.intValue(), this); } } } else if (encloses(enclosingElement)) { Integer level = (Integer) nodeSet.matchingNodes.removeKey(superReference); if (level != null && matchedClassContainer) this.patternLocator.matchReportReference(superReference, enclosingElement, null, null, elementBinding, level.intValue(), this); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { int level = resolveLevel(binding); if (level >= INACCURATE_MATCH) { matchReportImportRef( importRef, binding, locator.createImportHandle(importRef), level == ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (locator.encloses(element)) { // default is to report a match as a regular ref. this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { this.match = null; int referenceType = referenceType(); int offset = reference.sourceStart; switch (referenceType) { case IJavaElement.PACKAGE_FRAGMENT: this.match = locator.newPackageReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.TYPE: this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.FIELD: this.match = locator.newFieldReferenceMatch(element, null, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.LOCAL_VARIABLE: this.match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; case IJavaElement.TYPE_PARAMETER: this.match = locator.newTypeParameterReferenceMatch(element, accuracy, offset, reference.sourceEnd-offset+1, reference); break; } if (this.match != null) { locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/PatternLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { if (importRef.isStatic() && binding instanceof MethodBinding) { super.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { MethodBinding methodBinding = (reference instanceof MessageSend) ? ((MessageSend)reference).binding: ((elementBinding instanceof MethodBinding) ? (MethodBinding) elementBinding : null); if (this.isDeclarationOfReferencedMethodsPattern) { if (methodBinding == null) return; // need exact match to be able to open on type ref if (accuracy != SearchMatch.A_ACCURATE) return; // element that references the method must be included in the enclosing element DeclarationOfReferencedMethodsPattern declPattern = (DeclarationOfReferencedMethodsPattern) this.pattern; while (element != null && !declPattern.enclosingElement.equals(element)) element = element.getParent(); if (element != null) { reportDeclaration(methodBinding, locator, declPattern.knownMethods); } } else { MethodReferenceMatch methodReferenceMatch = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, false /*not constructor*/, false/*not synthetic*/, reference); methodReferenceMatch.setLocalElement(localElement); this.match = methodReferenceMatch; if (this.pattern.findReferences && reference instanceof MessageSend) { IJavaElement focus = this.pattern.focus; // verify closest match if pattern was bound // (see bug 70827) if (focus != null && focus.getElementType() == IJavaElement.METHOD) { if (methodBinding != null && methodBinding.declaringClass != null) { boolean isPrivate = Flags.isPrivate(((IMethod) focus).getFlags()); if (isPrivate && !CharOperation.equals(methodBinding.declaringClass.sourceName, focus.getParent().getElementName().toCharArray())) { return; // finally the match was not possible } } } matchReportReference((MessageSend)reference, locator, ((MessageSend)reference).binding); } else { if (reference instanceof SingleMemberAnnotation) { reference = ((SingleMemberAnnotation)reference).memberValuePairs()[0]; this.match.setImplicit(true); } int offset = reference.sourceStart; int length = reference.sourceEnd - offset + 1; this.match.setOffset(offset); this.match.setLength(length); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
void matchReportReference(MessageSend messageSend, MatchLocator locator, MethodBinding methodBinding) throws CoreException { // Look if there's a need to special report for parameterized type boolean isParameterized = false; if (methodBinding instanceof ParameterizedGenericMethodBinding) { // parameterized generic method isParameterized = true; // Update match regarding method type arguments ParameterizedGenericMethodBinding parameterizedMethodBinding = (ParameterizedGenericMethodBinding) methodBinding; this.match.setRaw(parameterizedMethodBinding.isRaw); TypeBinding[] typeArguments = /*parameterizedMethodBinding.isRaw ? null :*/ parameterizedMethodBinding.typeArguments; updateMatch(typeArguments, locator, this.pattern.methodArguments, this.pattern.hasMethodParameters()); // Update match regarding declaring class type arguments if (methodBinding.declaringClass.isParameterizedType() || methodBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)methodBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasMethodArguments() || parameterizedBinding.isParameterizedWithOwnVariables()) { // special case for pattern which defines method arguments but not its declaring type // in this case, we do not refine accuracy using declaring type arguments...! } else { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding method parameters // TODO ? (frederic) // Update match regarding method return type // TODO ? (frederic) // Special case for errors if (this.match.getRule() != 0 && messageSend.resolvedType == null) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } } else if (methodBinding instanceof ParameterizedMethodBinding) { isParameterized = true; if (methodBinding.declaringClass.isParameterizedType() || methodBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)methodBinding.declaringClass; if (!parameterizedBinding.isParameterizedWithOwnVariables()) { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding method parameters // TODO ? (frederic) // Update match regarding method return type // TODO ? (frederic) // Special case for errors if (this.match.getRule() != 0 && messageSend.resolvedType == null) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } } else if (this.pattern.hasMethodArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Report match int offset = (int) (messageSend.nameSourcePosition >>> 32); this.match.setOffset(offset); this.match.setLength(messageSend.sourceEnd - offset + 1); if (isParameterized && this.pattern.hasMethodArguments()) { locator.reportAccurateParameterizedMethodReference(this.match, messageSend, messageSend.typeArguments); } else { locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
protected void reportDeclaration(MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods) throws CoreException { ReferenceBinding declaringClass = methodBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type // Report match for binary if (type.isBinary()) { IMethod method = null; TypeBinding[] parameters = methodBinding.original().parameters; int parameterLength = parameters.length; char[][] parameterTypes = new char[parameterLength][]; for (int i = 0; i<parameterLength; i++) { char[] typeName = parameters[i].qualifiedSourceName(); for (int j=0, dim=parameters[i].dimensions(); j<dim; j++) { typeName = CharOperation.concat(typeName, new char[] {'[', ']'}); } parameterTypes[i] = typeName; } method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; IResource resource = type.getResource(); if (resource == null) resource = type.getJavaProject().getProject(); IBinaryType info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile)type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, method, methodBinding, info, SearchMatch.A_ACCURATE); return; } // When source is available, report match if method is found in the declaring type IResource resource = type.getResource(); if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(methodBinding.original()); if (methodDecl != null) { // Create method handle from method declaration String methodName = new String(methodBinding.selector); Argument[] arguments = methodDecl.arguments; int length = arguments == null ? 0 : arguments.length; String[] parameterTypes = new String[length]; for (int i = 0; i < length; i++) { char[][] typeName = arguments[i].type.getParameterizedTypeName(); parameterTypes[i] = Signature.createTypeSignature(CharOperation.concatWith(typeName, '.'), false); } IMethod method = type.getMethod(methodName, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; // Create and report corresponding match int offset = methodDecl.sourceStart; this.match = new MethodDeclarationMatch(method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields Binding refBinding = binding; if (importRef.isStatic()) { if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } } // Look for closest pattern PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { PatternLocator patternLocator = this.patternLocators[i]; int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(refBinding); if (newLevel > level) { closestPattern = patternLocator; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) { closestPattern.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { int newLevel = this.patternLocators[i].matchLevel(importRef); if (newLevel > level) { closestPattern = this.patternLocators[i]; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) closestPattern.matchReportImportRef(importRef, binding, element, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { PatternLocator closestPattern = null; int level = IMPOSSIBLE_MATCH; for (int i = 0, length = this.patternLocators.length; i < length; i++) { PatternLocator patternLocator = this.patternLocators[i]; int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference); if (newLevel > level) { closestPattern = patternLocator; if (newLevel == ACCURATE_MATCH) break; level = newLevel; } } if (closestPattern != null) closestPattern.matchReportReference(reference, element, localElement, otherElements, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/OrLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { Binding refBinding = binding; if (importRef.isStatic()) { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } } super.matchLevelAndReportImportRef(importRef, refBinding, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (binding == null) { this.matchReportReference(importRef, element, null/*no binding*/, accuracy, locator); } else { if (locator.encloses(element)) { long[] positions = importRef.sourcePositions; int last = positions.length - 1; if (binding instanceof ProblemReferenceBinding) binding = ((ProblemReferenceBinding) binding).closestMatch(); if (binding instanceof ReferenceBinding) { PackageBinding pkgBinding = ((ReferenceBinding) binding).fPackage; if (pkgBinding != null) last = pkgBinding.compoundName.length; } if (binding instanceof PackageBinding) last = ((PackageBinding) binding).compoundName.length; int start = (int) (positions[0] >>> 32); int end = (int) positions[last - 1]; this.match = locator.newPackageReferenceMatch(element, accuracy, start, end-start+1, importRef); locator.report(this.match); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { long[] positions = null; int last = -1; if (reference instanceof ImportReference) { ImportReference importRef = (ImportReference) reference; positions = importRef.sourcePositions; last = (importRef.bits & ASTNode.OnDemand) != 0 ? positions.length : positions.length - 1; } else { TypeBinding typeBinding = null; if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; positions = qNameRef.sourcePositions; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; break; case Binding.TYPE : //=============only type ============== if (qNameRef.binding instanceof TypeBinding) typeBinding = (TypeBinding) qNameRef.binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : Binding binding = qNameRef.binding; if (binding instanceof TypeBinding) { typeBinding = (TypeBinding) binding; } else if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; last = qNameRef.tokens.length - (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2); } else if (binding instanceof ProblemBinding) { ProblemBinding pbBinding = (ProblemBinding) binding; typeBinding = pbBinding.searchType; last = CharOperation.occurencesOf('.', pbBinding.name); } break; } } else if (reference instanceof QualifiedTypeReference) { QualifiedTypeReference qTypeRef = (QualifiedTypeReference) reference; positions = qTypeRef.sourcePositions; typeBinding = qTypeRef.resolvedType; } else if (reference instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference jsTypeRef = (JavadocSingleTypeReference) reference; positions = new long[1]; positions[0] = (((long)jsTypeRef.sourceStart) << 32) + jsTypeRef.sourceEnd; typeBinding = jsTypeRef.resolvedType; } if (positions == null) return; if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding instanceof ProblemReferenceBinding) typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch(); if (typeBinding instanceof ReferenceBinding) { PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage; if (pkgBinding != null) last = pkgBinding.compoundName.length; } // Do not report qualified references which are only enclosing type // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=91078) ReferenceBinding enclosingType = typeBinding == null ? null: typeBinding.enclosingType(); if (enclosingType != null) { int length = positions.length; while (enclosingType != null && length > 0) { length--; enclosingType = enclosingType.enclosingType(); } if (length <= 1) return; } } if (last == -1) { last = this.pattern.segments.length; } if (last == 0) return; if (last > positions.length) last = positions.length; int sourceStart = (int) (positions[0] >>> 32); int sourceEnd = ((int) positions[last - 1]); PackageReferenceMatch packageReferenceMatch = locator.newPackageReferenceMatch(element, accuracy, sourceStart, sourceEnd-sourceStart+1, reference); packageReferenceMatch.setLocalElement(localElement); this.match = packageReferenceMatch; locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/matching/LocalVariableLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { int offset = -1; int length = -1; if (reference instanceof SingleNameReference) { offset = reference.sourceStart; length = reference.sourceEnd-offset+1; } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; long sourcePosition = qNameRef.sourcePositions[0]; offset = (int) (sourcePosition >>> 32); length = ((int) sourcePosition) - offset +1; } else if (reference instanceof LocalDeclaration) { LocalVariable localVariable = getLocalVariable(); offset = localVariable.nameStart; length = localVariable.nameEnd-offset+1; element = localVariable; this.match = locator.newDeclarationMatch(element, null, accuracy, offset, length); locator.report(this.match); return; } if (offset >= 0) { this.match = locator.newLocalVariableReferenceMatch(element, accuracy, offset, length, reference); locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (elementBinding instanceof ReferenceBinding) { ReferenceBinding referenceBinding = (ReferenceBinding) elementBinding; if (referenceBinding.isClass() && this.pattern.typeSuffix == IIndexConstants.INTERFACE_SUFFIX) { // do not report class if expected types are only interfaces return; } if (referenceBinding.isInterface() && this.pattern.typeSuffix == IIndexConstants.CLASS_SUFFIX) { // do not report interface if expected types are only classes return; } } super.matchReportReference(reference, element, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { if (importRef.isStatic() && binding instanceof FieldBinding) { super.matchLevelAndReportImportRef(importRef, binding, locator); } }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements,Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfAccessedFieldsPattern) { // need exact match to be able to open on type ref if (accuracy != SearchMatch.A_ACCURATE) return; // element that references the field must be included in the enclosing element DeclarationOfAccessedFieldsPattern declPattern = (DeclarationOfAccessedFieldsPattern) this.pattern; while (element != null && !declPattern.enclosingElement.equals(element)) element = element.getParent(); if (element != null) { if (reference instanceof FieldReference) { reportDeclaration(((FieldReference) reference).binding, locator, declPattern.knownFields); } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; Binding nameBinding = qNameRef.binding; if (nameBinding instanceof FieldBinding) reportDeclaration((FieldBinding)nameBinding, locator, declPattern.knownFields); int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length; for (int i = 0; i < otherMax; i++) reportDeclaration(qNameRef.otherBindings[i], locator, declPattern.knownFields); } else if (reference instanceof SingleNameReference) { reportDeclaration((FieldBinding)((SingleNameReference) reference).binding, locator, declPattern.knownFields); } } } else if (reference instanceof ImportReference) { ImportReference importRef = (ImportReference) reference; long[] positions = importRef.sourcePositions; int lastIndex = importRef.tokens.length - 1; int start = (int) ((positions[lastIndex]) >>> 32); int end = (int) positions[lastIndex]; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start, end-start+1, importRef); locator.report(this.match); } else if (reference instanceof FieldReference) { FieldReference fieldReference = (FieldReference) reference; long position = fieldReference.nameSourcePosition; int start = (int) (position >>> 32); int end = (int) position; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, start, end-start+1, fieldReference); locator.report(this.match); } else if (reference instanceof SingleNameReference) { int offset = reference.sourceStart; this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, offset, reference.sourceEnd-offset+1, reference); locator.report(this.match); } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; int length = qNameRef.tokens.length; SearchMatch[] matches = new SearchMatch[length]; Binding nameBinding = qNameRef.binding; int indexOfFirstFieldBinding = qNameRef.indexOfFirstFieldBinding > 0 ? qNameRef.indexOfFirstFieldBinding-1 : 0; // first token if (matchesName(this.pattern.name, qNameRef.tokens[indexOfFirstFieldBinding]) && !(nameBinding instanceof LocalVariableBinding)) { FieldBinding fieldBinding = nameBinding instanceof FieldBinding ? (FieldBinding) nameBinding : null; if (fieldBinding == null) { matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, -1, -1, reference); } else { switch (matchField(fieldBinding, false)) { case ACCURATE_MATCH: matches[indexOfFirstFieldBinding] = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference); break; case INACCURATE_MATCH: this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference); if (fieldBinding.type != null && fieldBinding.type.isParameterizedType() && this.pattern.hasTypeArguments()) { updateMatch((ParameterizedTypeBinding) fieldBinding.type, this.pattern.getTypeArguments(), locator); } matches[indexOfFirstFieldBinding] = this.match; break; } } } // other tokens for (int i = indexOfFirstFieldBinding+1; i < length; i++) { char[] token = qNameRef.tokens[i]; if (matchesName(this.pattern.name, token)) { FieldBinding otherBinding = qNameRef.otherBindings == null ? null : qNameRef.otherBindings[i-(indexOfFirstFieldBinding+1)]; if (otherBinding == null) { matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding, accuracy, -1, -1, reference); } else { switch (matchField(otherBinding, false)) { case ACCURATE_MATCH: matches[i] = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_ACCURATE, -1, -1, reference); break; case INACCURATE_MATCH: this.match = locator.newFieldReferenceMatch(element, localElement, elementBinding, SearchMatch.A_INACCURATE, -1, -1, reference); if (otherBinding.type != null && otherBinding.type.isParameterizedType() && this.pattern.hasTypeArguments()) { updateMatch((ParameterizedTypeBinding) otherBinding.type, this.pattern.getTypeArguments(), locator); } matches[i] = this.match; break; } } } } locator.reportAccurateFieldReference(matches, qNameRef); } }
// in search/org/eclipse/jdt/internal/core/search/matching/FieldLocator.java
protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields) throws CoreException { // ignore length field if (fieldBinding == ArrayBinding.ArrayLength) return; ReferenceBinding declaringClass = fieldBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type char[] bindingName = fieldBinding.name; IField field = type.getField(new String(bindingName)); if (knownFields.addIfNotIncluded(field) == null) return; IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null; if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE); } else { if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; FieldDeclaration fieldDecl = null; FieldDeclaration[] fieldDecls = typeDecl.fields; int length = fieldDecls == null ? 0 : fieldDecls.length; for (int i = 0; i < length; i++) { if (CharOperation.equals(bindingName, fieldDecls[i].name)) { fieldDecl = fieldDecls[i]; break; } } if (fieldDecl != null) { int offset = fieldDecl.sourceStart; this.match = new FieldDeclarationMatch(((JavaElement) field).resolved(fieldBinding), SearchMatch.A_ACCURATE, offset, fieldDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException { Binding refBinding = binding; if (importRef.isStatic()) { // for static import, binding can be a field binding or a member type binding // verify that in this case binding is static and use declaring class for fields if (binding instanceof FieldBinding) { FieldBinding fieldBinding = (FieldBinding) binding; if (!fieldBinding.isStatic()) return; refBinding = fieldBinding.declaringClass; } else if (binding instanceof MethodBinding) { MethodBinding methodBinding = (MethodBinding) binding; if (!methodBinding.isStatic()) return; refBinding = methodBinding.declaringClass; } else if (binding instanceof MemberTypeBinding) { MemberTypeBinding memberBinding = (MemberTypeBinding) binding; if (!memberBinding.isStatic()) return; } // resolve and report int level = resolveLevel(refBinding); if (level >= INACCURATE_MATCH) { matchReportImportRef( importRef, binding, locator.createImportHandle(importRef), level == ACCURATE_MATCH ? SearchMatch.A_ACCURATE : SearchMatch.A_INACCURATE, locator); } return; } super.matchLevelAndReportImportRef(importRef, refBinding, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportImportRef(ImportReference importRef, Binding binding, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfReferencedTypesPattern) { if ((element = findElement(element, accuracy)) != null) { SimpleSet knownTypes = ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes; while (binding instanceof ReferenceBinding) { ReferenceBinding typeBinding = (ReferenceBinding) binding; reportDeclaration(typeBinding, 1, locator, knownTypes); binding = typeBinding.enclosingType(); } } return; } // return if this is not necessary to report if (this.pattern.hasTypeArguments() && !this.isEquivalentMatch &&!this.isErasureMatch) { return; } // Return if fine grain is on and does not concern import reference if ((this.pattern.fineGrain != 0 && (this.pattern.fineGrain & IJavaSearchConstants.IMPORT_DECLARATION_TYPE_REFERENCE) == 0)) { return; } // Create search match this.match = locator.newTypeReferenceMatch(element, binding, accuracy, importRef); // set match raw flag and rule this.match.setRaw(true); if (this.pattern.hasTypeArguments()) { // binding is raw => only compatible erasure if pattern has type arguments this.match.setRule(this.match.getRule() & (~SearchPattern.R_FULL_MATCH)); } // Try to find best selection for match TypeBinding typeBinding = null; boolean lastButOne = false; if (binding instanceof ReferenceBinding) { typeBinding = (ReferenceBinding) binding; } else if (binding instanceof FieldBinding) { // may happen for static import typeBinding = ((FieldBinding)binding).declaringClass; lastButOne = importRef.isStatic() && ((importRef.bits & ASTNode.OnDemand) == 0); } else if (binding instanceof MethodBinding) { // may happen for static import typeBinding = ((MethodBinding)binding).declaringClass; lastButOne = importRef.isStatic() && ((importRef.bits & ASTNode.OnDemand) == 0); } if (typeBinding != null) { int lastIndex = importRef.tokens.length - 1; if (lastButOne) { // for field or method static import, use last but one token lastIndex--; } if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // try to match all enclosing types for which the token matches as well. while (typeBinding != null && lastIndex >= 0) { if (resolveLevelForType(typeBinding) != IMPOSSIBLE_MATCH) { if (locator.encloses(element)) { long[] positions = importRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; // report match this.match.setOffset(start); this.match.setLength(end-start+1); locator.report(this.match); } return; } lastIndex--; typeBinding = typeBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, importRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ArrayTypeReference arrayRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.pattern.simpleName == null) { // TODO (frederic) need to add a test for this case while searching generic types... if (locator.encloses(element)) { int offset = arrayRef.sourceStart; int length = arrayRef.sourceEnd-offset+1; if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, offset, length, arrayRef); } else { this.match.setOffset(offset); this.match.setLength(length); } locator.report(this.match); return; } } this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, arrayRef); if (arrayRef.resolvedType != null) { matchReportReference(arrayRef, -1, arrayRef.resolvedType.leafComponentType(), locator); return; } locator.reportAccurateTypeReference(this.match, arrayRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { matchReportReference(reference, element, null, null, elementBinding, accuracy, locator); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { if (this.isDeclarationOfReferencedTypesPattern) { if ((element = findElement(element, accuracy)) != null) reportDeclaration(reference, element, locator, ((DeclarationOfReferencedTypesPattern) this.pattern).knownTypes); return; } // Create search match TypeReferenceMatch refMatch = locator.newTypeReferenceMatch(element, elementBinding, accuracy, reference); refMatch.setLocalElement(localElement); refMatch.setOtherElements(otherElements); this.match = refMatch; // Report match depending on reference type if (reference instanceof QualifiedNameReference) matchReportReference((QualifiedNameReference) reference, element, elementBinding, accuracy, locator); else if (reference instanceof QualifiedTypeReference) matchReportReference((QualifiedTypeReference) reference, element, elementBinding, accuracy, locator); else if (reference instanceof ArrayTypeReference) matchReportReference((ArrayTypeReference) reference, element, elementBinding, accuracy, locator); else { TypeBinding typeBinding = reference instanceof Expression ? ((Expression)reference).resolvedType : null; if (typeBinding != null) { matchReportReference((Expression)reference, -1, typeBinding, locator); return; } locator.report(this.match); } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(QualifiedNameReference qNameRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { Binding binding = qNameRef.binding; TypeBinding typeBinding = null; int lastIndex = qNameRef.tokens.length - 1; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; break; case Binding.TYPE : //=============only type ============== if (binding instanceof TypeBinding) typeBinding = (TypeBinding) binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : if (binding instanceof ProblemReferenceBinding) { typeBinding = (TypeBinding) binding; } else if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; } else if (binding instanceof ProblemBinding) { typeBinding = ((ProblemBinding) binding).searchType; } break; } if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // Create search match to report if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qNameRef); } // try to match all enclosing types for which the token matches as well. if (typeBinding instanceof ReferenceBinding) { ReferenceBinding refBinding = (ReferenceBinding) typeBinding; while (refBinding != null && lastIndex >= 0) { if (resolveLevelForType(refBinding) == ACCURATE_MATCH) { if (locator.encloses(element)) { long[] positions = qNameRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; this.match.setOffset(start); this.match.setLength(end-start+1); // Look if there's a need to special report for parameterized type matchReportReference(qNameRef, lastIndex, refBinding, locator); } return; } lastIndex--; refBinding = refBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, qNameRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void matchReportReference(QualifiedTypeReference qTypeRef, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { TypeBinding typeBinding = qTypeRef.resolvedType; int lastIndex = qTypeRef.tokens.length - 1; if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding instanceof ProblemReferenceBinding) { ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding; typeBinding = pbBinding.closestMatch(); lastIndex = pbBinding.compoundName.length - 1; } // Create search match to report if (this.match == null) { this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qTypeRef); } // try to match all enclosing types for which the token matches as well if (typeBinding instanceof ReferenceBinding) { ReferenceBinding refBinding = (ReferenceBinding) typeBinding; while (refBinding != null && lastIndex >= 0) { if (resolveLevelForType(refBinding) != IMPOSSIBLE_MATCH) { if (locator.encloses(element)) { long[] positions = qTypeRef.sourcePositions; // index now depends on pattern type signature int index = lastIndex; if (this.pattern.qualification != null) { index = lastIndex - this.pattern.segmentsSize; } if (index < 0) index = 0; int start = (int) ((positions[index]) >>> 32); int end = (int) positions[lastIndex]; this.match.setOffset(start); this.match.setLength(end-start+1); // Look if there's a need to special report for parameterized type matchReportReference(qTypeRef, lastIndex, refBinding, locator); } return; } lastIndex--; refBinding = refBinding.enclosingType(); } } locator.reportAccurateTypeReference(this.match, qTypeRef, this.pattern.simpleName); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
void matchReportReference(Expression expr, int lastIndex, TypeBinding refBinding, MatchLocator locator) throws CoreException { // Look if there's a need to special report for parameterized type if (refBinding.isParameterizedType() || refBinding.isRawType()) { // Try to refine accuracy ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)refBinding; updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Make a special report for parameterized types if necessary if (refBinding.isParameterizedType() && this.pattern.hasTypeArguments()) { TypeReference typeRef = null; TypeReference[] typeArguments = null; if (expr instanceof ParameterizedQualifiedTypeReference) { typeRef = (ParameterizedQualifiedTypeReference) expr; typeArguments = ((ParameterizedQualifiedTypeReference) expr).typeArguments[lastIndex]; } else if (expr instanceof ParameterizedSingleTypeReference) { typeRef = (ParameterizedSingleTypeReference) expr; typeArguments = ((ParameterizedSingleTypeReference) expr).typeArguments; } if (typeRef != null) { locator.reportAccurateParameterizedTypeReference(this.match, typeRef, lastIndex, typeArguments); return; } } } else if (this.pattern.hasTypeArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Report match if (expr instanceof ArrayTypeReference) { locator.reportAccurateTypeReference(this.match, expr, this.pattern.simpleName); return; } if (refBinding.isLocalType()) { // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=82673 LocalTypeBinding local = (LocalTypeBinding) refBinding.erasure(); IJavaElement focus = this.pattern.focus; if (focus != null && local.enclosingMethod != null && focus.getParent().getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) focus.getParent(); if (!CharOperation.equals(local.enclosingMethod.selector, method.getElementName().toCharArray())) { return; } } } if (this.pattern.simpleName == null) { this.match.setOffset(expr.sourceStart); this.match.setLength(expr.sourceEnd-expr.sourceStart+1); } locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void reportDeclaration(ASTNode reference, IJavaElement element, MatchLocator locator, SimpleSet knownTypes) throws CoreException { int maxType = -1; TypeBinding typeBinding = null; if (reference instanceof TypeReference) { typeBinding = ((TypeReference) reference).resolvedType; maxType = Integer.MAX_VALUE; } else if (reference instanceof QualifiedNameReference) { QualifiedNameReference qNameRef = (QualifiedNameReference) reference; Binding binding = qNameRef.binding; maxType = qNameRef.tokens.length - 1; switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) { case Binding.FIELD : // reading a field typeBinding = qNameRef.actualReceiverType; maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; break; case Binding.TYPE : //=============only type ============== if (binding instanceof TypeBinding) typeBinding = (TypeBinding) binding; break; case Binding.VARIABLE : //============unbound cases=========== case Binding.TYPE | Binding.VARIABLE : if (binding instanceof ProblemFieldBinding) { typeBinding = qNameRef.actualReceiverType; maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1; } else if (binding instanceof ProblemBinding) { ProblemBinding pbBinding = (ProblemBinding) binding; typeBinding = pbBinding.searchType; // second chance with recorded type so far char[] partialQualifiedName = pbBinding.name; maxType = CharOperation.occurencesOf('.', partialQualifiedName) - 1; // index of last bound token is one before the pb token if (typeBinding == null || maxType < 0) return; } break; } } else if (reference instanceof SingleNameReference) { typeBinding = (TypeBinding) ((SingleNameReference) reference).binding; maxType = 1; } if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding) typeBinding).leafComponentType; if (typeBinding == null || typeBinding instanceof BaseTypeBinding) return; if (typeBinding instanceof ProblemReferenceBinding) { TypeBinding original = typeBinding.closestMatch(); if (original == null) return; // original may not be set (bug 71279) typeBinding = original; } typeBinding = typeBinding.erasure(); reportDeclaration((ReferenceBinding) typeBinding, maxType, locator, knownTypes); }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeReferenceLocator.java
protected void reportDeclaration(ReferenceBinding typeBinding, int maxType, MatchLocator locator, SimpleSet knownTypes) throws CoreException { IType type = locator.lookupType(typeBinding); if (type == null) return; // case of a secondary type IResource resource = type.getResource(); boolean isBinary = type.isBinary(); IBinaryType info = null; if (isBinary) { if (resource == null) resource = type.getJavaProject().getProject(); info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); } while (maxType >= 0 && type != null) { if (!knownTypes.includes(type)) { if (isBinary) { locator.reportBinaryMemberDeclaration(resource, type, typeBinding, info, SearchMatch.A_ACCURATE); } else { if (typeBinding instanceof ParameterizedTypeBinding) typeBinding = ((ParameterizedTypeBinding) typeBinding).genericType(); ClassScope scope = ((SourceTypeBinding) typeBinding).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; int offset = typeDecl.sourceStart; this.match = new TypeDeclarationMatch(((JavaElement) type).resolved(typeBinding), SearchMatch.A_ACCURATE, offset, typeDecl.sourceEnd-offset+1, locator.getParticipant(), resource); locator.report(this.match); } } knownTypes.add(type); } typeBinding = typeBinding.enclosingType(); IJavaElement parent = type.getParent(); if (parent instanceof IType) { type = (IType)parent; } else { type = null; } maxType--; } }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorLocator.java
protected void matchReportReference(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { MethodBinding constructorBinding = null; boolean isSynthetic = false; if (reference instanceof ExplicitConstructorCall) { ExplicitConstructorCall call = (ExplicitConstructorCall) reference; isSynthetic = call.isImplicitSuper(); constructorBinding = call.binding; } else if (reference instanceof AllocationExpression) { AllocationExpression alloc = (AllocationExpression) reference; constructorBinding = alloc.binding; } else if (reference instanceof TypeDeclaration || reference instanceof FieldDeclaration) { super.matchReportReference(reference, element, elementBinding, accuracy, locator); if (this.match != null) return; } // Create search match this.match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, true, isSynthetic, reference); // Look to refine accuracy if (constructorBinding instanceof ParameterizedGenericMethodBinding) { // parameterized generic method // Update match regarding constructor type arguments ParameterizedGenericMethodBinding parameterizedMethodBinding = (ParameterizedGenericMethodBinding) constructorBinding; this.match.setRaw(parameterizedMethodBinding.isRaw); TypeBinding[] typeBindings = parameterizedMethodBinding.isRaw ? null : parameterizedMethodBinding.typeArguments; updateMatch(typeBindings, locator, this.pattern.constructorArguments, this.pattern.hasConstructorParameters()); // Update match regarding declaring class type arguments if (constructorBinding.declaringClass.isParameterizedType() || constructorBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)constructorBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasConstructorArguments() || parameterizedBinding.isParameterizedWithOwnVariables()) { // special case for constructor pattern which defines arguments but no type // in this case, we only use refined accuracy for constructor } else if (this.pattern.hasTypeArguments() && !this.pattern.hasConstructorArguments()) { // special case for constructor pattern which defines no constructor arguments but has type ones // in this case, we do not use refined accuracy updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } else { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding constructor parameters // TODO ? (frederic) } else if (constructorBinding instanceof ParameterizedMethodBinding) { // Update match regarding declaring class type arguments if (constructorBinding.declaringClass.isParameterizedType() || constructorBinding.declaringClass.isRawType()) { ParameterizedTypeBinding parameterizedBinding = (ParameterizedTypeBinding)constructorBinding.declaringClass; if (!this.pattern.hasTypeArguments() && this.pattern.hasConstructorArguments()) { // special case for constructor pattern which defines arguments but no type updateMatch(parameterizedBinding, new char[][][] {this.pattern.constructorArguments}, this.pattern.hasTypeParameters(), 0, locator); } else if (!parameterizedBinding.isParameterizedWithOwnVariables()) { updateMatch(parameterizedBinding, this.pattern.getTypeArguments(), this.pattern.hasTypeParameters(), 0, locator); } } else if (this.pattern.hasTypeArguments()) { this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // Update match regarding constructor parameters // TODO ? (frederic) } else if (this.pattern.hasConstructorArguments()) { // binding has no type params, compatible erasure if pattern does this.match.setRule(SearchPattern.R_ERASURE_MATCH); } // See whether it is necessary to report or not if (this.match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && this.match.isErasure()) || (this.isEquivalentMatch && this.match.isEquivalent()) || this.match.isExact(); if (!report) return; // Report match int offset = reference.sourceStart; this.match.setOffset(offset); this.match.setLength(reference.sourceEnd - offset + 1); if (reference instanceof FieldDeclaration) { // enum declaration FieldDeclaration enumConstant = (FieldDeclaration) reference; if (enumConstant.initialization instanceof QualifiedAllocationExpression) { locator.reportAccurateEnumConstructorReference(this.match, enumConstant, (QualifiedAllocationExpression) enumConstant.initialization); return; } } locator.report(this.match); }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
public boolean execute(IProgressMonitor progressMonitor) { if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; if (!this.folder.isAccessible()) return true; // nothing to do Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index == null) return true; ReadWriteMonitor monitor = index.monitor; if (monitor == null) return true; // index got deleted since acquired try { monitor.enterRead(); // ask permission to read String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ int max = paths == null ? 0 : paths.length; final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max==0 ? 33 : max+11); final String OK = "OK"; //$NON-NLS-1$ final String DELETED = "DELETED"; //$NON-NLS-1$ if (paths == null) { this.folder.accept(new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, file); } return false; } return true; } }, IResource.NONE); } else { for (int i = 0; i < max; i++) { indexedFileNames.put(paths[i], DELETED); } final long indexLastModified = index.getIndexFile().lastModified(); this.folder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location != null) { String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, indexedFileNames.get(containerRelativePath) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } } return false; } return true; } }, IResource.NONE ); } Object[] names = indexedFileNames.keyTable; Object[] values = indexedFileNames.valueTable; for (int i = 0, length = names.length; i < length; i++) { String name = (String) names[i]; if (name != null) { if (this.isCancelled) return false; Object value = values[i]; if (value != OK) { if (value == DELETED) this.manager.remove(name, this.containerPath); else { this.manager.addBinary((IFile) value, this.containerPath); } } } } // request to save index when all class files have been indexed... also sets state to SAVED_STATE this.manager.request(new SaveIndex(this.containerPath, this.manager)); }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexBinaryFolder.this.isCancelled) return false; if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location != null) { String containerRelativePath = Util.relativePath(file.getFullPath(), IndexBinaryFolder.this.containerPath.segmentCount()); indexedFileNames.put(containerRelativePath, indexedFileNames.get(containerRelativePath) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } } return false; } return true; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
public boolean execute(IProgressMonitor progressMonitor) { if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; if (!this.project.isAccessible()) return true; // nothing to do ReadWriteMonitor monitor = null; try { // Get source folder entries. Libraries are done as a separate job JavaProject javaProject = (JavaProject)JavaCore.create(this.project); // Do not create marker while getting raw classpath (see bug 41859) IClasspathEntry[] entries = javaProject.getRawClasspath(); int length = entries.length; IClasspathEntry[] sourceEntries = new IClasspathEntry[length]; int sourceEntriesNumber = 0; for (int i = 0; i < length; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) sourceEntries[sourceEntriesNumber++] = entry; } if (sourceEntriesNumber == 0) { IPath projectPath = javaProject.getPath(); for (int i = 0; i < length; i++) { IClasspathEntry entry = entries[i]; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && entry.getPath().equals(projectPath)) { // the project is also a library folder (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89815) // ensure a job exists to index it as a binary folder this.manager.indexLibrary(projectPath, this.project); return true; } } // nothing to index but want to save an empty index file so its not 'rebuilt' when part of a search request Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index != null) this.manager.saveIndex(index); return true; } if (sourceEntriesNumber != length) System.arraycopy(sourceEntries, 0, sourceEntries = new IClasspathEntry[sourceEntriesNumber], 0, sourceEntriesNumber); Index index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); if (index == null) return true; monitor = index.monitor; if (monitor == null) return true; // index got deleted since acquired monitor.enterRead(); // ask permission to read String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ int max = paths == null ? 0 : paths.length; final SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11); final String OK = "OK"; //$NON-NLS-1$ final String DELETED = "DELETED"; //$NON-NLS-1$ if (paths != null) { for (int i = 0; i < max; i++) indexedFileNames.put(paths[i], DELETED); } final long indexLastModified = max == 0 ? 0L : index.getIndexFile().lastModified(); IWorkspaceRoot root = this.project.getWorkspace().getRoot(); for (int i = 0; i < sourceEntriesNumber; i++) { if (this.isCancelled) return false; IClasspathEntry entry = sourceEntries[i]; IResource sourceFolder = root.findMember(entry.getPath()); if (sourceFolder != null) { // collect output locations if source is project (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32041) final HashSet outputs = new HashSet(); if (sourceFolder.getType() == IResource.PROJECT) { // Do not create marker while getting output location (see bug 41859) outputs.add(javaProject.getOutputLocation()); for (int j = 0; j < sourceEntriesNumber; j++) { IPath output = sourceEntries[j].getOutputLocation(); if (output != null) { outputs.add(output); } } } final boolean hasOutputs = !outputs.isEmpty(); final char[][] inclusionPatterns = ((ClasspathEntry) entry).fullInclusionPatternChars(); final char[][] exclusionPatterns = ((ClasspathEntry) entry).fullExclusionPatternChars(); if (max == 0) { sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; indexedFileNames.put(Util.relativePath(file.getFullPath(), 1/*remove project segment*/), file); } return false; case IResource.FOLDER : if (exclusionPatterns != null && inclusionPatterns == null) { // if there are inclusion patterns then we must walk the children if (Util.isExcluded(proxy.requestFullPath(), inclusionPatterns, exclusionPatterns, true)) return false; } if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; } }, IResource.NONE ); } else { sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location == null) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; String relativePathString = Util.relativePath(file.getFullPath(), 1/*remove project segment*/); indexedFileNames.put(relativePathString, indexedFileNames.get(relativePathString) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } return false; case IResource.FOLDER : if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns)) return false; if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; } }, IResource.NONE ); } } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (IndexAllProject.this.isCancelled) return false; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IFile file = (IFile) proxy.requestResource(); URI location = file.getLocationURI(); if (location == null) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(file, inclusionPatterns, exclusionPatterns)) return false; String relativePathString = Util.relativePath(file.getFullPath(), 1/*remove project segment*/); indexedFileNames.put(relativePathString, indexedFileNames.get(relativePathString) == null || indexLastModified < EFS.getStore(location).fetchInfo().getLastModified() ? (Object) file : (Object) OK); } return false; case IResource.FOLDER : if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(proxy.requestResource(), inclusionPatterns, exclusionPatterns)) return false; if (hasOutputs && outputs.contains(proxy.requestFullPath())) return false; } return true; }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void acceptSearchMatch(SearchMatch match) throws CoreException { this.resultCollector.accept( match.getResource(), match.getOffset(), match.getOffset() + match.getLength(), (IJavaElement) match.getElement(), match.getAccuracy() ); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { this.basicEngine.search(pattern, participants, scope, requestor, monitor); }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// 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
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; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
protected void touchProjects(final IProject[] projectsToTouch, IProgressMonitor progressMonitor) throws CoreException { for (int i = 0; i < projectsToTouch.length; i++) { IProgressMonitor monitor = progressMonitor == null ? null: new SubProgressMonitor(progressMonitor, 1); 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(monitor); } }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
public void run(IProgressMonitor monitor) throws CoreException { JavaModelManager manager = JavaModelManager.getJavaModelManager(); DeltaProcessor deltaProcessor = manager.getDeltaProcessor(); int previousDeltaCount = deltaProcessor.javaModelDeltas.size(); try { this.progressMonitor = monitor; pushOperation(this); try { if (canModifyRoots()) { // computes the root infos before executing the operation // noop if aready initialized JavaModelManager.getDeltaState().initializeRoots(false/*not initiAfterLoad*/); } executeOperation(); } finally { if (isTopLevelOperation()) { runPostActions(); } } } finally { try { // reacquire delta processor as it can have been reset during executeOperation() deltaProcessor = manager.getDeltaProcessor(); // update JavaModel using deltas that were recorded during this operation for (int i = previousDeltaCount, size = deltaProcessor.javaModelDeltas.size(); i < size; i++) { deltaProcessor.updateJavaModel((IJavaElementDelta)deltaProcessor.javaModelDeltas.get(i)); } // close the parents of the created elements and reset their project's cache (in case we are in an // IWorkspaceRunnable and the clients wants to use the created element's parent) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=83646 for (int i = 0, length = this.resultElements.length; i < length; i++) { IJavaElement element = this.resultElements[i]; Openable openable = (Openable) element.getOpenable(); if (!(openable instanceof CompilationUnit) || !((CompilationUnit) openable).isWorkingCopy()) { // a working copy must remain a child of its parent even after a move ((JavaElement) openable.getParent()).close(); } switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.PACKAGE_FRAGMENT: deltaProcessor.projectCachesToReset.add(element.getJavaProject()); break; } } deltaProcessor.resetProjectCaches(); // fire only iff: // - the operation is a top level operation // - the operation did produce some delta(s) // - but the operation has not modified any resource if (isTopLevelOperation()) { if ((deltaProcessor.javaModelDeltas.size() > previousDeltaCount || !deltaProcessor.reconcileDeltas.isEmpty()) && !hasModifiedResource()) { deltaProcessor.fire(null, DeltaProcessor.DEFAULT_CHANGE_EVENT); } // else deltas are fired while processing the resource delta } } finally { popOperation(); } } }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
public InputStream getContents() throws CoreException { ZipFile zipFile = null; try { zipFile = getZipFile(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } String entryName = getEntryName(); ZipEntry zipEntry = zipFile.getEntry(entryName); if (zipEntry == null){ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entryName)); } byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); return new ByteArrayInputStream(contents); } catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } }
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
public InputStream getContents() throws CoreException { if (this.resource instanceof IFile) return ((IFile) this.resource).getContents(); return null; }
// in model/org/eclipse/jdt/internal/core/JarEntryDirectory.java
public InputStream getContents() throws CoreException { return new ByteArrayInputStream(new byte[0]); }
// 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
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; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void verifyArchiveContent(IPath path) throws CoreException { if (isInvalidArchive(path)) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); } ZipFile file = getZipFile(path); closeZipFile(file); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public ZipFile getZipFile(IPath path) throws CoreException { if (isInvalidArchive(path)) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, new ZipException())); ZipCache zipCache; ZipFile zipFile; if ((zipCache = (ZipCache)this.zipFiles.get()) != null && (zipFile = zipCache.getCache(path)) != null) { return zipFile; } File localFile = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource file = root.findMember(path); if (file != null) { // internal resource URI location; if (file.getType() != IResource.FILE || (location = file.getLocationURI()) == null) { throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } localFile = Util.toLocalFile(location, null/*no progress availaible*/); if (localFile == null) throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.bind(Messages.file_notFound, path.toString()), null)); } else { // external resource -> it is ok to use toFile() localFile= path.toFile(); } try { if (ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JavaModelManager.getZipFile(IPath)] Creating ZipFile on " + localFile ); //$NON-NLS-1$ //$NON-NLS-2$ } zipFile = new ZipFile(localFile); if (zipCache != null) { zipCache.setCache(path, zipFile); } return zipFile; } catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); } }
// 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
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(); } }
// 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 void initialize(IPath path, IJavaProject javaProject) throws CoreException { // not used }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private Set getNonChainingJarsCache() throws CoreException { // Even if there is one entry in the cache, just return it. It may not be // the complete cache, but avoid going through all the projects to populate the cache. if (this.nonChainingJars != null && this.nonChainingJars.size() > 0) { return this.nonChainingJars; } Set result = new HashSet(); IJavaProject[] projects = getJavaModel().getJavaProjects(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; IClasspathEntry[] classpath = ((JavaProject) javaProject).getResolvedClasspath(); for (int j = 0, length2 = classpath.length; j < length2; j++) { IClasspathEntry entry = classpath[j]; IPath path; if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY && !result.contains(path = entry.getPath()) && ClasspathEntry.resolvedChainedLibraries(path).length == 0) { result.add(path); } } } this.nonChainingJars = Collections.synchronizedSet(result); return this.nonChainingJars; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private Set getClasspathListCache(String cacheName) throws CoreException { if (cacheName == NON_CHAINING_JARS_CACHE) return getNonChainingJarsCache(); else if (cacheName == INVALID_ARCHIVES_CACHE) return this.invalidArchives; else return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void loadVariablesAndContainers() throws CoreException { // backward compatibility, consider persistent property QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "variables"); //$NON-NLS-1$ String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName); try { if (xmlString != null){ StringReader reader = new StringReader(xmlString); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch(SAXException e) { return; } catch(ParserConfigurationException e){ return; } finally { reader.close(); } if (cpElement == null) return; if (!cpElement.getNodeName().equalsIgnoreCase("variables")) { //$NON-NLS-1$ return; } NodeList list= cpElement.getChildNodes(); int length= list.getLength(); for (int i= 0; i < length; ++i) { Node node= list.item(i); short type= node.getNodeType(); if (type == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equalsIgnoreCase("variable")) { //$NON-NLS-1$ variablePut( element.getAttribute("name"), //$NON-NLS-1$ new Path(element.getAttribute("path"))); //$NON-NLS-1$ } } } } } catch(IOException e){ // problem loading xml file: nothing we can do } finally { if (xmlString != null){ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(qName, null); // flush old one } } // backward compatibility, load variables and containers from preferences into cache loadVariablesAndContainers(getDefaultPreferences()); loadVariablesAndContainers(getInstancePreferences()); // load variables and containers from saved file into cache File file = getVariableAndContainersFile(); DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); switch (in.readInt()) { case 2 : new VariablesAndContainersLoadHelper(in).load(); break; case 1 : // backward compatibility, load old format // variables int size = in.readInt(); while (size-- > 0) { String varName = in.readUTF(); String pathString = in.readUTF(); if (CP_ENTRY_IGNORE.equals(pathString)) continue; IPath varPath = Path.fromPortableString(pathString); this.variables.put(varName, varPath); this.previousSessionVariables.put(varName, varPath); } // containers IJavaModel model = getJavaModel(); int projectSize = in.readInt(); while (projectSize-- > 0) { String projectName = in.readUTF(); IJavaProject project = model.getJavaProject(projectName); int containerSize = in.readInt(); while (containerSize-- > 0) { IPath containerPath = Path.fromPortableString(in.readUTF()); int length = in.readInt(); byte[] containerString = new byte[length]; in.readFully(containerString); recreatePersistedContainer(project, containerPath, new String(containerString), true/*add to container values*/); } } break; } } catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ } catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ } finally { if (in != null) { try { in.close(); } catch (IOException e) { // nothing we can do: ignore } } } // override persisted values for variables which have a registered initializer String[] registeredVariables = getRegisteredVariableNames(); for (int i = 0; i < registeredVariables.length; i++) { String varName = registeredVariables[i]; this.variables.put(varName, null); // reset variable, but leave its entry in the Map, so it will be part of variable names. } // override persisted values for containers which have a registered initializer containersReset(getRegisteredContainerIDs()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveState(PerProjectInfo info, ISaveContext context) throws CoreException { // passed this point, save actions are non trivial if (context.getKind() == ISaveContext.SNAPSHOT) return; // save built state if (info.triedRead) saveBuiltState(info); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveBuiltState(PerProjectInfo info) throws CoreException { if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_saveStateProgress, info.project.getName())); File file = getSerializationFile(info.project); if (file == null) return; long t = System.currentTimeMillis(); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { out.writeUTF(JavaCore.PLUGIN_ID); out.writeUTF("STATE"); //$NON-NLS-1$ if (info.savedState == null) { out.writeBoolean(false); } else { out.writeBoolean(true); JavaBuilder.writeState(info.savedState, out); } } finally { out.close(); } } catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); } if (JavaBuilder.DEBUG) { t = System.currentTimeMillis() - t; System.out.println(Messages.bind(Messages.build_saveStateComplete, String.valueOf(t))); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathListCache(String cacheName) throws CoreException { File file = getClasspathListFile(cacheName); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Set pathCache = getClasspathListCache(cacheName); synchronized (pathCache) { out.writeInt(pathCache.size()); Iterator entries = pathCache.iterator(); while (entries.hasNext()) { IPath path = (IPath) entries.next(); out.writeUTF(path.toPortableString()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariablesAndContainers(ISaveContext context) throws CoreException { File file = getVariableAndContainersFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeInt(VARIABLES_AND_CONTAINERS_FILE_VERSION); new VariablesAndContainersSaveHelper(out).save(context); } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void saving(ISaveContext context) throws CoreException { long start = -1; if (VERBOSE) start = System.currentTimeMillis(); // save variable and container values on snapshot/full save saveVariablesAndContainers(context); if (VERBOSE) traceVariableAndContainers("Saved", start); //$NON-NLS-1$ switch(context.getKind()) { case ISaveContext.FULL_SAVE : { // save non-chaining jar and invalid jar caches on full save saveClasspathListCache(NON_CHAINING_JARS_CACHE); saveClasspathListCache(INVALID_ARCHIVES_CACHE); // will need delta since this save (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658) context.needDelta(); // clean up indexes on workspace full save // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52347) IndexManager manager = this.indexManager; if (manager != null // don't force initialization of workspace scope as we could be shutting down // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93941) && this.workspaceScope != null) { manager.cleanUpIndexes(); } } //$FALL-THROUGH$ case ISaveContext.SNAPSHOT : { // clean up external folders on full save or snapshot this.externalFoldersManager.cleanUp(null); } } IProject savedProject = context.getProject(); if (savedProject != null) { if (!JavaProject.hasJavaNature(savedProject)) return; // ignore PerProjectInfo info = getPerProjectInfo(savedProject, true /* create info */); saveState(info, context); return; } ArrayList vStats= null; // lazy initialized ArrayList values = null; synchronized(this.perProjectInfos) { values = new ArrayList(this.perProjectInfos.values()); } Iterator iterator = values.iterator(); while (iterator.hasNext()) { try { PerProjectInfo info = (PerProjectInfo) iterator.next(); saveState(info, context); } catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); } } if (vStats != null) { IStatus[] stats= new IStatus[vStats.size()]; vStats.toArray(stats); throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Messages.build_cannotSaveStates, null)); } // save external libs timestamps this.deltaState.saveExternalLibTimeStamps(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void startup() throws CoreException { try { configurePluginDebugOptions(); // initialize Java model cache this.cache = new JavaModelCache(); // request state folder creation (workaround 19885) JavaCore.getPlugin().getStateLocation(); // Initialize eclipse preferences initializePreferences(); // Listen to preference changes this.propertyListener = new IEclipsePreferences.IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { JavaModelManager.this.optionsCache = null; } }; InstanceScope.INSTANCE.getNode(JavaCore.PLUGIN_ID).addPreferenceChangeListener(this.propertyListener); // listen for encoding changes (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=255501 ) this.resourcesPropertyListener = new IEclipsePreferences.IPreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent event) { if (ResourcesPlugin.PREF_ENCODING.equals(event.getKey())) { JavaModelManager.this.optionsCache = null; } } }; String resourcesPluginId = ResourcesPlugin.getPlugin().getBundle().getSymbolicName(); InstanceScope.INSTANCE.getNode(resourcesPluginId).addPreferenceChangeListener(this.resourcesPropertyListener); // Listen to content-type changes Platform.getContentTypeManager().addContentTypeChangeListener(this); // retrieve variable values long start = -1; if (VERBOSE) start = System.currentTimeMillis(); loadVariablesAndContainers(); if (VERBOSE) traceVariableAndContainers("Loaded", start); //$NON-NLS-1$ // listen for resource changes this.deltaState.initializeRootsWithPreviousSession(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.addResourceChangeListener( this.deltaState, /* update spec in JavaCore#addPreProcessingResourceChangedListener(...) if adding more event types */ IResourceChangeEvent.PRE_BUILD | IResourceChangeEvent.POST_BUILD | IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_REFRESH); startIndexing(); // process deltas since last activated in indexer thread so that indexes are up-to-date. // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658 Job processSavedState = new Job(Messages.savedState_jobName) { protected IStatus run(IProgressMonitor monitor) { try { // add save participant and process delta atomically // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 workspace.run( new IWorkspaceRunnable() { public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } } }, monitor); } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; processSavedState.setSystem(true); processSavedState.setPriority(Job.SHORT); // process asap processSavedState.schedule(); } catch (RuntimeException e) { shutdown(); throw e; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected IStatus run(IProgressMonitor monitor) { try { // add save participant and process delta atomically // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937 workspace.run( new IWorkspaceRunnable() { public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } } }, monitor); } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void run(IProgressMonitor progress) throws CoreException { ISavedState savedState = workspace.addSaveParticipant(JavaCore.PLUGIN_ID, JavaModelManager.this); if (savedState != null) { // the event type coming from the saved state is always POST_AUTO_BUILD // force it to be POST_CHANGE so that the delta processor can handle it JavaModelManager.this.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE; savedState.processResourceChangeEvents(JavaModelManager.this.deltaState); } }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void computeClasspathLocations( IWorkspaceRoot root, JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject) throws CoreException { /* Update cycle marker */ IMarker cycleMarker = javaProject.getCycleMarker(); if (cycleMarker != null) { int severity = JavaCore.ERROR.equals(javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true)) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING; if (severity != cycleMarker.getAttribute(IMarker.SEVERITY, severity)) cycleMarker.setAttribute(IMarker.SEVERITY, severity); } IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath(); ArrayList sLocations = new ArrayList(classpathEntries.length); ArrayList bLocations = new ArrayList(classpathEntries.length); nextEntry : for (int i = 0, l = classpathEntries.length; i < l; i++) { ClasspathEntry entry = (ClasspathEntry) classpathEntries[i]; IPath path = entry.getPath(); Object target = JavaModel.getTarget(path, true); if (target == null) continue nextEntry; switch(entry.getEntryKind()) { case IClasspathEntry.CPE_SOURCE : if (!(target instanceof IContainer)) continue nextEntry; IPath outputPath = entry.getOutputLocation() != null ? entry.getOutputLocation() : javaProject.getOutputLocation(); IContainer outputFolder; if (outputPath.segmentCount() == 1) { outputFolder = javaProject.getProject(); } else { outputFolder = root.getFolder(outputPath); if (!outputFolder.exists()) createOutputFolder(outputFolder); } sLocations.add( ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullInclusionPatternChars(), entry.fullExclusionPatternChars())); continue nextEntry; case IClasspathEntry.CPE_PROJECT : if (!(target instanceof IProject)) continue nextEntry; IProject prereqProject = (IProject) target; if (!JavaProject.hasJavaNature(prereqProject)) continue nextEntry; // if project doesn't have java nature or is not accessible JavaProject prereqJavaProject = (JavaProject) JavaCore.create(prereqProject); IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath(); ArrayList seen = new ArrayList(); nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) { IClasspathEntry prereqEntry = prereqClasspathEntries[j]; if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { Object prereqTarget = JavaModel.getTarget(prereqEntry.getPath(), true); if (!(prereqTarget instanceof IContainer)) continue nextPrereqEntry; IPath prereqOutputPath = prereqEntry.getOutputLocation() != null ? prereqEntry.getOutputLocation() : prereqJavaProject.getOutputLocation(); IContainer binaryFolder = prereqOutputPath.segmentCount() == 1 ? (IContainer) prereqProject : (IContainer) root.getFolder(prereqOutputPath); if (binaryFolder.exists() && !seen.contains(binaryFolder)) { seen.add(binaryFolder); ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true, entry.getAccessRuleSet()); bLocations.add(bLocation); if (binaryLocationsPerProject != null) { // normal builder mode ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(prereqProject); if (existingLocations == null) { existingLocations = new ClasspathLocation[] {bLocation}; } else { int size = existingLocations.length; System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); existingLocations[size] = bLocation; } binaryLocationsPerProject.put(prereqProject, existingLocations); } } } } continue nextEntry; case IClasspathEntry.CPE_LIBRARY : if (target instanceof IResource) { IResource resource = (IResource) target; ClasspathLocation bLocation = null; if (resource instanceof IFile) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocation = ClasspathLocation.forLibrary((IFile) resource, accessRuleSet); } else if (resource instanceof IContainer) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false, accessRuleSet); // is library folder not output folder } bLocations.add(bLocation); if (binaryLocationsPerProject != null) { // normal builder mode IProject p = resource.getProject(); // can be the project being built ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(p); if (existingLocations == null) { existingLocations = new ClasspathLocation[] {bLocation}; } else { int size = existingLocations.length; System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size); existingLocations[size] = bLocation; } binaryLocationsPerProject.put(p, existingLocations); } } else if (target instanceof File) { AccessRuleSet accessRuleSet = (JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true)) && JavaCore.IGNORE.equals(javaProject.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true))) ? null : entry.getAccessRuleSet(); bLocations.add(ClasspathLocation.forLibrary(path.toString(), accessRuleSet)); } continue nextEntry; } } // now split the classpath locations... place the output folders ahead of the other .class file folders & jars ArrayList outputFolders = new ArrayList(1); this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()]; if (!sLocations.isEmpty()) { sLocations.toArray(this.sourceLocations); // collect the output folders, skipping duplicates next : for (int i = 0, l = this.sourceLocations.length; i < l; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; IPath outputPath = md.binaryFolder.getFullPath(); for (int j = 0; j < i; j++) { // compare against previously walked source folders if (outputPath.equals(this.sourceLocations[j].binaryFolder.getFullPath())) { md.hasIndependentOutputFolder = this.sourceLocations[j].hasIndependentOutputFolder; continue next; } } outputFolders.add(md); // also tag each source folder whose output folder is an independent folder & is not also a source folder for (int j = 0, m = this.sourceLocations.length; j < m; j++) if (outputPath.equals(this.sourceLocations[j].sourceFolder.getFullPath())) continue next; md.hasIndependentOutputFolder = true; } } // combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()]; int index = 0; for (int i = 0, l = outputFolders.size(); i < l; i++) this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i); for (int i = 0, l = bLocations.size(); i < l; i++) this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void createOutputFolder(IContainer outputFolder) throws CoreException { createParentFolder(outputFolder.getParent()); ((IFolder) outputFolder).create(IResource.FORCE | IResource.DERIVED, true, null); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
private void createParentFolder(IContainer parent) throws CoreException { if (!parent.exists()) { createParentFolder(parent.getParent()); ((IFolder) parent).create(true, true, null); } }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException { this.currentProject = getProject(); if (this.currentProject == null || !this.currentProject.isAccessible()) return new IProject[0]; if (DEBUG) System.out.println("\nStarting build of " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ this.notifier = new BuildNotifier(monitor, this.currentProject); this.notifier.begin(); boolean ok = false; try { this.notifier.checkCancel(); kind = initializeBuilder(kind, true); if (isWorthBuilding()) { if (kind == FULL_BUILD) { if (DEBUG) System.out.println("Performing full build as requested by user"); //$NON-NLS-1$ buildAll(); } else { if ((this.lastState = getLastState(this.currentProject)) == null) { if (DEBUG) System.out.println("Performing full build since last saved state was not found"); //$NON-NLS-1$ buildAll(); } else if (hasClasspathChanged()) { // if the output location changes, do not delete the binary files from old location // the user may be trying something if (DEBUG) System.out.println("Performing full build since classpath has changed"); //$NON-NLS-1$ buildAll(); } else if (this.nameEnvironment.sourceLocations.length > 0) { // if there is no source to compile & no classpath changes then we are done SimpleLookupTable deltas = findDeltas(); if (deltas == null) { if (DEBUG) System.out.println("Performing full build since deltas are missing after incremental request"); //$NON-NLS-1$ buildAll(); } else if (deltas.elementSize > 0) { buildDeltas(deltas); } else if (DEBUG) { System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$ } } else { if (hasStructuralDelta()) { // double check that a jar file didn't get replaced in a binary project if (DEBUG) System.out.println("Performing full build since there are structural deltas"); //$NON-NLS-1$ buildAll(); } else { if (DEBUG) System.out.println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$ this.lastState.tagAsNoopBuild(); } } } ok = true; } } catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); } catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); } catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); } finally { for (int i = 0, l = this.participants == null ? 0 : this.participants.length; i < l; i++) this.participants[i].buildFinished(this.javaProject); if (!ok) // If the build failed, clear the previously built state, forcing a full build next time. clearLastState(); this.notifier.done(); cleanup(); } IProject[] requiredProjects = getRequiredProjects(true); if (DEBUG) System.out.println("Finished build of " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ return requiredProjects; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
protected void clean(IProgressMonitor monitor) throws CoreException { this.currentProject = getProject(); if (this.currentProject == null || !this.currentProject.isAccessible()) return; if (DEBUG) System.out.println("\nCleaning " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ this.notifier = new BuildNotifier(monitor, this.currentProject); this.notifier.begin(); try { this.notifier.checkCancel(); initializeBuilder(CLEAN_BUILD, true); if (DEBUG) System.out.println("Clearing last state as part of clean : " + this.lastState); //$NON-NLS-1$ clearLastState(); removeProblemsAndTasksFor(this.currentProject); new BatchImageBuilder(this, false).cleanOutputFolders(false); } catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); } finally { this.notifier.done(); cleanup(); } if (DEBUG) System.out.println("Finished cleaning " + this.currentProject.getName() //$NON-NLS-1$ + " @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private void createInconsistentBuildMarker(CoreException coreException) throws CoreException { String message = null; IStatus status = coreException.getStatus(); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); if (children != null && children.length > 0) message = children[0].getMessage(); } if (message == null) message = coreException.getMessage(); IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_inconsistentProject, message), new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
boolean hasBuildpathErrors() throws CoreException { IMarker[] markers = this.currentProject.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); for (int i = 0, l = markers.length; i < l; i++) if (markers[i].getAttribute(IJavaModelMarker.CATEGORY_ID, -1) == CategorizedProblem.CAT_BUILDPATH) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean hasJavaBuilder(IProject project) throws CoreException { ICommand[] buildCommands = project.getDescription().getBuildSpec(); for (int i = 0, l = buildCommands.length; i < l; i++) if (buildCommands[i].getBuilderName().equals(JavaCore.BUILDER_ID)) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private int initializeBuilder(int kind, boolean forBuild) throws CoreException { // some calls just need the nameEnvironment initialized so skip the rest this.javaProject = (JavaProject) JavaCore.create(this.currentProject); this.workspaceRoot = this.currentProject.getWorkspace().getRoot(); if (forBuild) { // cache the known participants for this project this.participants = JavaModelManager.getJavaModelManager().compilationParticipants.getCompilationParticipants(this.javaProject); if (this.participants != null) for (int i = 0, l = this.participants.length; i < l; i++) if (this.participants[i].aboutToBuild(this.javaProject) == CompilationParticipant.NEEDS_FULL_BUILD) kind = FULL_BUILD; // Flush the existing external files cache if this is the beginning of a build cycle String projectName = this.currentProject.getName(); if (builtProjects == null || builtProjects.contains(projectName)) { JavaModel.flushExternalFileCache(); builtProjects = new ArrayList(); } builtProjects.add(projectName); } this.binaryLocationsPerProject = new SimpleLookupTable(3); this.nameEnvironment = new NameEnvironment(this.workspaceRoot, this.javaProject, this.binaryLocationsPerProject, this.notifier); if (forBuild) { String filterSequence = this.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true); char[][] filters = filterSequence != null && filterSequence.length() > 0 ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { this.extraResourceFileFilters = null; this.extraResourceFolderFilters = null; } else { int fileCount = 0, folderCount = 0; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') folderCount++; else fileCount++; } this.extraResourceFileFilters = new char[fileCount][]; this.extraResourceFolderFilters = new String[folderCount]; for (int i = 0, l = filters.length; i < l; i++) { char[] f = filters[i]; if (f.length == 0) continue; if (f[f.length - 1] == '/') this.extraResourceFolderFilters[--folderCount] = new String(f, 0, f.length - 1); else this.extraResourceFileFilters[--fileCount] = f; } } } return kind; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p) throws CoreException { IMarker[] markers = p.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); for (int i = 0, l = markers.length; i < l; i++) if (markers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR) return true; return false; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
private boolean isWorthBuilding() throws CoreException { boolean abortBuilds = JavaCore.ABORT.equals(this.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true)); if (!abortBuilds) return true; // Abort build only if there are classpath errors if (isClasspathBroken(this.javaProject.getRawClasspath(), this.currentProject)) { if (DEBUG) System.out.println("Aborted build because project has classpath errors (incomplete or involved in cycle)"); //$NON-NLS-1$ removeProblemsAndTasksFor(this.currentProject); // remove all compilation problems IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.build_abortDueToClasspathProblems, new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); return false; } if (JavaCore.WARNING.equals(this.javaProject.getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true))) return true; // make sure all prereq projects have valid build states... only when aborting builds since projects in cycles do not have build states // except for projects involved in a 'warning' cycle (see below) IProject[] requiredProjects = getRequiredProjects(false); for (int i = 0, l = requiredProjects.length; i < l; i++) { IProject p = requiredProjects[i]; if (getLastState(p) == null) { // The prereq project has no build state: if this prereq project has a 'warning' cycle marker then allow build (see bug id 23357) JavaProject prereq = (JavaProject) JavaCore.create(p); if (prereq.hasCycleMarker() && JavaCore.WARNING.equals(this.javaProject.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true))) { if (DEBUG) System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$ + " was not built since its part of a cycle"); //$NON-NLS-1$ continue; } if (!hasJavaBuilder(p)) { if (DEBUG) System.out.println("Continued to build even though prereq project " + p.getName() //$NON-NLS-1$ + " is not built by JavaBuilder"); //$NON-NLS-1$ continue; } if (DEBUG) System.out.println("Aborted build because prereq project " + p.getName() //$NON-NLS-1$ + " was not built"); //$NON-NLS-1$ removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { isClasspathBroken(prereq.getRawClasspath(), p) ? Messages.bind(Messages.build_prereqProjectHasClasspathProblems, p.getName()) : Messages.bind(Messages.build_prereqProjectMustBeRebuilt, p.getName()), new Integer(IMarker.SEVERITY_ERROR), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); return false; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean checkForClassFileChanges(IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { IResource resource = binaryDelta.getResource(); // remember that if inclusion & exclusion patterns change then a full build is done boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null) && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns); switch(resource.getType()) { case IResource.FOLDER : if (isExcluded && md.inclusionPatterns == null) return true; // no need to go further with this delta since its children cannot be included IResourceDelta[] children = binaryDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!checkForClassFileChanges(children[i], md, segmentCount)) return false; return true; case IResource.FILE : if (!isExcluded && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) { // perform full build if a managed class file has been changed IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); if (this.newState.isKnownType(typePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$ return false; } return true; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean findSourceFiles(IResourceDelta delta) throws CoreException { ArrayList visited = this.makeOutputFolderConsistent ? new ArrayList(this.sourceLocations.length) : null; for (int i = 0, l = this.sourceLocations.length; i < l; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; if (this.makeOutputFolderConsistent && md.hasIndependentOutputFolder && !visited.contains(md.binaryFolder)) { // even a project which acts as its own source folder can have an independent/nested output folder visited.add(md.binaryFolder); IResourceDelta binaryDelta = delta.findMember(md.binaryFolder.getProjectRelativePath()); if (binaryDelta != null) { int segmentCount = binaryDelta.getFullPath().segmentCount(); IResourceDelta[] children = binaryDelta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!checkForClassFileChanges(children[j], md, segmentCount)) return false; } } if (md.sourceFolder.equals(this.javaBuilder.currentProject)) { // skip nested source & output folders when the project is a source folder int segmentCount = delta.getFullPath().segmentCount(); IResourceDelta[] children = delta.getAffectedChildren(); for (int j = 0, m = children.length; j < m; j++) if (!isExcludedFromProject(children[j].getFullPath())) if (!findSourceFiles(children[j], md, segmentCount)) return false; } else { IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath()); if (sourceDelta != null) { if (sourceDelta.getKind() == IResourceDelta.REMOVED) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$ return false; // removed source folder should not make it here, but handle anyways (ADDED is supported) } int segmentCount = sourceDelta.getFullPath().segmentCount(); IResourceDelta[] children = sourceDelta.getAffectedChildren(); try { for (int j = 0, m = children.length; j < m; j++) if (!findSourceFiles(children[j], md, segmentCount)) return false; } catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow } } } this.notifier.checkCancel(); } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean findSourceFiles(IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { // When a package becomes a type or vice versa, expect 2 deltas, // one on the folder & one on the source file IResource resource = sourceDelta.getResource(); // remember that if inclusion & exclusion patterns change then a full build is done boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null) && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns); switch(resource.getType()) { case IResource.FOLDER : if (isExcluded && md.inclusionPatterns == null) return true; // no need to go further with this delta since its children cannot be included switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (!isExcluded) { IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); createFolder(addedPackagePath, md.binaryFolder); // ensure package exists in the output folder // see if any known source file is from the same package... classpath already includes new package if (this.sourceLocations.length > 1 && this.newState.isKnownPackage(addedPackagePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("Skipped dependents of added package " + addedPackagePath); //$NON-NLS-1$ } else { if (JavaBuilder.DEBUG) System.out.println("Found added package " + addedPackagePath); //$NON-NLS-1$ addDependentsOf(addedPackagePath, true); } } //$FALL-THROUGH$ collect all the source files case IResourceDelta.CHANGED : IResourceDelta[] children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; case IResourceDelta.REMOVED : if (isExcluded) { // since this folder is excluded then there is nothing to delete (from this md), but must walk any included subfolders children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; } IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); if (this.sourceLocations.length > 1) { for (int i = 0, l = this.sourceLocations.length; i < l; i++) { if (this.sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) { // only a package fragment was removed, same as removing multiple source files createFolder(removedPackagePath, md.binaryFolder); // ensure package exists in the output folder IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren(); for (int j = 0, m = removedChildren.length; j < m; j++) if (!findSourceFiles(removedChildren[j], md, segmentCount)) return false; return true; } } } if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // same idea as moving a source file // see bug 163200 IResource movedFolder = this.javaBuilder.workspaceRoot.getFolder(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFolder); } IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath); if (removedPackageFolder.exists()) removedPackageFolder.delete(IResource.FORCE, null); // add dependents even when the package thinks it does not exist to be on the safe side if (JavaBuilder.DEBUG) System.out.println("Found removed package " + removedPackagePath); //$NON-NLS-1$ addDependentsOf(removedPackagePath, true); this.newState.removePackage(sourceDelta); } return true; case IResource.FILE : if (isExcluded) return true; String resourceName = resource.getName(); if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) { IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); String typeLocator = resource.getProjectRelativePath().toString(); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (JavaBuilder.DEBUG) System.out.println("Compile this added source file " + typeLocator); //$NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); String typeName = typePath.toString(); if (!this.newState.isDuplicateLocator(typeName, typeLocator)) { // adding dependents results in 2 duplicate errors if (JavaBuilder.DEBUG) System.out.println("Found added source file " + typeName); //$NON-NLS-1$ addDependentsOf(typePath, true); } return true; case IResourceDelta.REMOVED : char[][] definedTypeNames = this.newState.getDefinedTypeNamesFor(typeLocator); if (definedTypeNames == null) { // defined a single type matching typePath removeClassFile(typePath, md.binaryFolder); if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // remove problems and tasks for a compilation unit that is being moved (to another package or renamed) // if the target file is a compilation unit, the new cu will be recompiled // if the target file is a non-java resource, then markers are removed // see bug 2857 IResource movedFile = this.javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFile); } } else { if (JavaBuilder.DEBUG) System.out.println("Found removed source file " + typePath.toString()); //$NON-NLS-1$ addDependentsOf(typePath, true); // add dependents of the source file since it may be involved in a name collision if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type IPath packagePath = typePath.removeLastSegments(1); for (int i = 0, l = definedTypeNames.length; i < l; i++) removeClassFile(packagePath.append(new String(definedTypeNames[i])), md.binaryFolder); } } this.newState.removeLocator(typeLocator); return true; case IResourceDelta.CHANGED : if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (JavaBuilder.DEBUG) System.out.println("Compile this changed source file " + typeLocator); //$NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); } return true; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) { // perform full build if a managed class file has been changed if (this.makeOutputFolderConsistent) { IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); if (this.newState.isKnownType(typePath.toString())) { if (JavaBuilder.DEBUG) System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$ return false; } } return true; } else if (md.hasIndependentOutputFolder) { if (this.javaBuilder.filterExtraResource(resource)) return true; // copy all other resource deltas to the output folder IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount); IResource outputFile = md.binaryFolder.getFile(resourcePath); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED : if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying added file " + resourcePath); //$NON-NLS-1$ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); return true; case IResourceDelta.REMOVED : if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting removed file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } return true; case IResourceDelta.CHANGED : if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying changed file " + resourcePath); //$NON-NLS-1$ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); } return true; } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void removeClassFile(IPath typePath, IContainer outputFolder) throws CoreException { if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type this.newState.removeQualifiedTypeName(typePath.toString()); // add dependents even when the type thinks it does not exist to be on the safe side if (JavaBuilder.DEBUG) System.out.println("Found removed type " + typePath); //$NON-NLS-1$ addDependentsOf(typePath, true); // when member types are removed, their enclosing type is structurally changed } IFile classFile = outputFolder.getFile(typePath.addFileExtension(SuffixConstants.EXTENSION_class)); if (classFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting class file of removed type " + typePath); //$NON-NLS-1$ classFile.delete(IResource.FORCE, null); } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void removeSecondaryTypes() throws CoreException { if (this.secondaryTypesToRemove != null) { // delayed deleting secondary types until the end of the compile loop Object[] keyTable = this.secondaryTypesToRemove.keyTable; Object[] valueTable = this.secondaryTypesToRemove.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { IContainer outputFolder = (IContainer) keyTable[i]; if (outputFolder != null) { ArrayList paths = (ArrayList) valueTable[i]; for (int j = 0, m = paths.size(); j < m; j++) removeClassFile((IPath) paths.get(j), outputFolder); } } this.secondaryTypesToRemove = null; if (this.previousSourceFiles != null) this.previousSourceFiles = null; // cannot optimize recompile case when a secondary type is deleted, see 181269 } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { IMarker[] markers = JavaBuilder.getProblemsFor(sourceFile.resource); CategorizedProblem[] problems = result.getProblems(); if (problems == null && markers.length == 0) return; this.notifier.updateProblemCounts(markers, problems); JavaBuilder.removeProblemsFor(sourceFile.resource); storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { IMarker[] markers = JavaBuilder.getTasksFor(sourceFile.resource); CategorizedProblem[] tasks = result.getTasks(); if (tasks == null && markers.length == 0) return; JavaBuilder.removeTasksFor(sourceFile.resource); storeTasksFor(sourceFile, tasks); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected void writeClassFileContents(ClassFile classfile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // Before writing out the class file, compare it to the previous file // If structural changes occurred then add dependent source files byte[] bytes = classfile.getBytes(); if (file.exists()) { if (writeClassFileCheck(file, qualifiedFileName, bytes) || compilationUnit.updateClassFile) { // see 46093 if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(new ByteArrayInputStream(bytes), true, false, null); } else if (JavaBuilder.DEBUG) { System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$ } } else { if (isTopLevelType) addDependentsOf(new Path(qualifiedFileName), true); // new type if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow } } }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException { try { byte[] oldBytes = Util.getResourceContentsAsByteArray(file); notEqual : if (newBytes.length == oldBytes.length) { for (int i = newBytes.length; --i >= 0;) if (newBytes[i] != oldBytes[i]) break notEqual; return false; // bytes are identical so skip them } URI location = file.getLocationURI(); if (location == null) return false; // unable to determine location of this class file String filePath = location.getSchemeSpecificPart(); ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray()); // ignore local types since they're only visible inside a single method if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) { if (JavaBuilder.DEBUG) System.out.println("Type has structural changes " + fileName); //$NON-NLS-1$ addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } } catch (ClassFormatException e) { addDependentsOf(new Path(fileName), true); this.newState.wasStructurallyChanged(fileName); } return true; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void addAllSourceFiles(final ArrayList sourceFiles) throws CoreException { for (int i = 0, l = this.sourceLocations.length; i < l; i++) { final ClasspathMultiDirectory sourceLocation = this.sourceLocations[i]; final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; final char[][] inclusionPatterns = sourceLocation.inclusionPatterns; final boolean isAlsoProject = sourceLocation.sourceFolder.equals(this.javaBuilder.currentProject); final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); final IContainer outputFolder = sourceLocation.binaryFolder; final boolean isOutputFolder = sourceLocation.sourceFolder.equals(outputFolder); sourceLocation.sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; sourceFiles.add(new SourceFile((IFile) resource, sourceLocation)); } return false; case IResource.FOLDER : IPath folderPath = null; if (isAlsoProject) if (isExcludedFromProject(folderPath = proxy.requestFullPath())) return false; if (exclusionPatterns != null) { if (folderPath == null) folderPath = proxy.requestFullPath(); if (Util.isExcluded(folderPath, inclusionPatterns, exclusionPatterns, true)) { // must walk children if inclusionPatterns != null, can skip them if == null // but folder is excluded so do not create it in the output folder return inclusionPatterns != null; } } if (!isOutputFolder) { if (folderPath == null) folderPath = proxy.requestFullPath(); String packageName = folderPath.lastSegment(); if (packageName.length() > 0) { String sourceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaConventions.validatePackageName(packageName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR) createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); } } } return true; } }, IResource.NONE ); this.notifier.checkCancel(); } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; sourceFiles.add(new SourceFile((IFile) resource, sourceLocation)); } return false; case IResource.FOLDER : IPath folderPath = null; if (isAlsoProject) if (isExcludedFromProject(folderPath = proxy.requestFullPath())) return false; if (exclusionPatterns != null) { if (folderPath == null) folderPath = proxy.requestFullPath(); if (Util.isExcluded(folderPath, inclusionPatterns, exclusionPatterns, true)) { // must walk children if inclusionPatterns != null, can skip them if == null // but folder is excluded so do not create it in the output folder return inclusionPatterns != null; } } if (!isOutputFolder) { if (folderPath == null) folderPath = proxy.requestFullPath(); String packageName = folderPath.lastSegment(); if (packageName.length() > 0) { String sourceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = AbstractImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaConventions.validatePackageName(packageName, sourceLevel, complianceLevel).getSeverity() != IStatus.ERROR) createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder); } } } return true; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void copyResource(IResource source, IResource destination) throws CoreException { IPath destPath = destination.getFullPath(); try { source.copy(destPath, IResource.FORCE | IResource.DERIVED, null); } catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; } Util.setReadOnly(destination, false); // just in case the original was read only }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected IContainer createFolder(IPath packagePath, IContainer outputFolder) throws CoreException { if (packagePath.isEmpty()) return outputFolder; IFolder folder = outputFolder.getFolder(packagePath); if (!folder.exists()) { createFolder(packagePath.removeLastSegments(1), outputFolder); folder.create(IResource.FORCE | IResource.DERIVED, true, null); } return folder; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException { if (sourceFile == null || problems == null || problems.length == 0) return; // once a classpath error is found, ignore all other problems for this project so the user can see the main error // but still try to compile as many source files as possible to help the case when the base libraries are in source if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file IResource resource = sourceFile.resource; HashSet managedMarkerTypes = JavaModelManager.getJavaModelManager().compilationParticipants.managedMarkerTypes(); for (int i = 0, l = problems.length; i < l; i++) { CategorizedProblem problem = problems[i]; int id = problem.getID(); // handle missing classfile situation if (id == IProblem.IsClassPathCorrect) { String missingClassfileName = problem.getArguments()[0]; if (JavaBuilder.DEBUG) System.out.println(Messages.bind(Messages.build_incompleteClassPath, missingClassfileName)); boolean isInvalidClasspathError = JavaCore.ERROR.equals(this.javaBuilder.javaProject.getOption(JavaCore.CORE_INCOMPLETE_CLASSPATH, true)); // insert extra classpath problem, and make it the only problem for this project (optional) if (isInvalidClasspathError && JavaCore.ABORT.equals(this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true))) { JavaBuilder.removeProblemsAndTasksFor(this.javaBuilder.currentProject); // make this the only problem for this project this.keepStoringProblemMarkers = false; } IMarker marker = this.javaBuilder.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IJavaModelMarker.CATEGORY_ID, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_incompleteClassPath, missingClassfileName), new Integer(isInvalidClasspathError ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING), new Integer(CategorizedProblem.CAT_BUILDPATH), JavaBuilder.SOURCE_ID } ); // even if we're not keeping more markers, still fall through rest of the problem reporting, so that offending // IsClassPathCorrect problem gets recorded since it may help locate the offending reference } String markerType = problem.getMarkerType(); boolean managedProblem = false; if (IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER.equals(markerType) || (managedProblem = managedMarkerTypes.contains(markerType))) { IMarker marker = resource.createMarker(markerType); String[] attributeNames = JAVA_PROBLEM_MARKER_ATTRIBUTE_NAMES; int standardLength = attributeNames.length; String[] allNames = attributeNames; int managedLength = managedProblem ? 0 : 1; String[] extraAttributeNames = problem.getExtraMarkerAttributeNames(); int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length; if (managedLength > 0 || extraLength > 0) { allNames = new String[standardLength + managedLength + extraLength]; System.arraycopy(attributeNames, 0, allNames, 0, standardLength); if (managedLength > 0) allNames[standardLength] = IMarker.SOURCE_ID; System.arraycopy(extraAttributeNames, 0, allNames, standardLength + managedLength, extraLength); } Object[] allValues = new Object[allNames.length]; // standard attributes int index = 0; allValues[index++] = problem.getMessage(); // message allValues[index++] = problem.isError() ? S_ERROR : S_WARNING; // severity allValues[index++] = new Integer(id); // ID allValues[index++] = new Integer(problem.getSourceStart()); // start int end = problem.getSourceEnd(); allValues[index++] = new Integer(end > 0 ? end + 1 : end); // end allValues[index++] = new Integer(problem.getSourceLineNumber()); // line allValues[index++] = Util.getProblemArgumentsForMarker(problem.getArguments()); // arguments allValues[index++] = new Integer(problem.getCategoryID()); // category ID // SOURCE_ID attribute for JDT problems if (managedLength > 0) allValues[index++] = JavaBuilder.SOURCE_ID; // optional extra attributes if (extraLength > 0) System.arraycopy(problem.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength); marker.setAttributes(allNames, allValues); if (!this.keepStoringProblemMarkers) return; // only want the one error recorded on this source file } } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void storeTasksFor(SourceFile sourceFile, CategorizedProblem[] tasks) throws CoreException { if (sourceFile == null || tasks == null || tasks.length == 0) return; IResource resource = sourceFile.resource; for (int i = 0, l = tasks.length; i < l; i++) { CategorizedProblem task = tasks[i]; if (task.getID() == IProblem.Task) { IMarker marker = resource.createMarker(IJavaModelMarker.TASK_MARKER); Integer priority = P_NORMAL; String compilerPriority = task.getArguments()[2]; if (JavaCore.COMPILER_TASK_PRIORITY_HIGH.equals(compilerPriority)) priority = P_HIGH; else if (JavaCore.COMPILER_TASK_PRIORITY_LOW.equals(compilerPriority)) priority = P_LOW; String[] attributeNames = JAVA_TASK_MARKER_ATTRIBUTE_NAMES; int standardLength = attributeNames.length; String[] allNames = attributeNames; String[] extraAttributeNames = task.getExtraMarkerAttributeNames(); int extraLength = extraAttributeNames == null ? 0 : extraAttributeNames.length; if (extraLength > 0) { allNames = new String[standardLength + extraLength]; System.arraycopy(attributeNames, 0, allNames, 0, standardLength); System.arraycopy(extraAttributeNames, 0, allNames, standardLength, extraLength); } Object[] allValues = new Object[allNames.length]; // standard attributes int index = 0; allValues[index++] = task.getMessage(); allValues[index++] = priority; allValues[index++] = new Integer(task.getID()); allValues[index++] = new Integer(task.getSourceStart()); allValues[index++] = new Integer(task.getSourceEnd() + 1); allValues[index++] = new Integer(task.getSourceLineNumber()); allValues[index++] = Boolean.FALSE; allValues[index++] = JavaBuilder.SOURCE_ID; // optional extra attributes if (extraLength > 0) System.arraycopy(task.getExtraMarkerAttributeValues(), 0, allValues, index, extraLength); marker.setAttributes(allNames, allValues); } } }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException { CategorizedProblem[] problems = result.getProblems(); if (problems == null || problems.length == 0) return; this.notifier.updateProblemCounts(problems); storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException { CategorizedProblem[] tasks = result.getTasks(); if (tasks == null || tasks.length == 0) return; storeTasksFor(sourceFile, tasks); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected char[] writeClassFile(ClassFile classFile, SourceFile compilationUnit, boolean isTopLevelType) throws CoreException { String fileName = new String(classFile.fileName()); // the qualified type name "p1/p2/A" IPath filePath = new Path(fileName); IContainer outputFolder = compilationUnit.sourceLocation.binaryFolder; IContainer container = outputFolder; if (filePath.segmentCount() > 1) { container = createFolder(filePath.removeLastSegments(1), outputFolder); filePath = new Path(filePath.lastSegment()); } IFile file = container.getFile(filePath.addFileExtension(SuffixConstants.EXTENSION_class)); writeClassFileContents(classFile, file, fileName, isTopLevelType, compilationUnit); // answer the name of the class file as in Y or Y$M return filePath.lastSegment().toCharArray(); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
protected void writeClassFileContents(ClassFile classFile, IFile file, String qualifiedFileName, boolean isTopLevelType, SourceFile compilationUnit) throws CoreException { // InputStream input = new SequenceInputStream( // new ByteArrayInputStream(classFile.header, 0, classFile.headerOffset), // new ByteArrayInputStream(classFile.contents, 0, classFile.contentsOffset)); InputStream input = new ByteArrayInputStream(classFile.getBytes()); if (file.exists()) { // Deal with shared output folders... last one wins... no collision cases detected if (JavaBuilder.DEBUG) System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$ if (!file.isDerived()) file.setDerived(true, null); file.setContents(input, true, false, null); } else { // Default implementation just writes out the bytes for the new class file... if (JavaBuilder.DEBUG) System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$ file.create(input, IResource.FORCE | IResource.DERIVED, null); } }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void cleanOutputFolders(boolean copyBack) throws CoreException { boolean deleteAll = JavaCore.CLEAN.equals( this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, true)); if (deleteAll) { if (this.javaBuilder.participants != null) for (int i = 0, l = this.javaBuilder.participants.length; i < l; i++) this.javaBuilder.participants[i].cleanStarting(this.javaBuilder.javaProject); ArrayList visited = new ArrayList(this.sourceLocations.length); for (int i = 0, l = this.sourceLocations.length; i < l; i++) { this.notifier.subTask(Messages.bind(Messages.build_cleaningOutput, this.javaBuilder.currentProject.getName())); ClasspathMultiDirectory sourceLocation = this.sourceLocations[i]; if (sourceLocation.hasIndependentOutputFolder) { IContainer outputFolder = sourceLocation.binaryFolder; if (!visited.contains(outputFolder)) { visited.add(outputFolder); IResource[] members = outputFolder.members(); for (int j = 0, m = members.length; j < m; j++) { IResource member = members[j]; if (!member.isDerived()) { member.accept( new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { resource.setDerived(true, null); return resource.getType() != IResource.FILE; } } ); } member.delete(IResource.FORCE, null); } } this.notifier.checkCancel(); if (copyBack) copyExtraResourcesBack(sourceLocation, true); } else { boolean isOutputFolder = sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder); final char[][] exclusionPatterns = isOutputFolder ? sourceLocation.exclusionPatterns : null; // ignore exclusionPatterns if output folder == another source folder... not this one final char[][] inclusionPatterns = isOutputFolder ? sourceLocation.inclusionPatterns : null; // ignore inclusionPatterns if output folder == another source folder... not this one sourceLocation.binaryFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; if (!resource.isDerived()) resource.setDerived(true, null); resource.delete(IResource.FORCE, null); } return false; } if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(proxy.requestFullPath(), null, exclusionPatterns, true)) return false; BatchImageBuilder.this.notifier.checkCancel(); return true; } }, IResource.NONE ); this.notifier.checkCancel(); } this.notifier.checkCancel(); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResource resource) throws CoreException { resource.setDerived(true, null); return resource.getType() != IResource.FILE; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.FILE) { if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) { IResource resource = proxy.requestResource(); if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; if (!resource.isDerived()) resource.setDerived(true, null); resource.delete(IResource.FORCE, null); } return false; } if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(proxy.requestFullPath(), null, exclusionPatterns, true)) return false; BatchImageBuilder.this.notifier.checkCancel(); return true; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void copyExtraResourcesBack(ClasspathMultiDirectory sourceLocation, final boolean deletedAll) throws CoreException { // When, if ever, does a builder need to copy resources files (not .java or .class) into the output folder? // If we wipe the output folder at the beginning of the build then all 'extra' resources must be copied to the output folder. this.notifier.subTask(Messages.build_copyingResources); final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount(); final char[][] exclusionPatterns = sourceLocation.exclusionPatterns; final char[][] inclusionPatterns = sourceLocation.inclusionPatterns; final IContainer outputFolder = sourceLocation.binaryFolder; final boolean isAlsoProject = sourceLocation.sourceFolder.equals(this.javaBuilder.currentProject); sourceLocation.sourceFolder.accept( new IResourceProxyVisitor() { public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName()) || org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) return false; resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount); IResource copiedResource = outputFolder.getFile(partialPath); if (copiedResource.exists()) { if (deletedAll) { IResource originalResource = findOriginalResource(partialPath); String id = originalResource.getFullPath().removeFirstSegments(1).toString(); createProblemFor( resource, null, Messages.bind(Messages.build_duplicateResource, id), BatchImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true)); return false; } copiedResource.delete(IResource.FORCE, null); // last one wins } createFolder(partialPath.removeLastSegments(1), outputFolder); // ensure package folder exists copyResource(resource, copiedResource); return false; case IResource.FOLDER : resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (isAlsoProject && isExcludedFromProject(resource.getFullPath())) return false; // the sourceFolder == project if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(resource.getFullPath(), null, exclusionPatterns, true)) return false; } return true; } }, IResource.NONE ); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
public boolean visit(IResourceProxy proxy) throws CoreException { IResource resource = null; switch(proxy.getType()) { case IResource.FILE : if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(proxy.getName()) || org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(proxy.getName())) return false; resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (exclusionPatterns != null || inclusionPatterns != null) if (Util.isExcluded(resource.getFullPath(), inclusionPatterns, exclusionPatterns, false)) return false; IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount); IResource copiedResource = outputFolder.getFile(partialPath); if (copiedResource.exists()) { if (deletedAll) { IResource originalResource = findOriginalResource(partialPath); String id = originalResource.getFullPath().removeFirstSegments(1).toString(); createProblemFor( resource, null, Messages.bind(Messages.build_duplicateResource, id), BatchImageBuilder.this.javaBuilder.javaProject.getOption(JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true)); return false; } copiedResource.delete(IResource.FORCE, null); // last one wins } createFolder(partialPath.removeLastSegments(1), outputFolder); // ensure package folder exists copyResource(resource, copiedResource); return false; case IResource.FOLDER : resource = proxy.requestResource(); if (BatchImageBuilder.this.javaBuilder.filterExtraResource(resource)) return false; if (isAlsoProject && isExcludedFromProject(resource.getFullPath())) return false; // the sourceFolder == project if (exclusionPatterns != null && inclusionPatterns == null) // must walk children if inclusionPatterns != null if (Util.isExcluded(resource.getFullPath(), null, exclusionPatterns, true)) return false; } return true; }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
protected void storeProblemsFor(SourceFile sourceFile, CategorizedProblem[] problems) throws CoreException { if (sourceFile == null || problems == null || problems.length == 0) return; for (int i = problems.length; --i >= 0;) { CategorizedProblem problem = problems[i]; if (problem != null && problem.getID() == IProblem.UndefinedType) { if (this.typeLocatorsWithUndefinedTypes == null) this.typeLocatorsWithUndefinedTypes = new StringSet(3); this.typeLocatorsWithUndefinedTypes.add(sourceFile.typeLocator()); break; } } super.storeProblemsFor(sourceFile, problems); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public IFolder createLinkFolder(IPath externalFolderPath, boolean refreshIfExistAlready, IProgressMonitor monitor) throws CoreException { IProject externalFoldersProject = createExternalFoldersProject(monitor); // run outside synchronized as this can create a resource return createLinkFolder(externalFolderPath, refreshIfExistAlready, externalFoldersProject, monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private IFolder createLinkFolder(IPath externalFolderPath, boolean refreshIfExistAlready, IProject externalFoldersProject, IProgressMonitor monitor) throws CoreException { IFolder result = addFolder(externalFolderPath, externalFoldersProject, false); if (!result.exists()) result.createLink(externalFolderPath, IResource.ALLOW_MISSING_LOCAL, monitor); else if (refreshIfExistAlready) result.refreshLocal(IResource.DEPTH_INFINITE, monitor); return result; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public void cleanUp(IProgressMonitor monitor) throws CoreException { ArrayList toDelete = getFoldersToCleanUp(monitor); if (toDelete == null) return; for (Iterator iterator = toDelete.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); IFolder folder = (IFolder) entry.getValue(); folder.delete(true, monitor); IPath key = (IPath) entry.getKey(); this.folders.remove(key); } IProject project = getExternalFoldersProject(); if (project.isAccessible() && project.members().length == 1/*remaining member is .project*/) project.delete(true, monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private ArrayList getFoldersToCleanUp(IProgressMonitor monitor) throws CoreException { DeltaProcessingState state = JavaModelManager.getDeltaState(); HashMap roots = state.roots; HashMap sourceAttachments = state.sourceAttachments; if (roots == null && sourceAttachments == null) return null; Map knownFolders = getFolders(); ArrayList result = null; synchronized (knownFolders) { Iterator iterator = knownFolders.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); IPath path = (IPath) entry.getKey(); if ((roots != null && !roots.containsKey(path)) && (sourceAttachments != null && !sourceAttachments.containsKey(path))) { if (entry.getValue() != null) { if (result == null) result = new ArrayList(); result.add(entry); } } } } return result; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
public IProject createExternalFoldersProject(IProgressMonitor monitor) throws CoreException { IProject project = getExternalFoldersProject(); if (!project.isAccessible()) { if (!project.exists()) { createExternalFoldersProject(project, monitor); } openExternalFoldersProject(project, monitor); } return project; }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private void openExternalFoldersProject(IProject project, IProgressMonitor monitor) throws CoreException { try { project.open(monitor); } catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); } }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
private void createExternalFoldersProject(IProject project, IProgressMonitor monitor) throws CoreException { IProjectDescription desc = project.getWorkspace().newProjectDescription(project.getName()); IPath stateLocation = JavaCore.getPlugin().getStateLocation(); desc.setLocation(stateLocation.append(EXTERNAL_PROJECT_NAME)); project.create(desc, IResource.HIDDEN, monitor); }
// in model/org/eclipse/jdt/internal/core/UserLibraryClasspathContainerInitializer.java
public void initialize(IPath containerPath, IJavaProject project) throws CoreException { if (isUserLibraryContainer(containerPath)) { String userLibName = containerPath.segment(1); UserLibrary userLibrary = JavaModelManager.getUserLibraryManager().getUserLibrary(userLibName); if (userLibrary != null) { UserLibraryClasspathContainer container = new UserLibraryClasspathContainer(userLibName); JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project }, new IClasspathContainer[] { container }, null); } else if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_no_user_library_found(project, userLibName); } } else if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_not_a_user_library(project, containerPath); } }
// in model/org/eclipse/jdt/internal/core/UserLibraryClasspathContainerInitializer.java
public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion) throws CoreException { if (isUserLibraryContainer(containerPath)) { String name = containerPath.segment(1); if (containerSuggestion != null) { JavaModelManager.getUserLibraryManager().setUserLibrary(name, containerSuggestion.getClasspathEntries(), containerSuggestion.getKind() == IClasspathContainer.K_SYSTEM); } else { JavaModelManager.getUserLibraryManager().removeUserLibrary(name); } // update of affected projects was done as a consequence of setUserLibrary() or removeUserLibrary() } }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
public ZipFile getJar() throws CoreException { return JavaModelManager.getJavaModelManager().getZipFile(getPath()); }
// 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/RegionBasedTypeHierarchy.java
protected void compute() throws JavaModelException, CoreException { HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this); builder.build(this.computeSubtypes); }
// in model/org/eclipse/jdt/internal/core/JarEntryResource.java
protected ZipFile getZipFile() throws CoreException { if (this.parent instanceof IPackageFragment) { JarPackageFragmentRoot root = (JarPackageFragmentRoot) ((IPackageFragment) this.parent).getParent(); return root.getJar(); } else if (this.parent instanceof JarPackageFragmentRoot) { return ((JarPackageFragmentRoot) this.parent).getJar(); } else return ((JarEntryDirectory) this.parent).getZipFile(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void saveExternalLibTimeStamps() throws CoreException { if (this.externalTimeStamps == null) return; // cleanup to avoid any leak ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=244849 ) HashSet toRemove = new HashSet(); if (this.roots != null) { Enumeration keys = this.externalTimeStamps.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (this.roots.get(key) == null) { toRemove.add(key); } } } File timestamps = getTimeStampsFile(); DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps))); out.writeInt(this.externalTimeStamps.size() - toRemove.size()); Iterator entries = this.externalTimeStamps.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IPath key = (IPath) entry.getKey(); if (!toRemove.contains(key)) { out.writeUTF(key.toPortableString()); Long timestamp = (Long) entry.getValue(); out.writeLong(timestamp.longValue()); } } } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing we can do: ignore } } } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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) // non local file system localFile= fileStore.toLocalFile(EFS.CACHE, monitor); return localFile; }
// 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/ProjectReferenceChange.java
public void run(IProgressMonitor monitor) throws CoreException { IProjectDescription description = projectResource.getDescription(); description.setDynamicReferences(requiredProjectArray); projectResource.setDescription(description, IResource.AVOID_NATURE_CONFIG, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected void addToBuildSpec(String builderID) throws CoreException { IProjectDescription description = this.project.getDescription(); int javaCommandIndex = getJavaCommandIndex(description.getBuildSpec()); if (javaCommandIndex == -1) { // Add a Java command to the build spec ICommand command = description.newCommand(); command.setBuilderName(builderID); setJavaCommand(description, command); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void configure() throws CoreException { // register Java builder addToBuildSpec(JavaCore.BUILDER_ID); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void deconfigure() throws CoreException { // deregister Java builder removeFromBuildSpec(JavaCore.BUILDER_ID); // remove .classpath file // getProject().getFile(ClasspathHelper.CLASSPATH_FILENAME).delete(false, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public String getSharedProperty(String key) throws CoreException { String property = null; IFile rscFile = this.project.getFile(key); if (rscFile.exists()) { byte[] bytes = Util.getResourceContentsAsByteArray(rscFile); try { property = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); } } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location != null) { File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file != null && file.exists()) { byte[] bytes; try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { return null; } try { property = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); } } } } return property; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
protected void removeFromBuildSpec(String builderID) throws CoreException { IProjectDescription description = this.project.getDescription(); ICommand[] commands = description.getBuildSpec(); for (int i = 0; i < commands.length; ++i) { if (commands[i].getBuilderName().equals(builderID)) { ICommand[] newCommands = new ICommand[commands.length - 1]; System.arraycopy(commands, 0, newCommands, 0, i); System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1); description.setBuildSpec(newCommands); this.project.setDescription(description, null); return; } } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
private void setJavaCommand( IProjectDescription description, ICommand newCommand) throws CoreException { ICommand[] oldBuildSpec = description.getBuildSpec(); int oldJavaCommandIndex = getJavaCommandIndex(oldBuildSpec); ICommand[] newCommands; if (oldJavaCommandIndex == -1) { // Add a Java build spec before other builders (1FWJK7I) newCommands = new ICommand[oldBuildSpec.length + 1]; System.arraycopy(oldBuildSpec, 0, newCommands, 1, oldBuildSpec.length); newCommands[0] = newCommand; } else { oldBuildSpec[oldJavaCommandIndex] = newCommand; newCommands = oldBuildSpec; } // Commit the spec change into the project description.setBuildSpec(newCommands); this.project.setDescription(description, null); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public void setSharedProperty(String key, String value) throws CoreException { IFile rscFile = this.project.getFile(key); byte[] bytes = null; try { bytes = value.getBytes(org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); } InputStream inputStream = new ByteArrayInputStream(bytes); // update the resource content if (rscFile.exists()) { if (rscFile.isReadOnly()) { // provide opportunity to checkout read-only .classpath file (23984) ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, null); } rscFile.setContents(inputStream, IResource.FORCE, null); } else { rscFile.create(inputStream, IResource.FORCE, null); } }
// in model/org/eclipse/jdt/core/ClasspathContainerInitializer.java
public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion) throws CoreException { // By default, classpath container initializers do not accept updating containers }
// in model/org/eclipse/jdt/core/JavaCore.java
public void configureJavaElementMarker(IMarker marker, IJavaElement element) throws CoreException { if (element instanceof IMember) element = ((IMember) element).getClassFile(); if (marker != null && element != null) marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier()); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException { try { if (monitor != null) { monitor.beginTask(Messages.javamodel_initialization, 100); monitor.subTask(Messages.javamodel_configuring_classpath_containers); } // initialize all containers and variables JavaModelManager manager = JavaModelManager.getJavaModelManager(); SubProgressMonitor subMonitor = null; try { if (monitor != null) { subMonitor = new SubProgressMonitor(monitor, 50); // 50% of the time is spent in initializing containers and variables subMonitor.beginTask("", 100); //$NON-NLS-1$ subMonitor.worked(5); // give feedback to the user that something is happening manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(subMonitor); } if (manager.forceBatchInitializations(true/*initAfterLoad*/)) { // if no other thread has started the batch container initializations manager.getClasspathContainer(Path.EMPTY, null); // force the batch initialization } else { // else wait for the batch initialization to finish while (manager.batchContainerInitializations == JavaModelManager.BATCH_INITIALIZATION_IN_PROGRESS) { if (subMonitor != null) { subMonitor.subTask(manager.batchContainerInitializationsProgress.subTaskName); subMonitor.worked(manager.batchContainerInitializationsProgress.getWorked()); } synchronized(manager) { try { manager.wait(100); } catch (InterruptedException e) { // continue } } } } } finally { if (subMonitor != null) subMonitor.done(); manager.batchContainerInitializationsProgress.initializeAfterLoadMonitor.set(null); } // avoid leaking source attachment properties (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183413 ) // and recreate links for external folders if needed if (monitor != null) monitor.subTask(Messages.javamodel_resetting_source_attachment_properties); final IJavaProject[] projects = manager.getJavaModel().getJavaProjects(); HashSet visitedPaths = new HashSet(); ExternalFoldersManager externalFoldersManager = JavaModelManager.getExternalManager(); for (int i = 0, length = projects.length; i < length; i++) { JavaProject javaProject = (JavaProject) projects[i]; IClasspathEntry[] classpath; try { classpath = javaProject.getResolvedClasspath(); } catch (JavaModelException e) { // project no longer exist: ignore continue; } if (classpath != null) { for (int j = 0, length2 = classpath.length; j < length2; j++) { IClasspathEntry entry = classpath[j]; if (entry.getSourceAttachmentPath() != null) { IPath entryPath = entry.getPath(); if (visitedPaths.add(entryPath)) { Util.setSourceAttachmentProperty(entryPath, null); } } // else source might have been attached by IPackageFragmentRoot#attachSource(...), we keep it if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath entryPath = entry.getPath(); if (ExternalFoldersManager.isExternalFolderPath(entryPath) && externalFoldersManager.getFolder(entryPath) == null) { externalFoldersManager.addFolder(entryPath, true); } } } } } try { externalFoldersManager.createPendingFolders(monitor); } catch(JavaModelException jme) { // Creation of external folder project failed. Log it and continue; Util.log(jme, "Error while processing external folders"); //$NON-NLS-1$ } // initialize delta state if (monitor != null) monitor.subTask(Messages.javamodel_initializing_delta_state); manager.deltaState.rootsAreStale = true; // in case it was already initialized before we cleaned up the source attachment proprties manager.deltaState.initializeRoots(true/*initAfteLoad*/); // dummy query for waiting until the indexes are ready if (monitor != null) monitor.subTask(Messages.javamodel_configuring_searchengine); SearchEngine engine = new SearchEngine(); IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); try { engine.searchAllTypeNames( null, SearchPattern.R_EXACT_MATCH, "!@$#!@".toCharArray(), //$NON-NLS-1$ SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE, IJavaSearchConstants.CLASS, scope, new TypeNameRequestor() { public void acceptType( int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) { // no type to accept } }, // will not activate index query caches if indexes are not ready, since it would take to long // to wait until indexes are fully rebuild IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search ); } catch (JavaModelException e) { // /search failed: ignore } catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed } // check if the build state version number has changed since last session // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=98969) if (monitor != null) monitor.subTask(Messages.javamodel_getting_build_state_number); QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "stateVersionNumber"); //$NON-NLS-1$ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); String versionNumber = null; try { versionNumber = root.getPersistentProperty(qName); } catch (CoreException e) { // could not read version number: consider it is new } final JavaModel model = manager.getJavaModel(); String newVersionNumber = Byte.toString(State.VERSION); if (!newVersionNumber.equals(versionNumber)) { // build state version number has changed: touch every projects to force a rebuild if (JavaBuilder.DEBUG) System.out.println("Build state version number has changed"); //$NON-NLS-1$ IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor progressMonitor2) throws CoreException { for (int i = 0, length = projects.length; i < length; i++) { IJavaProject project = projects[i]; try { if (JavaBuilder.DEBUG) System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$ project.getProject().touch(progressMonitor2); } catch (CoreException e) { // could not touch this project: ignore } } } }; if (monitor != null) monitor.subTask(Messages.javamodel_building_after_upgrade); try { ResourcesPlugin.getWorkspace().run(runnable, monitor); } catch (CoreException e) { // could not touch all projects } try { root.setPersistentProperty(qName, newVersionNumber); } catch (CoreException e) { Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$ } } // ensure external jars are refreshed (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=93668) try { if (monitor != null) monitor.subTask(Messages.javamodel_refreshing_external_jars); model.refreshExternalArchives( null/*refresh all projects*/, monitor == null ? null : new SubProgressMonitor(monitor, 1) // 1% of the time is spent in jar refresh ); } catch (JavaModelException e) { // refreshing failed: ignore } } finally { if (monitor != null) monitor.done(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
public void run(IProgressMonitor progressMonitor2) throws CoreException { for (int i = 0, length = projects.length; i < length; i++) { IJavaProject project = projects[i]; try { if (JavaBuilder.DEBUG) System.out.println("Touching " + project.getElementName()); //$NON-NLS-1$ project.getProject().touch(progressMonitor2); } catch (CoreException e) { // could not touch this project: ignore } } }
// in model/org/eclipse/jdt/core/JavaCore.java
public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException { // only match units or classfiles if (element instanceof IMember){ IMember member = (IMember) element; if (member.isBinary()){ element = member.getClassFile(); } else { element = member.getCompilationUnit(); } } if (element == null) return false; if (marker == null) return false; String markerHandleId = (String)marker.getAttribute(ATT_HANDLE_ID); if (markerHandleId == null) return false; IJavaElement markerElement = JavaCore.create(markerHandleId); while (true){ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs. // cycle through enclosing types in case marker is associated with a classfile (15568) if (markerElement instanceof IClassFile){ IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType(); if (enclosingType != null){ markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile continue; } } break; } return false; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException { // only match units or classfiles if (element instanceof IMember){ IMember member = (IMember) element; if (member.isBinary()){ element = member.getClassFile(); } else { element = member.getCompilationUnit(); } } if (element == null) return false; if (markerDelta == null) return false; String markerDeltarHandleId = (String)markerDelta.getAttribute(ATT_HANDLE_ID); if (markerDeltarHandleId == null) return false; IJavaElement markerElement = JavaCore.create(markerDeltarHandleId); while (true){ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs. // cycle through enclosing types in case marker is associated with a classfile (15568) if (markerElement instanceof IClassFile){ IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType(); if (enclosingType != null){ markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile continue; } } break; } return false; }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException { run(action, ResourcesPlugin.getWorkspace().getRoot(), monitor); }
// in model/org/eclipse/jdt/core/JavaCore.java
public static void run(IWorkspaceRunnable action, ISchedulingRule rule, IProgressMonitor monitor) throws CoreException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); if (workspace.isTreeLocked()) { new BatchOperation(action).run(monitor); } else { // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode workspace.run(new BatchOperation(action), rule, IWorkspace.AVOID_UPDATE, monitor); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(boolean ignoreComments) throws CoreException { int curr= 0; do { try { curr= this.scanner.getNextToken(); if (curr == TerminalTokens.TokenNameEOF) { throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$ } } catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); } } while (ignoreComments && isComment(curr)); return curr; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int readNext(int offset, boolean ignoreComments) throws CoreException { setOffset(offset); return readNext(ignoreComments); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getNextStartOffset(int offset, boolean ignoreComments) throws CoreException { readNext(offset, ignoreComments); return getCurrentStartOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getNextEndOffset(int offset, boolean ignoreComments) throws CoreException { readNext(offset, ignoreComments); return getCurrentEndOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public void readToToken(int tok) throws CoreException { int curr= 0; do { curr= readNext(false); } while (curr != tok); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public void readToToken(int tok, int offset) throws CoreException { setOffset(offset); readToToken(tok); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getTokenStartOffset(int token, int startOffset) throws CoreException { readToToken(token, startOffset); return getCurrentStartOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getTokenEndOffset(int token, int startOffset) throws CoreException { readToToken(token, startOffset); return getCurrentEndOffset(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
public int getPreviousTokenEndOffset(int token, int startOffset) throws CoreException { setOffset(startOffset); int res= startOffset; int curr= readNext(false); while (curr != token) { res= getCurrentEndOffset(); curr= readNext(false); } return res; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public final TextEdit rewriteImports(IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor= new NullProgressMonitor(); } try { monitor.beginTask(Messages.bind(Messages.importRewrite_processDescription), 2); if (!hasRecordedChanges()) { this.createdImports= CharOperation.NO_STRINGS; this.createdStaticImports= CharOperation.NO_STRINGS; return new MultiTextEdit(); } CompilationUnit usedAstRoot= this.astRoot; if (usedAstRoot == null) { ASTParser parser= ASTParser.newParser(AST.JLS4); parser.setSource(this.compilationUnit); parser.setFocalPosition(0); // reduced AST parser.setResolveBindings(false); usedAstRoot= (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1)); } ImportRewriteAnalyzer computer= new ImportRewriteAnalyzer( this.compilationUnit, usedAstRoot, this.importOrder, this.importOnDemandThreshold, this.staticImportOnDemandThreshold, this.restoreExistingImports, this.useContextToFilterImplicitImports); computer.setFilterImplicitImports(this.filterImplicitImports); if (this.addedImports != null) { for (int i= 0; i < this.addedImports.size(); i++) { String curr= (String) this.addedImports.get(i); computer.addImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0)); } } if (this.removedImports != null) { for (int i= 0; i < this.removedImports.size(); i++) { String curr= (String) this.removedImports.get(i); computer.removeImport(curr.substring(1), STATIC_PREFIX == curr.charAt(0)); } } TextEdit result= computer.getResultingEdits(new SubProgressMonitor(monitor, 1)); this.createdImports= computer.getCreatedImports(); this.createdStaticImports= computer.getCreatedStaticImports(); return result; } finally { monitor.done(); } }
208
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/ClasspathSourceDirectory.java
catch(CoreException ignored) { // treat as if missing }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (CoreException e1) { // problem opening zip file or getting root kind // consider root corrupt and ignore // just resize cpLocations System.arraycopy(cpLocations, 0, cpLocations = new ClasspathLocation[cpLocations.length-1], 0, index); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { // cannot read class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException ce) { // Do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch(CoreException ce) { try { return ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset(); } catch (CoreException e) { // use no encoding } }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (CoreException e) { // use no encoding }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddFolderToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (CoreException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (CoreException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(CoreException e) { // ignore delta if not able to traverse }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(CoreException e){ // project doesn't exist or is not open: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e){ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind(Messages.classpath_unboundProject, new String[] {path.segment(0), projectName})); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (CoreException e) { if (e.getStatus().getMessage() == Messages.status_IOException) { return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Messages.bind( Messages.classpath_archiveReadError, new String[] {entryPathMsg, project.getElementName()})); } }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/NonJavaResource.java
catch (CoreException e) { Util.log(e, "Could not retrieve children of " + this.resource.getFullPath()); //$NON-NLS-1$ return NO_CHILDREN; }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { // skip }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { // ignore Util.log(e, "Exception while initializing all containers"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (vStats == null) vStats= new ArrayList(); vStats.add(e.getStatus()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/builder/NameEnvironment.java
catch(CoreException e) { this.sourceLocations = new ClasspathMultiDirectory[0]; this.binaryLocations = new ClasspathLocation[0]; }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there are no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there are no tasks }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { // assume there were no problems }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException while cleaning: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException ignore) { // skip it }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (CoreException ignore) { // skip it }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch(CoreException ignored) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (CoreException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException ignored) { // ignore the second exception }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$ if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) createProblemFor(compilationUnit.resource, null, Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR); else createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile, JavaCore.ERROR); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // must continue with compile loop so just log the CoreException Util.log(e, "JavaBuilder logging CompilationParticipant's CoreException to help debugging"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Error while creating a link for external folder :" + folderPath); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while initializing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // use default encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // no problem, use default encoding }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // ignore e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { // Ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (CoreException e) { return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (CoreException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
catch (CoreException e1) { this.encoding = null; }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException ce) { // use no encoding }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (CoreException e) { // CoreException from hasNature - should not happen since we check that the project is accessible // JavaModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(CoreException ce) { // do not use any encoding encoding = null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/ResourceCompilationUnit.java
catch (CoreException e) { return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (CoreException e) { resources = NO_NON_JAVA_RESOURCES; resourcesCounter = 0; }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(project.getName())) return true; // project does not exist or is not open }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not create marker: cannot do much if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not flush markers: not much we can do if (JavaModelManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // could not get markers: return null }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { // problems loading preference store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { return newDoesNotExistStatus(); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e) { // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_container_initializer(containerID, configurationElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(CoreException e){ // executable extension could not be created: ignore this initializer if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { verbose_failed_to_instanciate_variable_initializer(variable, configElement); e.printStackTrace(); } }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException ce) { // fails silently and return plugin global encoding if core exception occurs }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not read version number: consider it is new }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not touch this project: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { // could not touch all projects }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (CoreException e) { Util.log(e, "Could not persist build state version number"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(CoreException e){ // unable to instantiate extension, will answer default formatter instead }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(CoreException e){ // unable to read }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch(CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java
catch (CoreException e) { handleException(e); }
79
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { // catch the case that a package has been renamed and collides on disk with an as-yet-to-be-deleted package if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { if (JavaBuilder.DEBUG) System.out.println("ABORTING incremental build... found renamed package"); //$NON-NLS-1$ return false; } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/IncrementalImageBuilder.java
catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) { IStatus status = e.getStatus(); if (status instanceof IResourceStatus) { IPath oldFilePath = ((IResourceStatus) status).getPath(); char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray(); char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(compilationUnit.typeLocator()); boolean fromSameFile = false; if (previousTypeNames == null) { fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName); } else { for (int i = 0, l = previousTypeNames.length; i < l; i++) { if (CharOperation.equals(previousTypeNames[i], oldTypeName)) { fromSameFile = true; break; } } } if (fromSameFile) { // file is defined by the same compilationUnit, but won't be deleted until later so do it now IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment())); collision.delete(true, false, null); boolean success = false; try { file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null); success = true; } catch (CoreException ignored) { // ignore the second exception } if (success) return; } } // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName)); } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { // handle the case when the source resource is deleted source.refreshLocal(0, null); if (!source.exists()) return; // source resource was deleted so skip it throw e; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/builder/BatchImageBuilder.java
catch (CoreException e) { throw internalException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
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; }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
catch (CoreException e) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=148970 if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(affectedProject.getElementName())) throw e; }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
3
runtime (Domain) DOMException
public class DOMException extends RuntimeException {

	private static final long serialVersionUID = 2536853590795032028L; // backward compatible
/**
 * Creates a new exception with no detail message.
 */
public DOMException() {
	// just create a new DOMException with no detail message
}
/**
 * Creates a new exception with the given detail message.
 *
 * @param message the detail message
 */
public DOMException(String message) {
	super(message);
}
}
10
            
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { DOMNode first = getFirstFieldDeclaration(); DOMNode last = getLastFieldDeclaration(); DOMNode node= first; String source= first.getContents(); while (node != last) { node= node.fNextNode; source+=node.getContents(); } DOMBuilder builder = new DOMBuilder(); IDOMField[] details= builder.createFields(source.toCharArray()); if (details.length == 0) { throw new DOMException(Messages.dom_cannotDetail); } else { node= this; for (int i= 0; i < details.length; i++) { node.shareContents((DOMNode)details[i]); node= node.fNextNode; } } } else { super.becomeDetailed(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { DOMNode detailed= getDetailedNode(); if (detailed == null) { throw new DOMException(Messages.dom_cannotDetail); } if (detailed != this) { shareContents(detailed); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
0 6
            
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { if (isVariableDeclarator() || hasMultipleVariableDeclarators()) { DOMNode first = getFirstFieldDeclaration(); DOMNode last = getLastFieldDeclaration(); DOMNode node= first; String source= first.getContents(); while (node != last) { node= node.fNextNode; source+=node.getContents(); } DOMBuilder builder = new DOMBuilder(); IDOMField[] details= builder.createFields(source.toCharArray()); if (details.length == 0) { throw new DOMException(Messages.dom_cannotDetail); } else { node= this; for (int i= 0; i < details.length; i++) { node.shareContents((DOMNode)details[i]); node= node.fNextNode; } } } else { super.becomeDetailed(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { if (isVariableDeclarator()) { expand(); } super.insertSibling(sibling); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException { basicAddChild(child); // if the node is a constructor, it must also be fragmented to update the constructor's name if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } else { fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
protected void becomeDetailed() throws DOMException { if (!isDetailed()) { DOMNode detailed= getDetailedNode(); if (detailed == null) { throw new DOMException(Messages.dom_cannotDetail); } if (detailed != this) { shareContents(detailed); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
1
            
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (DOMException e) { if (e.code != DOMException.NOT_FOUND_ERR) throw e; return null; }
1
            
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (DOMException e) { if (e.code != DOMException.NOT_FOUND_ERR) throw e; return null; }
0
runtime (Lib) Error 2
            
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
public void deleteVariable(IGlobalVariable variable) { if (variable instanceof GlobalVariableWrapper) { GlobalVariableWrapper wrapper = (GlobalVariableWrapper)variable; this.context.deleteVariable(wrapper.variable); } else { throw new Error("Unknown implementation of IGlobalVariable"); //$NON-NLS-1$ } }
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new Error(); } }
1
            
// in model/org/eclipse/jdt/internal/core/JavaElementInfo.java
catch (CloneNotSupportedException e) { throw new Error(); }
3
            
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
public CompilationUnitDeclaration removeNextUnit() throws Error { CompilationUnitDeclaration next = null; boolean yield = false; synchronized (this) { next = this.units[this.currentIndex]; if (next == null || this.caughtException != null) { do { if (this.processingThread == null) { if (this.caughtException != null) { // rethrow the caught exception from the processingThread in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } return null; } //System.out.print('r'); //if (this.sleepCount > 0) throw new IllegalStateException(new Integer(this.sleepCount).toString()); this.sleepCount = -1; try { wait(100); } catch (InterruptedException ignore) { // ignore } this.sleepCount = 0; next = this.units[this.currentIndex]; } while (next == null); } this.units[this.currentIndex++] = null; if (this.currentIndex >= this.size) this.currentIndex = 0; if (this.sleepCount >= 1 && ++this.sleepCount > 4) { notify(); // wake up processing thread to add next unit but only after removing some elements first yield = this.sleepCount > 8; } } if (yield) Thread.yield(); return next; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
public char[] getContents(ICompilationUnit unit) throws Error { if (this.readingThreads == null || this.units.length == 0) { if (this.caughtException != null) { // rethrow the caught exception from the readingThreads in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } return unit.getContents(); } boolean yield = false; char[] result = null; synchronized (this) { if (unit == this.filesRead[this.readyToReadPosition]) { result = this.contentsRead[this.readyToReadPosition]; while (result == this.readInProcessMarker || result == null) { // let the readingThread know we're waiting //System.out.print('|'); this.contentsRead[this.readyToReadPosition] = null; try { wait(250); } catch (InterruptedException ignore) { // ignore } if (this.caughtException != null) { // rethrow the caught exception from the readingThreads in the main compiler thread if (this.caughtException instanceof Error) throw (Error) this.caughtException; throw (RuntimeException) this.caughtException; } result = this.contentsRead[this.readyToReadPosition]; } // free spot for next file this.filesRead[this.readyToReadPosition] = null; this.contentsRead[this.readyToReadPosition] = null; if (++this.readyToReadPosition >= this.contentsRead.length) this.readyToReadPosition = 0; if (this.sleepingThreadCount > 0) { //System.out.print('+'); //System.out.print(this.nextFileToRead); notify(); yield = this.sleepingThreadCount == this.readingThreads.length; } } else { // must make sure we're reading ahead of the unit int unitIndex = 0; for (int l = this.units.length; unitIndex < l; unitIndex++) if (this.units[unitIndex] == unit) break; if (unitIndex == this.units.length) { // attempting to read a unit that was not included in the initial files - should not happen this.units = new ICompilationUnit[0]; // stop looking for more } else if (unitIndex >= this.nextFileToRead) { // start over //System.out.println(unitIndex + " vs " + this.nextFileToRead); this.nextFileToRead = unitIndex + START_CUSHION; this.readyToReadPosition = 0; this.nextAvailablePosition = 0; this.filesRead = new ICompilationUnit[CACHE_SIZE]; this.contentsRead = new char[CACHE_SIZE][]; notifyAll(); } } } if (yield) Thread.yield(); // ensure other threads get a chance if (result != null) return result; //System.out.print('-'); return unit.getContents(); }
11
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (Error e) { synchronized (this) { this.processingThread = null; this.caughtException = e; } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (Error e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
9
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (Error e) { if (this.processingThread != null && !(e instanceof ThreadDeath)) { // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (Error e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
0
checked (Lib) Exception 0 0 11
            
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
private void notifyParticipants(final CompilationUnit workingCopy) { IJavaProject javaProject = getWorkingCopy().getJavaProject(); CompilationParticipant[] participants = JavaModelManager.getJavaModelManager().compilationParticipants.getCompilationParticipants(javaProject); if (participants == null) return; final ReconcileContext context = new ReconcileContext(this, workingCopy); for (int i = 0, length = participants.length; i < length; i++) { final CompilationParticipant participant = participants[i]; SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { if (exception instanceof Error) { throw (Error) exception; // errors are not supposed to be caught } else if (exception instanceof OperationCanceledException) throw (OperationCanceledException) exception; else if (exception instanceof UnsupportedOperationException) { // might want to disable participant as it tried to modify the buffer of the working copy being reconciled Util.log(exception, "Reconcile participant attempted to modify the buffer of the working copy being reconciled"); //$NON-NLS-1$ } else Util.log(exception, "Exception occurred in reconcile participant"); //$NON-NLS-1$ } public void run() throws Exception { participant.reconcile(context); } }); } }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
public void run() throws Exception { participant.reconcile(context); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
private void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) { final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType); for (int i= 0; i < listenerCount; i++) { if ((listenerMask[i] & eventType) != 0){ final IElementChangedListener listener = listeners[i]; long start = -1; if (VERBOSE) { System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ start = System.currentTimeMillis(); } // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ } public void run() throws Exception { PerformanceStats stats = null; if(PERF) { stats = PerformanceStats.getStats(JavaModelManager.DELTA_LISTENER_PERF, listener); stats.startRun(); } listener.elementChanged(extraEvent); if(PERF) { stats.endRun(); } } }); if (VERBOSE) { System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
public void run() throws Exception { PerformanceStats stats = null; if(PERF) { stats = PerformanceStats.getStats(JavaModelManager.DELTA_LISTENER_PERF, listener); stats.startRun(); } listener.elementChanged(extraEvent); if(PERF) { stats.endRun(); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
private void notifyTypeHierarchies(IElementChangedListener[] listeners, int listenerCount) { for (int i= 0; i < listenerCount; i++) { final IElementChangedListener listener = listeners[i]; if (!(listener instanceof TypeHierarchy)) continue; // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$ } public void run() throws Exception { TypeHierarchy typeHierarchy = (TypeHierarchy)listener; if (typeHierarchy.hasFineGrainChanges()) { // case of changes in primary working copies typeHierarchy.needsRefresh = true; typeHierarchy.fireChange(); } } }); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
public void run() throws Exception { TypeHierarchy typeHierarchy = (TypeHierarchy)listener; if (typeHierarchy.hasFineGrainChanges()) { // case of changes in primary working copies typeHierarchy.needsRefresh = true; typeHierarchy.fireChange(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public CompilationParticipant[] getCompilationParticipants(IJavaProject project) { final Object[][] participantsPerSource = getRegisteredParticipants(); if (participantsPerSource == NO_PARTICIPANTS) return null; String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true/*inherit options*/); final int sourceLevelIndex = indexForSourceLevel(sourceLevel); final Object[] participants = participantsPerSource[sourceLevelIndex]; int length = participants.length; CompilationParticipant[] result = new CompilationParticipant[length]; int index = 0; for (int i = 0; i < length; i++) { if (participants[i] instanceof IConfigurationElement) { final IConfigurationElement configElement = (IConfigurationElement) participants[i]; final int participantIndex = i; SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred while creating compilation participant"); //$NON-NLS-1$ } public void run() throws Exception { Object executableExtension = configElement.createExecutableExtension("class"); //$NON-NLS-1$ for (int j = sourceLevelIndex; j < MAX_SOURCE_LEVEL; j++) participantsPerSource[j][participantIndex] = executableExtension; } }); } CompilationParticipant participant; if ((participants[i] instanceof CompilationParticipant) && (participant = (CompilationParticipant) participants[i]).isActive(project)) result[index++] = participant; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void run() throws Exception { Object executableExtension = configElement.createExecutableExtension("class"); //$NON-NLS-1$ for (int j = sourceLevelIndex; j < MAX_SOURCE_LEVEL; j++) participantsPerSource[j][participantIndex] = executableExtension; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public AbstractAnnotationProcessorManager createAnnotationProcessorManager() { synchronized(this) { if (this.annotationProcessorManagerFactory == null) { IExtensionPoint extension = Platform.getExtensionRegistry().getExtensionPoint(JavaCore.PLUGIN_ID, ANNOTATION_PROCESSOR_MANAGER_EXTPOINT_ID); if (extension == null) return null; IExtension[] extensions = extension.getExtensions(); for(int i = 0; i < extensions.length; i++) { if (i > 0) { Util.log(null, "An annotation processor manager is already registered: ignoring " + extensions[i].getUniqueIdentifier()); //$NON-NLS-1$ break; } IConfigurationElement[] configElements = extensions[i].getConfigurationElements(); for(int j = 0; j < configElements.length; j++) { final IConfigurationElement configElement = configElements[j]; if ("annotationProcessorManager".equals(configElement.getName())) { //$NON-NLS-1$ this.annotationProcessorManagerFactory = configElement; break; } } } } } if (this.annotationProcessorManagerFactory == null) { return null; } final AbstractAnnotationProcessorManager[] apm = new AbstractAnnotationProcessorManager[1]; apm[0] = null; final IConfigurationElement factory = this.annotationProcessorManagerFactory; SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred while loading annotation processor manager"); //$NON-NLS-1$ } public void run() throws Exception { Object executableExtension = factory.createExecutableExtension("class"); //$NON-NLS-1$ if (executableExtension instanceof AbstractAnnotationProcessorManager) { apm[0] = (AbstractAnnotationProcessorManager) executableExtension; } } }); return apm[0]; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
public void run() throws Exception { Object executableExtension = factory.createExecutableExtension("class"); //$NON-NLS-1$ if (executableExtension instanceof AbstractAnnotationProcessorManager) { apm[0] = (AbstractAnnotationProcessorManager) executableExtension; } }
// in model/org/eclipse/jdt/internal/core/Buffer.java
protected void notifyChanged(final BufferChangedEvent event) { ArrayList listeners = this.changeListeners; if (listeners != null) { for (int i = 0, size = listeners.size(); i < size; ++i) { final IBufferChangedListener listener = (IBufferChangedListener) listeners.get(i); SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of buffer change notification"); //$NON-NLS-1$ } public void run() throws Exception { listener.bufferChanged(event); } }); } }
// in model/org/eclipse/jdt/internal/core/Buffer.java
public void run() throws Exception { listener.bufferChanged(event); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
public void fireChange() { ArrayList listeners = getClonedChangeListeners(); // clone so that a listener cannot have a side-effect on this list when being notified if (listeners == null) { return; } if (DEBUG) { System.out.println("FIRING hierarchy change ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ if (this.focusType != null) { System.out.println(" for hierarchy focused on " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$ } } for (int i= 0; i < listeners.size(); i++) { final ITypeHierarchyChangedListener listener= (ITypeHierarchyChangedListener)listeners.get(i); SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of Type hierarchy change notification"); //$NON-NLS-1$ } public void run() throws Exception { listener.typeHierarchyChanged(TypeHierarchy.this); } }); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
public void run() throws Exception { listener.typeHierarchyChanged(TypeHierarchy.this); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void resourceChanged(final IResourceChangeEvent event) { for (int i = 0; i < this.preResourceChangeListenerCount; i++) { // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief final IResourceChangeListener listener = this.preResourceChangeListeners[i]; if ((this.preResourceChangeEventMasks[i] & event.getType()) != 0) SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable exception) { Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$ } public void run() throws Exception { listener.resourceChanged(event); } }); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
public void run() throws Exception { listener.resourceChanged(event); }
// in model/org/eclipse/jdt/core/JavaCore.java
public void stop(BundleContext context) throws Exception { try { JavaModelManager.getJavaModelManager().shutdown(); } finally { // ensure we call super.stop as the last thing super.stop(context); } }
// in model/org/eclipse/jdt/core/JavaCore.java
public void start(BundleContext context) throws Exception { super.start(context); JavaModelManager.getJavaModelManager().startup(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
public Object start(IApplicationContext context) throws Exception { File[] filesToFormat = processCommandLine((String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS)); if (filesToFormat == null) { return IApplication.EXIT_OK; } if (!this.quiet) { if (this.configName != null) { System.out.println(Messages.bind(Messages.CommandLineConfigFile, this.configName)); } System.out.println(Messages.bind(Messages.CommandLineStart)); } final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(this.options); // format the list of files and/or directories for (int i = 0, max = filesToFormat.length; i < max; i++) { final File file = filesToFormat[i]; if (file.isDirectory()) { formatDirTree(file, codeFormatter); } else if (Util.isJavaLikeFileName(file.getPath())) { formatFile(file, codeFormatter); } } if (!this.quiet) { System.out.println(Messages.bind(Messages.CommandLineDone)); } return IApplication.EXIT_OK; }
17
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (Exception e) { this.printlnErr(this.main.bind( "requestor.notRetrieveErrorMessage", problem.toString())); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (Exception e) { // it's just for debug purposes... ignore all exceptions in this area }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
catch(Exception e){ // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
catch (Exception e) { if (JobManager.VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch(Exception e) { this.knownPackageNames = new SimpleSet(); // assume for this build the zipFile is empty }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (Exception ex) { validComment = false; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (Exception e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ast/JavadocSingleNameReference.java
catch (Exception e) { scope.problemReporter().javadocUndeclaredParamTagName(this.token, this.sourceStart, this.sourceEnd, -1); }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (Exception ex) { // Give up extended ranges at this level if unexpected exception happens... }
4
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (Exception ex) { throw new BuildException(ex); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/util/ClassFileReader.java
catch (Exception e) { e.printStackTrace(); throw new ClassFormatException(ClassFormatException.ERROR_TRUNCATED_INPUT); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch (Exception e) { throw new ClassFormatException( ClassFormatException.ErrTruncatedInput, readOffset); }
0
unknown (Lib) ExceptionInInitializerError 1 1
            
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
0 0 0 0
unknown (Lib) FileNotFoundException 0 0 0 16
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (FileNotFoundException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559 }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (FileNotFoundException e) { e.printStackTrace(); }
1
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
1
runtime (Domain) FoundRelevantDeltaException
class FoundRelevantDeltaException extends RuntimeException {
				private static final long serialVersionUID = 7137113252936111022L; // backward compatible
				// only the class name is used (to differenciate from other RuntimeExceptions)
			}
2
            
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
public boolean visit(IResourceDelta delta) /* throws CoreException */ { switch (delta.getKind()){ case IResourceDelta.ADDED : case IResourceDelta.REMOVED : throw new FoundRelevantDeltaException(); case IResourceDelta.CHANGED : // if any flag is set but SYNC or MARKER, this delta should be considered if (delta.getAffectedChildren().length == 0 // only check leaf delta nodes && (delta.getFlags() & ~(IResourceDelta.SYNC | IResourceDelta.MARKERS)) != 0) { throw new FoundRelevantDeltaException(); } } return true; }
0 0 1
            
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(FoundRelevantDeltaException e) { //System.out.println("RELEVANT DELTA detected in: "+ (System.currentTimeMillis() - start)); return true; }
0 0
checked (Lib) IOException 31
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
void initialize(boolean reuseExistingFile) throws IOException { if (this.indexFile.exists()) { if (reuseExistingFile) { FileInputStream stream = new FileInputStream(this.indexFile); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, 128); try { char[] signature = readStreamChars(stream); if (!CharOperation.equals(signature, SIGNATURE_CHARS)) { throw new IOException(Messages.exception_wrongFormat); } this.headerInfoOffset = readStreamInt(stream); if (this.headerInfoOffset > 0) { // file is empty if its not set stream.skip(this.headerInfoOffset - this.bufferEnd); // assume that the header info offset is over current buffer end this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); readHeaderInfo(stream); } } finally { stream.close(); } return; } if (!this.indexFile.delete()) { if (DEBUG) System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$ } } if (this.indexFile.createNewFile()) { FileOutputStream stream = new FileOutputStream(this.indexFile, false); try { this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; writeStreamChars(stream, SIGNATURE_CHARS); writeStreamInt(stream, -1); // file is empty // write the buffer to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } } finally { stream.close(); } } else { if (DEBUG) System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$ } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException { if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file if (DEBUG) System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$ } else if (!newIndexFile.createNewFile()) { if (DEBUG) System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$ } int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize; this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); this.categoryTables = new HashtableOfObject(size); this.separator = diskIndex.separator; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException { // assume write lock is held // compute & write out new docNames String[] docNames = readAllDocumentNames(); int previousLength = docNames.length; int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames SimpleLookupTable indexedDocuments = new SimpleLookupTable(3); // for each new/changed document in the memoryIndex docNames = computeDocumentNames(docNames, positions, indexedDocuments, memoryIndex); if (docNames.length == 0) { if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved // index is now empty since all the saved documents were removed DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath()); newDiskIndex.initialize(false); return newDiskIndex; } DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$ try { newDiskIndex.initializeFrom(this, newDiskIndex.indexFile); FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false); int offsetToHeader = -1; try { newDiskIndex.writeAllDocumentNames(docNames, stream); docNames = null; // free up the space // add each new/changed doc to empty category tables using its new position # if (indexedDocuments.elementSize > 0) { Object[] names = indexedDocuments.keyTable; Object[] integerPositions = indexedDocuments.valueTable; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) newDiskIndex.copyQueryResults( (HashtableOfObject) memoryIndex.docsToReferences.get(names[i]), ((Integer) integerPositions[i]).intValue()); } indexedDocuments = null; // free up the space // merge each category table with the new ones & write them out if (previousLength == 0) newDiskIndex.writeCategories(stream); else newDiskIndex.mergeCategories(this, positions, stream); offsetToHeader = newDiskIndex.streamEnd; newDiskIndex.writeHeaderInfo(stream); positions = null; // free up the space } finally { stream.close(); this.streamBuffer = null; } newDiskIndex.writeOffsetToHeader(offsetToHeader); // rename file by deleting previous index file & renaming temp one if (this.indexFile.exists() && !this.indexFile.delete()) { if (DEBUG) System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$ } if (!newDiskIndex.indexFile.renameTo(this.indexFile)) { if (DEBUG) System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$ } } catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; } newDiskIndex.indexFile = this.indexFile; return newDiskIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readHeaderInfo(FileInputStream stream) throws IOException { // must be same order as writeHeaderInfo() this.numberOfChunks = readStreamInt(stream); this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF; this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF; this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF); long fileLength = this.indexFile.length(); if (this.numberOfChunks > fileLength ) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } this.chunkOffsets = new int[this.numberOfChunks]; for (int i = 0; i < this.numberOfChunks; i++) this.chunkOffsets[i] = readStreamInt(stream); this.startOfCategoryTables = readStreamInt(stream); int size = readStreamInt(stream); this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); if (size > fileLength) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } char[] previousCategory = null; int offset = -1; for (int i = 0; i < size; i++) { char[] categoryName = INTERNED_CATEGORY_NAMES.get(readStreamChars(stream)); offset = readStreamInt(stream); this.categoryOffsets.put(categoryName, offset); // cache offset to category table if (previousCategory != null) { this.categoryEnds.put(previousCategory, offset); // cache end of the category table } previousCategory = categoryName; } if (previousCategory != null) { this.categoryEnds.put(previousCategory, this.headerInfoOffset); // cache end of the category table } this.categoryTables = new HashtableOfObject(3); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry loadClasspathEntry() throws IOException { int id = loadInt(); if (id < 0 || id > this.allClasspathEntryCount) throw new IOException("Unexpected classpathentry id"); //$NON-NLS-1$ if (id < this.allClasspathEntryCount) return this.allClasspathEntries[id]; int contentKind = loadInt(); int entryKind = loadInt(); IPath path = loadPath(); IPath[] inclusionPatterns = loadPaths(); IPath[] exclusionPatterns = loadPaths(); IPath sourceAttachmentPath = loadPath(); IPath sourceAttachmentRootPath = loadPath(); IPath specificOutputLocation = loadPath(); boolean isExported = loadBoolean(); IAccessRule[] accessRules = loadAccessRules(); boolean combineAccessRules = loadBoolean(); IClasspathAttribute[] extraAttributes = loadAttributes(); IClasspathEntry entry = new ClasspathEntry(contentKind, entryKind, path, inclusionPatterns, exclusionPatterns, sourceAttachmentPath, sourceAttachmentRootPath, specificOutputLocation, isExported, accessRules, combineAccessRules, extraAttributes); IClasspathEntry[] array = this.allClasspathEntries; if (array == null || id == array.length) { array = new IClasspathEntry[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allClasspathEntries, 0, array, 0, id); this.allClasspathEntries = array; } array[id] = entry; this.allClasspathEntryCount = id + 1; return entry; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private String loadString() throws IOException { int id = loadInt(); if (id < 0 || id > this.allStringsCount) throw new IOException("Unexpected string id"); //$NON-NLS-1$ if (id < this.allStringsCount) return this.allStrings[id]; String string = this.in.readUTF(); String[] array = this.allStrings; if (array == null || id == array.length) { array = new String[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allStrings, 0, array, 0, id); this.allStrings = array; } array[id] = string; this.allStringsCount = id + 1; return string; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
protected Object readState(IProject project) throws CoreException { File file = getSerializationFile(project); if (file != null && file.exists()) { try { DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file))); try { String pluginID= in.readUTF(); if (!pluginID.equals(JavaCore.PLUGIN_ID)) throw new IOException(Messages.build_wrongFileFormat); String kind= in.readUTF(); if (!kind.equals("STATE")) //$NON-NLS-1$ throw new IOException(Messages.build_wrongFileFormat); if (in.readBoolean()) return JavaBuilder.readState(project, in); if (JavaBuilder.DEBUG) System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$ } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$ } } else if (JavaBuilder.DEBUG) { if (file == null) System.out.println("Project does not exist: " + project); //$NON-NLS-1$ else System.out.println("Build state file " + file.getPath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$ } return null; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static UserLibrary createFromString(Reader reader) throws IOException { Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase(TAG_USERLIBRARY)) { throw new IOException(Messages.file_badFormat); } String version= cpElement.getAttribute(TAG_VERSION); boolean isSystem= Boolean.valueOf(cpElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue(); NodeList list= cpElement.getChildNodes(); int length = list.getLength(); ArrayList res= new ArrayList(length); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equals(TAG_ARCHIVE)) { String pathString = element.getAttribute(TAG_PATH); String sourceAttachString = element.hasAttribute(TAG_SOURCEATTACHMENT) ? element.getAttribute(TAG_SOURCEATTACHMENT) : null; String sourceAttachRootString = element.hasAttribute(TAG_SOURCEATTACHMENTROOT) ? element.getAttribute(TAG_SOURCEATTACHMENTROOT) : null; IPath entryPath = null; IPath sourceAttachPath = null; IPath sourceAttachRootPath = null; if (version.equals(VERSION_ONE)) { entryPath = Path.fromOSString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromOSString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromOSString(sourceAttachRootString); } else { entryPath = Path.fromPortableString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromPortableString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromPortableString(sourceAttachRootString); } NodeList children = element.getElementsByTagName("*"); //$NON-NLS-1$ boolean[] foundChildren = new boolean[children.getLength()]; NodeList attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = ClasspathEntry.decodeExtraAttributes(attributeList); attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = ClasspathEntry.decodeAccessRules(attributeList); IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, sourceAttachPath, sourceAttachRootPath, accessRules, extraAttributes, false/*not exported*/); res.add(entry); } } } IClasspathEntry[] entries= (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]); return new UserLibrary(entries, isSystem); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static byte[] readByteTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } return bytes; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static long[] readLongTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if (length % 8 != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into longs long[] longs = new long[length / 8]; int i = 0; int longIndex = 0; while (true) { longs[longIndex++] = (((long) (bytes[i++] & 0xFF)) << 56) + (((long) (bytes[i++] & 0xFF)) << 48) + (((long) (bytes[i++] & 0xFF)) << 40) + (((long) (bytes[i++] & 0xFF)) << 32) + (((long) (bytes[i++] & 0xFF)) << 24) + (((long) (bytes[i++] & 0xFF)) << 16) + (((long) (bytes[i++] & 0xFF)) << 8) + (bytes[i++] & 0xFF); if (i == length) break; } return longs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static char[] readTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if ((length & 1) != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into chars char[] chars = new char[length / 2]; int i = 0; int charIndex = 0; while (true) { chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); if (i == length) break; } return chars; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static String buildAllDirectoriesInto(String outputPath, String relativeFileName) throws IOException { char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; File f; outputPath = outputPath.replace('/', fileSeparatorChar); // these could be optimized out if we normalized paths once and for // all relativeFileName = relativeFileName.replace('/', fileSeparatorChar); String outputDirPath, fileName; int separatorIndex = relativeFileName.lastIndexOf(fileSeparatorChar); if (separatorIndex == -1) { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath.substring(0, outputPath.length() - 1); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath; fileName = outputPath + fileSeparator + relativeFileName; } } else { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath + relativeFileName.substring(0, separatorIndex); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath + fileSeparator + relativeFileName.substring(0, separatorIndex); fileName = outputPath + fileSeparator + relativeFileName; } } f = new File(outputDirPath); f.mkdirs(); if (f.isDirectory()) { return fileName; } else { // the directory creation failed for some reason - retry using // a slower algorithm so as to refine the diagnostic if (outputPath.endsWith(fileSeparator)) { outputPath = outputPath.substring(0, outputPath.length() - 1); } f = new File(outputPath); boolean checkFileType = false; if (f.exists()) { checkFileType = true; // pre-existed } else { // we have to create that directory if (!f.mkdirs()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValidAll, f.getAbsolutePath())); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } StringBuffer outDir = new StringBuffer(outputPath); outDir.append(fileSeparator); StringTokenizer tokenizer = new StringTokenizer(relativeFileName, fileSeparator); String token = tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { f = new File(outDir.append(token).append(fileSeparator).toString()); checkFileType = false; // reset if (f.exists()) { checkFileType = true; // this is suboptimal, but it catches corner cases // in which a regular file pre-exists } else { // we have to create that directory if (!f.mkdir()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValid, outDir.substring(outputPath.length() + 1, outDir.length() - 1), outputPath)); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } token = tokenizer.nextToken(); } // token contains the last one return outDir.append(token).toString(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { InputStream stream = null; try { InputStream inputStream = zip.getInputStream(ze); if (inputStream == null) throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ stream = new BufferedInputStream(inputStream); return getInputStreamAsByteArray(stream, (int) ze.getSize()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
4
            
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
131
            
// in scripts/GenerateBuildScript.java
private static void dumpAllProperties(Writer writer, File sourceDir, ArrayList collector, String gcj_exe, String dest_dir) throws IOException { writer.write(" <echo message=\"compiling resources -> .o\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ for (int i = 0, max = collector.size(); i < max; i++) { String absolutePath = (String) collector.get(i); String fileName = absolutePath.substring(sourceDir.getAbsolutePath().length() + 1); writer.write(MessageFormat.format(" <exec dir=\"{1}\" executable=\"$'{'gcc-path'}'/bin/{0}\">" + LINE_SEPARATOR, new Object[] { gcj_exe, dest_dir})); //$NON-NLS-1$ writer.write(" <arg line=\"--resource "); //$NON-NLS-1$ writer.write(fileName + " " + fileName + " -c -o " + getObjectName(fileName) + "\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ writer.write(" </exec>" + LINE_SEPARATOR); //$NON-NLS-1$ } }
// in scripts/GenerateBuildScript.java
private static void dumpAllClassFiles(Writer writer, File sourceDir, ArrayList collector, String gcj_exe, String dest_dir) throws IOException { writer.write(" <echo message=\"compiling class files -> .o\"/>" + LINE_SEPARATOR); //$NON-NLS-1$ writer.write( MessageFormat.format( " <apply failonerror=\"true\" executable=\"$'{'gcc-path'}'/bin/{0}\" dest=\"{1}\" parallel=\"false\">" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"--verbose\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"--classpath={1}\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-O2\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-c\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-fassume-compiled\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-march=pentium4\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-mfpmath=sse\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <srcfile/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <arg value=\"-o\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <targetfile/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <fileset dir=\"{1}\" includes=\"**/*.class\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " <mapper type=\"glob\" from=\"*.class\" to=\"*.o\"/>" + LINE_SEPARATOR + //$NON-NLS-1$ " </apply>" + LINE_SEPARATOR + LINE_SEPARATOR,//$NON-NLS-1$ new Object[] { gcj_exe, dest_dir })); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
public void initialize() throws IOException { // nothing to do }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
public void initialize() throws IOException { if (this.zipFile == null) { this.zipFile = new ZipFile(this.file); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MultiTypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { if (this.simpleNames == null) { // if no simple names then return all possible ones from index return index.query(getIndexCategories(), null, -1); // match rule is irrelevant when the key is null } int count = -1; int numOfNames = this.simpleNames.length; EntryResult[][] allResults = numOfNames > 1 ? new EntryResult[numOfNames][] : null; for (int i = 0; i < numOfNames; i++) { char[] key = this.simpleNames[i]; int matchRule = getMatchRule(); switch(getMatchMode()) { case R_PREFIX_MATCH : // do a prefix query with the simpleName break; case R_EXACT_MATCH : // do a prefix query with the simpleName matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; key = CharOperation.append(key, SEPARATOR); break; case R_PATTERN_MATCH : if (key[key.length - 1] != '*') key = CharOperation.concat(key, ONE_STAR, SEPARATOR); break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the simpleName break; } EntryResult[] entries = index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null if (entries != null) { if (allResults == null) return entries; allResults[++count] = entries; } } if (count == -1) return null; int total = 0; for (int i = 0; i <= count; i++) total += allResults[i].length; EntryResult[] allEntries = new EntryResult[total]; int next = 0; for (int i = 0; i <= count; i++) { EntryResult[] entries = allResults[i]; System.arraycopy(entries, 0, allEntries, next, entries.length); next += entries.length; } return allEntries; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public static void findIndexMatches(SearchPattern pattern, Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { pattern.findIndexMatches(index, requestor, participant, scope, monitor); }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.selector; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_EXACT_MATCH : if (this.selector != null && this.parameterCount >= 0 && !this.varargs) key = createIndexKey(this.selector, this.parameterCount); else { // do a prefix query with the selector matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; } break; case R_PREFIX_MATCH : // do a prefix query with the selector break; case R_PATTERN_MATCH : if (this.parameterCount >= 0 && !this.varargs) key = createIndexKey(this.selector == null ? ONE_STAR : this.selector, this.parameterCount); else if (this.selector != null && this.selector[this.selector.length - 1] != '*') key = CharOperation.concat(this.selector, ONE_STAR, SEPARATOR); // else do a pattern query with just the selector break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the selector break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { return index.query(CATEGORIES, SECONDARY_PATTERN_KEY, R_PATTERN_MATCH | R_CASE_SENSITIVE); }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.superSimpleName; // can be null int matchRule = getMatchRule(); // cannot include the superQualification since it may not exist in the index switch(getMatchMode()) { case R_EXACT_MATCH : // do a prefix query with the superSimpleName matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; if (this.superSimpleName != null) key = CharOperation.append(this.superSimpleName, SEPARATOR); break; case R_PREFIX_MATCH : // do a prefix query with the superSimpleName break; case R_PATTERN_MATCH : // do a pattern query with the superSimpleName break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the superSimpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { // per construction, OR pattern can only be used with a PathCollector (which already gather results using a set) try { index.startQuery(); for (int i = 0, length = this.patterns.length; i < length; i++) this.patterns[i].findIndexMatches(index, requestor, participant, scope, progressMonitor); } finally { index.stopQuery(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.declaringSimpleName; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_EXACT_MATCH : if (this.declaringSimpleName != null && this.parameterCount >= 0 && !this.varargs) { key = createIndexKey(this.declaringSimpleName, this.parameterCount); } matchRule &= ~R_EXACT_MATCH; matchRule |= R_PREFIX_MATCH; break; case R_PREFIX_MATCH : // do a prefix query with the declaringSimpleName break; case R_PATTERN_MATCH : if (this.parameterCount >= 0 && !this.varargs) { key = CharOperation.concat(createIndexKey(this.declaringSimpleName == null ? ONE_STAR : this.declaringSimpleName, this.parameterCount), ONE_STAR); } else if (this.declaringSimpleName != null && this.declaringSimpleName[this.declaringSimpleName.length - 1] != '*') { key = CharOperation.concat(this.declaringSimpleName, ONE_STAR, SEPARATOR); } else if (key != null){ key = CharOperation.concat(key, ONE_STAR); } // else do a pattern query with just the declaringSimpleName break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the declaringSimpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java
public EntryResult[] queryIn(Index index) throws IOException { char[] key = this.simpleName; // can be null int matchRule = getMatchRule(); switch(getMatchMode()) { case R_PREFIX_MATCH : // do a prefix query with the simpleName break; case R_EXACT_MATCH : matchRule &= ~R_EXACT_MATCH; if (this.simpleName != null) { matchRule |= R_PREFIX_MATCH; key = this.pkg == null ? CharOperation.append(this.simpleName, SEPARATOR) : CharOperation.concat(this.simpleName, SEPARATOR, this.pkg, SEPARATOR, CharOperation.NO_CHAR); break; // do a prefix query with the simpleName and possibly the pkg } matchRule |= R_PATTERN_MATCH; // $FALL-THROUGH$ - fall thru to encode the key and do a pattern query case R_PATTERN_MATCH : if (this.pkg == null) { if (this.simpleName == null) { switch(this.typeSuffix) { case CLASS_SUFFIX : case INTERFACE_SUFFIX : case ENUM_SUFFIX : case ANNOTATION_TYPE_SUFFIX : case CLASS_AND_INTERFACE_SUFFIX : case CLASS_AND_ENUM_SUFFIX : case INTERFACE_AND_ANNOTATION_SUFFIX : // null key already returns all types // key = new char[] {ONE_STAR[0], SEPARATOR, ONE_STAR[0]}; break; } } else if (this.simpleName[this.simpleName.length - 1] != '*') { key = CharOperation.concat(this.simpleName, ONE_STAR, SEPARATOR); } break; // do a pattern query with the current encoded key } // must decode to check enclosingTypeNames due to the encoding of local types key = CharOperation.concat( this.simpleName == null ? ONE_STAR : this.simpleName, SEPARATOR, this.pkg, SEPARATOR, ONE_STAR); break; case R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; case R_CAMELCASE_MATCH: case R_CAMELCASE_SAME_PART_COUNT_MATCH: // do a prefix query with the simpleName break; } return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null }
// in search/org/eclipse/jdt/internal/core/search/matching/IntersectingPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); resetQuery(); SimpleSet intersectedNames = null; try { index.startQuery(); do { SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); SimpleSet newIntersectedNames = new SimpleSet(3); for (int i = 0, l = entries.length; i < l; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { String[] names = entry.getDocumentNames(index); if (intersectedNames != null) { for (int j = 0, n = names.length; j < n; j++) if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]); } else { for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]); } } } if (newIntersectedNames.elementSize == 0) return; intersectedNames = newIntersectedNames; } while (hasNextQuery()); } finally { index.stopQuery(); } String containerPath = index.containerPath; char separator = index.separator; Object[] names = intersectedNames.values; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) acceptMatch((String) names[i], containerPath, separator, null/*no pattern*/, requestor, participant, scope, progressMonitor); // AndPatterns cannot provide the decoded result }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
public void saveIndex(Index index) throws IOException { // must have permission to write from the write monitor if (index.hasChanged()) { if (VERBOSE) Util.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$ index.save(); } synchronized (this) { IPath containerPath = new Path(index.containerPath); if (this.jobEnd > this.jobStart) { for (int i = this.jobEnd; i > this.jobStart; i--) { // skip the current job IJob job = this.awaitingJobs[i]; if (job instanceof IndexRequest) if (((IndexRequest) job).containerPath.equals(containerPath)) return; } } IPath indexLocation = computeIndexLocation(containerPath); updateIndexState(indexLocation, SAVED_STATE); } }
// in search/org/eclipse/jdt/internal/core/index/EntryResult.java
public String[] getDocumentNames(Index index) throws java.io.IOException { if (this.documentTables != null) { int length = this.documentTables.length; if (length == 1 && this.documentNames == null) { // have a single table Object offset = this.documentTables[0]; int[] numbers = index.diskIndex.readDocumentNumbers(offset); String[] names = new String[numbers.length]; for (int i = 0, l = numbers.length; i < l; i++) names[i] = index.diskIndex.readDocumentName(numbers[i]); return names; } for (int i = 0; i < length; i++) { Object offset = this.documentTables[i]; int[] numbers = index.diskIndex.readDocumentNumbers(offset); for (int j = 0, k = numbers.length; j < k; j++) addDocumentName(index.diskIndex.readDocumentName(numbers[j])); } } if (this.documentNames == null) return CharOperation.NO_STRINGS; String[] names = new String[this.documentNames.elementSize]; int count = 0; Object[] values = this.documentNames.values; for (int i = 0, l = values.length; i < l; i++) if (values[i] != null) names[count++] = (String) values[i]; return names; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public EntryResult[] query(char[][] categories, char[] key, int matchRule) throws IOException { if (this.memoryIndex.shouldMerge() && this.monitor.exitReadEnterWrite()) { try { save(); } finally { this.monitor.exitWriteEnterRead(); } } HashtableOfObject results; int rule = matchRule & MATCH_RULE_INDEX_MASK; if (this.memoryIndex.hasChanged()) { results = this.diskIndex.addQueryResults(categories, key, rule, this.memoryIndex); results = this.memoryIndex.addQueryResults(categories, key, rule, results); } else { results = this.diskIndex.addQueryResults(categories, key, rule, null); } if (results == null) return null; EntryResult[] entryResults = new EntryResult[results.elementSize]; int count = 0; Object[] values = results.valueTable; for (int i = 0, l = values.length; i < l; i++) { EntryResult result = (EntryResult) values[i]; if (result != null) entryResults[count++] = result; } return entryResults; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public String[] queryDocumentNames(String substring) throws IOException { SimpleSet results; if (this.memoryIndex.hasChanged()) { results = this.diskIndex.addDocumentNames(substring, this.memoryIndex); this.memoryIndex.addDocumentNames(substring, results); } else { results = this.diskIndex.addDocumentNames(substring, null); } if (results.elementSize == 0) return null; String[] documentNames = new String[results.elementSize]; int count = 0; Object[] paths = results.values; for (int i = 0, l = paths.length; i < l; i++) if (paths[i] != null) documentNames[count++] = (String) paths[i]; return documentNames; }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public void reset() throws IOException { this.memoryIndex = new MemoryIndex(); this.diskIndex = new DiskIndex(this.diskIndex.indexFile.getCanonicalPath()); this.diskIndex.initialize(false/*do not reuse the index file*/); }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public void save() throws IOException { // must own the write lock of the monitor if (!hasChanged()) return; int numberOfChanges = this.memoryIndex.docsToReferences.elementSize; this.diskIndex.separator = this.separator; this.diskIndex = this.diskIndex.mergeWith(this.memoryIndex); this.memoryIndex = new MemoryIndex(); if (numberOfChanges > 1000) System.gc(); // reclaim space if the MemoryIndex was very BIG }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
SimpleSet addDocumentNames(String substring, MemoryIndex memoryIndex) throws IOException { // must skip over documents which have been added/changed/deleted in the memory index String[] docNames = readAllDocumentNames(); SimpleSet results = new SimpleSet(docNames.length); if (substring == null) { if (memoryIndex == null) { for (int i = 0, l = docNames.length; i < l; i++) results.add(docNames[i]); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; for (int i = 0, l = docNames.length; i < l; i++) { String docName = docNames[i]; if (!docsToRefs.containsKey(docName)) results.add(docName); } } } else { if (memoryIndex == null) { for (int i = 0, l = docNames.length; i < l; i++) if (docNames[i].startsWith(substring, 0)) results.add(docNames[i]); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; for (int i = 0, l = docNames.length; i < l; i++) { String docName = docNames[i]; if (docName.startsWith(substring, 0) && !docsToRefs.containsKey(docName)) results.add(docName); } } } return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private HashtableOfObject addQueryResult(HashtableOfObject results, char[] word, Object docs, MemoryIndex memoryIndex, boolean prevResults) throws IOException { // must skip over documents which have been added/changed/deleted in the memory index if (results == null) results = new HashtableOfObject(13); EntryResult result = prevResults ? (EntryResult) results.get(word) : null; if (memoryIndex == null) { if (result == null) results.putUnsafely(word, new EntryResult(word, docs)); else result.addDocumentTable(docs); } else { SimpleLookupTable docsToRefs = memoryIndex.docsToReferences; if (result == null) result = new EntryResult(word, null); int[] docNumbers = readDocumentNumbers(docs); for (int i = 0, l = docNumbers.length; i < l; i++) { String docName = readDocumentName(docNumbers[i]); if (!docsToRefs.containsKey(docName)) result.addDocumentName(docName); } if (!result.isEmpty()) results.put(word, result); } return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
HashtableOfObject addQueryResults(char[][] categories, char[] key, int matchRule, MemoryIndex memoryIndex) throws IOException { // assumes sender has called startQuery() & will call stopQuery() when finished if (this.categoryOffsets == null) return null; // file is empty HashtableOfObject results = null; // initialized if needed // No need to check the results table for duplicacy while processing the // first category table or if the first category tables doesn't have any results. boolean prevResults = false; if (key == null) { for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], true); // cache if key is null since its a definite match if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; if (results == null) results = new HashtableOfObject(wordsToDocNumbers.elementSize); for (int j = 0, m = words.length; j < m; j++) if (words[j] != null) results = addQueryResult(results, words[j], values[j], memoryIndex, prevResults); } prevResults = results != null; } if (results != null && this.cachedChunks == null) cacheDocumentNames(); } else { switch (matchRule) { case SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); Object value; if (wordsToDocNumbers != null && (value = wordsToDocNumbers.get(key)) != null) results = addQueryResult(results, key, value, memoryIndex, prevResults); prevResults = results != null; } break; case SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CASE_SENSITIVE: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; for (int j = 0, m = words.length; j < m; j++) { char[] word = words[j]; if (word != null && key[0] == word[0] && CharOperation.prefixEquals(key, word)) results = addQueryResult(results, word, values[j], memoryIndex, prevResults); } } prevResults = results != null; } break; default: for (int i = 0, l = categories.length; i < l; i++) { HashtableOfObject wordsToDocNumbers = readCategoryTable(categories[i], false); if (wordsToDocNumbers != null) { char[][] words = wordsToDocNumbers.keyTable; Object[] values = wordsToDocNumbers.valueTable; for (int j = 0, m = words.length; j < m; j++) { char[] word = words[j]; if (word != null && Index.isMatch(key, word, matchRule)) results = addQueryResult(results, word, values[j], memoryIndex, prevResults); } } prevResults = results != null; } } } if (results == null) return null; return results; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void cacheDocumentNames() throws IOException { // will need all document names so get them now this.cachedChunks = new String[this.numberOfChunks][]; FileInputStream stream = new FileInputStream(this.indexFile); try { if (this.numberOfChunks > 5) BUFFER_READ_SIZE <<= 1; int offset = this.chunkOffsets[0]; stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); for (int i = 0; i < this.numberOfChunks; i++) { int size = i == this.numberOfChunks - 1 ? this.sizeOfLastChunk : CHUNK_SIZE; readChunk(this.cachedChunks[i] = new String[size], stream, 0, size); } } catch (IOException e) { this.cachedChunks = null; throw e; } finally { stream.close(); this.streamBuffer = null; BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
void initialize(boolean reuseExistingFile) throws IOException { if (this.indexFile.exists()) { if (reuseExistingFile) { FileInputStream stream = new FileInputStream(this.indexFile); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, 128); try { char[] signature = readStreamChars(stream); if (!CharOperation.equals(signature, SIGNATURE_CHARS)) { throw new IOException(Messages.exception_wrongFormat); } this.headerInfoOffset = readStreamInt(stream); if (this.headerInfoOffset > 0) { // file is empty if its not set stream.skip(this.headerInfoOffset - this.bufferEnd); // assume that the header info offset is over current buffer end this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); readHeaderInfo(stream); } } finally { stream.close(); } return; } if (!this.indexFile.delete()) { if (DEBUG) System.out.println("initialize - Failed to delete index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index " + this.indexFile); //$NON-NLS-1$ } } if (this.indexFile.createNewFile()) { FileOutputStream stream = new FileOutputStream(this.indexFile, false); try { this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; writeStreamChars(stream, SIGNATURE_CHARS); writeStreamInt(stream, -1); // file is empty // write the buffer to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } } finally { stream.close(); } } else { if (DEBUG) System.out.println("initialize - Failed to create new index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create new index " + this.indexFile); //$NON-NLS-1$ } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException { if (newIndexFile.exists() && !newIndexFile.delete()) { // delete the temporary index file if (DEBUG) System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$ } else if (!newIndexFile.createNewFile()) { if (DEBUG) System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$ } int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.elementSize; this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); this.categoryTables = new HashtableOfObject(size); this.separator = diskIndex.separator; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void mergeCategories(DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException { // at this point, this.categoryTables contains the names -> wordsToDocs added in copyQueryResults() char[][] oldNames = onDisk.categoryOffsets.keyTable; for (int i = 0, l = oldNames.length; i < l; i++) { char[] oldName = oldNames[i]; if (oldName != null && !this.categoryTables.containsKey(oldName)) this.categoryTables.put(oldName, null); } char[][] categoryNames = this.categoryTables.keyTable; for (int i = 0, l = categoryNames.length; i < l; i++) if (categoryNames[i] != null) mergeCategory(categoryNames[i], onDisk, positions, stream); this.categoryTables = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void mergeCategory(char[] categoryName, DiskIndex onDisk, int[] positions, FileOutputStream stream) throws IOException { HashtableOfObject wordsToDocs = (HashtableOfObject) this.categoryTables.get(categoryName); if (wordsToDocs == null) wordsToDocs = new HashtableOfObject(3); HashtableOfObject oldWordsToDocs = onDisk.readCategoryTable(categoryName, true); if (oldWordsToDocs != null) { char[][] oldWords = oldWordsToDocs.keyTable; Object[] oldArrayOffsets = oldWordsToDocs.valueTable; nextWord: for (int i = 0, l = oldWords.length; i < l; i++) { char[] oldWord = oldWords[i]; if (oldWord != null) { int[] oldDocNumbers = (int[]) oldArrayOffsets[i]; int length = oldDocNumbers.length; int[] mappedNumbers = new int[length]; int count = 0; for (int j = 0; j < length; j++) { int pos = positions[oldDocNumbers[j]]; if (pos > RE_INDEXED) // forget any reference to a document which was deleted or re_indexed mappedNumbers[count++] = pos; } if (count < length) { if (count == 0) continue nextWord; // skip words which no longer have any references System.arraycopy(mappedNumbers, 0, mappedNumbers = new int[count], 0, count); } Object o = wordsToDocs.get(oldWord); if (o == null) { wordsToDocs.putUnsafely(oldWord, mappedNumbers); } else { IntList list = null; if (o instanceof IntList) { list = (IntList) o; } else { list = new IntList((int[]) o); wordsToDocs.put(oldWord, list); } for (int j = 0; j < count; j++) list.add(mappedNumbers[j]); } } } onDisk.categoryTables.put(categoryName, null); // flush cached table } writeCategoryTable(categoryName, wordsToDocs, stream); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
DiskIndex mergeWith(MemoryIndex memoryIndex) throws IOException { // assume write lock is held // compute & write out new docNames String[] docNames = readAllDocumentNames(); int previousLength = docNames.length; int[] positions = new int[previousLength]; // keeps track of the position of each document in the new sorted docNames SimpleLookupTable indexedDocuments = new SimpleLookupTable(3); // for each new/changed document in the memoryIndex docNames = computeDocumentNames(docNames, positions, indexedDocuments, memoryIndex); if (docNames.length == 0) { if (previousLength == 0) return this; // nothing to do... memory index contained deleted documents that had never been saved // index is now empty since all the saved documents were removed DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath()); newDiskIndex.initialize(false); return newDiskIndex; } DiskIndex newDiskIndex = new DiskIndex(this.indexFile.getPath() + ".tmp"); //$NON-NLS-1$ try { newDiskIndex.initializeFrom(this, newDiskIndex.indexFile); FileOutputStream stream = new FileOutputStream(newDiskIndex.indexFile, false); int offsetToHeader = -1; try { newDiskIndex.writeAllDocumentNames(docNames, stream); docNames = null; // free up the space // add each new/changed doc to empty category tables using its new position # if (indexedDocuments.elementSize > 0) { Object[] names = indexedDocuments.keyTable; Object[] integerPositions = indexedDocuments.valueTable; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) newDiskIndex.copyQueryResults( (HashtableOfObject) memoryIndex.docsToReferences.get(names[i]), ((Integer) integerPositions[i]).intValue()); } indexedDocuments = null; // free up the space // merge each category table with the new ones & write them out if (previousLength == 0) newDiskIndex.writeCategories(stream); else newDiskIndex.mergeCategories(this, positions, stream); offsetToHeader = newDiskIndex.streamEnd; newDiskIndex.writeHeaderInfo(stream); positions = null; // free up the space } finally { stream.close(); this.streamBuffer = null; } newDiskIndex.writeOffsetToHeader(offsetToHeader); // rename file by deleting previous index file & renaming temp one if (this.indexFile.exists() && !this.indexFile.delete()) { if (DEBUG) System.out.println("mergeWith - Failed to delete " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to delete index file " + this.indexFile); //$NON-NLS-1$ } if (!newDiskIndex.indexFile.renameTo(this.indexFile)) { if (DEBUG) System.out.println("mergeWith - Failed to rename " + this.indexFile); //$NON-NLS-1$ throw new IOException("Failed to rename index file " + this.indexFile); //$NON-NLS-1$ } } catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; } newDiskIndex.indexFile = this.indexFile; return newDiskIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private synchronized String[] readAllDocumentNames() throws IOException { if (this.numberOfChunks <= 0) return CharOperation.NO_STRINGS; FileInputStream stream = new FileInputStream(this.indexFile); try { int offset = this.chunkOffsets[0]; stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); int lastIndex = this.numberOfChunks - 1; String[] docNames = new String[lastIndex * CHUNK_SIZE + this.sizeOfLastChunk]; for (int i = 0; i < this.numberOfChunks; i++) readChunk(docNames, stream, i * CHUNK_SIZE, i < lastIndex ? CHUNK_SIZE : this.sizeOfLastChunk); return docNames; } finally { stream.close(); this.streamBuffer = null; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private synchronized HashtableOfObject readCategoryTable(char[] categoryName, boolean readDocNumbers) throws IOException { // result will be null if categoryName is unknown int offset = this.categoryOffsets.get(categoryName); if (offset == HashtableOfIntValues.NO_VALUE) { return null; } if (this.categoryTables == null) { this.categoryTables = new HashtableOfObject(3); } else { HashtableOfObject cachedTable = (HashtableOfObject) this.categoryTables.get(categoryName); if (cachedTable != null) { if (readDocNumbers) { // must cache remaining document number arrays Object[] arrayOffsets = cachedTable.valueTable; for (int i = 0, l = arrayOffsets.length; i < l; i++) if (arrayOffsets[i] instanceof Integer) arrayOffsets[i] = readDocumentNumbers(arrayOffsets[i]); } return cachedTable; } } FileInputStream stream = new FileInputStream(this.indexFile); HashtableOfObject categoryTable = null; char[][] matchingWords = null; int count = 0; int firstOffset = -1; this.streamBuffer = new byte[BUFFER_READ_SIZE]; try { stream.skip(offset); this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); int size = readStreamInt(stream); try { if (size < 0) { // DEBUG System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ } categoryTable = new HashtableOfObject(size); } catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; } int largeArraySize = 256; for (int i = 0; i < size; i++) { char[] word = readStreamChars(stream); int arrayOffset = readStreamInt(stream); // if arrayOffset is: // <= 0 then the array size == 1 with the value -> -arrayOffset // > 1 & < 256 then the size of the array is > 1 & < 256, the document array follows immediately // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table) if (arrayOffset <= 0) { categoryTable.putUnsafely(word, new int[] {-arrayOffset}); // store 1 element array by negating documentNumber } else if (arrayOffset < largeArraySize) { categoryTable.putUnsafely(word, readStreamDocumentArray(stream, arrayOffset)); // read in-lined array providing size } else { arrayOffset = readStreamInt(stream); // read actual offset if (readDocNumbers) { if (matchingWords == null) matchingWords = new char[size][]; if (count == 0) firstOffset = arrayOffset; matchingWords[count++] = word; } categoryTable.putUnsafely(word, new Integer(arrayOffset)); // offset to array in the file } } this.categoryTables.put(INTERNED_CATEGORY_NAMES.get(categoryName), categoryTable); // cache the table as long as its not too big // in practice, some tables can be greater than 500K when they contain more than 10K elements this.cachedCategoryName = categoryTable.elementSize < 20000 ? categoryName : null; } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { stream.close(); } if (matchingWords != null && count > 0) { stream = new FileInputStream(this.indexFile); try { stream.skip(firstOffset); this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); for (int i = 0; i < count; i++) { // each array follows the previous one categoryTable.put(matchingWords[i], readStreamDocumentArray(stream, readStreamInt(stream))); } } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { stream.close(); } } this.streamBuffer = null; return categoryTable; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readChunk(String[] docNames, FileInputStream stream, int index, int size) throws IOException { String current = new String(readStreamChars(stream)); docNames[index++] = current; for (int i = 1; i < size; i++) { if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int start = this.streamBuffer[this.bufferIndex++] & 0xFF; int end = this.streamBuffer[this.bufferIndex++] & 0xFF; String next = new String(readStreamChars(stream)); if (start > 0) { if (end > 0) { int length = current.length(); next = current.substring(0, start) + next + current.substring(length - end, length); } else { next = current.substring(0, start) + next; } } else if (end > 0) { int length = current.length(); next = next + current.substring(length - end, length); } docNames[index++] = next; current = next; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized int[] readDocumentNumbers(Object arrayOffset) throws IOException { // arrayOffset is either a cached array of docNumbers or an Integer offset in the file if (arrayOffset instanceof int[]) return (int[]) arrayOffset; FileInputStream stream = new FileInputStream(this.indexFile); try { int offset = ((Integer) arrayOffset).intValue(); stream.skip(offset); this.streamBuffer = new byte[BUFFER_READ_SIZE]; this.bufferIndex = 0; this.bufferEnd = stream.read(this.streamBuffer, 0, this.streamBuffer.length); return readStreamDocumentArray(stream, readStreamInt(stream)); } finally { stream.close(); this.streamBuffer = null; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readHeaderInfo(FileInputStream stream) throws IOException { // must be same order as writeHeaderInfo() this.numberOfChunks = readStreamInt(stream); this.sizeOfLastChunk = this.streamBuffer[this.bufferIndex++] & 0xFF; this.documentReferenceSize = this.streamBuffer[this.bufferIndex++] & 0xFF; this.separator = (char) (this.streamBuffer[this.bufferIndex++] & 0xFF); long fileLength = this.indexFile.length(); if (this.numberOfChunks > fileLength ) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } this.chunkOffsets = new int[this.numberOfChunks]; for (int i = 0; i < this.numberOfChunks; i++) this.chunkOffsets[i] = readStreamInt(stream); this.startOfCategoryTables = readStreamInt(stream); int size = readStreamInt(stream); this.categoryOffsets = new HashtableOfIntValues(size); this.categoryEnds = new HashtableOfIntValues(size); if (size > fileLength) { // not an accurate check, but good enough https://bugs.eclipse.org/bugs/show_bug.cgi?id=350612 if (DEBUG) System.out.println("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ throw new IOException("Index file is corrupted " + this.indexFile); //$NON-NLS-1$ } char[] previousCategory = null; int offset = -1; for (int i = 0; i < size; i++) { char[] categoryName = INTERNED_CATEGORY_NAMES.get(readStreamChars(stream)); offset = readStreamInt(stream); this.categoryOffsets.put(categoryName, offset); // cache offset to category table if (previousCategory != null) { this.categoryEnds.put(previousCategory, offset); // cache end of the category table } previousCategory = categoryName; } if (previousCategory != null) { this.categoryEnds.put(previousCategory, this.headerInfoOffset); // cache end of the category table } this.categoryTables = new HashtableOfObject(3); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void readStreamBuffer(FileInputStream stream) throws IOException { // if we're about to read a known amount at the end of the existing buffer, but it does not completely fit // so we need to shift the remaining bytes to be read, and fill the buffer from the stream if (this.bufferEnd < this.streamBuffer.length) return; // we're at the end of the stream - nothing left to read int bytesInBuffer = this.bufferEnd - this.bufferIndex; if (bytesInBuffer > 0) System.arraycopy(this.streamBuffer, this.bufferIndex, this.streamBuffer, 0, bytesInBuffer); this.bufferEnd = bytesInBuffer + stream.read(this.streamBuffer, bytesInBuffer, this.bufferIndex); this.bufferIndex = 0; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private char[] readStreamChars(FileInputStream stream) throws IOException { // read chars array length if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int length = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; length += this.streamBuffer[this.bufferIndex++] & 0xFF; // fill the chars from bytes buffer char[] word = new char[length]; int i = 0; while (i < length) { // how many characters can be decoded without refilling the buffer? int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3); // all the characters must already be in the buffer if we're at the end of the stream if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null) charsInBuffer = length; while (i < charsInBuffer) { byte b = this.streamBuffer[this.bufferIndex++]; switch (b & 0xF0) { case 0x00 : case 0x10 : case 0x20 : case 0x30 : case 0x40 : case 0x50 : case 0x60 : case 0x70 : word[i++]= (char) b; break; case 0xC0 : case 0xD0 : char next = (char) this.streamBuffer[this.bufferIndex++]; if ((next & 0xC0) != 0x80) { throw new UTFDataFormatException(); } char ch = (char) ((b & 0x1F) << 6); ch |= next & 0x3F; word[i++] = ch; break; case 0xE0 : char first = (char) this.streamBuffer[this.bufferIndex++]; char second = (char) this.streamBuffer[this.bufferIndex++]; if ((first & second & 0xC0) != 0x80) { throw new UTFDataFormatException(); } ch = (char) ((b & 0x0F) << 12); ch |= ((first& 0x3F) << 6); ch |= second & 0x3F; word[i++] = ch; break; default: throw new UTFDataFormatException(); } } if (i < length && stream != null) readStreamBuffer(stream); } return word; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private int[] readStreamDocumentArray(FileInputStream stream, int arraySize) throws IOException { int[] indexes = new int[arraySize]; if (arraySize == 0) return indexes; int i = 0; switch (this.documentReferenceSize) { case 1 : while (i < arraySize) { // how many bytes without refilling the buffer? int bytesInBuffer = i + this.bufferEnd - this.bufferIndex; if (bytesInBuffer > arraySize) bytesInBuffer = arraySize; while (i < bytesInBuffer) { indexes[i++] = this.streamBuffer[this.bufferIndex++] & 0xFF; } if (i < arraySize && stream != null) readStreamBuffer(stream); } break; case 2 : while (i < arraySize) { // how many shorts without refilling the buffer? int shortsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 2); if (shortsInBuffer > arraySize) shortsInBuffer = arraySize; while (i < shortsInBuffer) { int val = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; indexes[i++] = val + (this.streamBuffer[this.bufferIndex++] & 0xFF); } if (i < arraySize && stream != null) readStreamBuffer(stream); } break; default : while (i < arraySize) { indexes[i++] = readStreamInt(stream); } break; } return indexes; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private int readStreamInt(FileInputStream stream) throws IOException { if (this.bufferIndex + 4 >= this.bufferEnd) { readStreamBuffer(stream); } int val = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 24; val += (this.streamBuffer[this.bufferIndex++] & 0xFF) << 16; val += (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; return val + (this.streamBuffer[this.bufferIndex++] & 0xFF); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeAllDocumentNames(String[] sortedDocNames, FileOutputStream stream) throws IOException { if (sortedDocNames.length == 0) throw new IllegalArgumentException(); // assume the file was just created by initializeFrom() this.streamBuffer = new byte[BUFFER_WRITE_SIZE]; this.bufferIndex = 0; this.streamEnd = 0; // in order, write: SIGNATURE & headerInfoOffset place holder, then each compressed chunk of document names writeStreamChars(stream, SIGNATURE_CHARS); this.headerInfoOffset = this.streamEnd; writeStreamInt(stream, -1); // will overwrite with correct value later int size = sortedDocNames.length; this.numberOfChunks = (size / CHUNK_SIZE) + 1; this.sizeOfLastChunk = size % CHUNK_SIZE; if (this.sizeOfLastChunk == 0) { this.numberOfChunks--; this.sizeOfLastChunk = CHUNK_SIZE; } this.documentReferenceSize = size <= 0x7F ? 1 : (size <= 0x7FFF ? 2 : 4); // number of bytes used to encode a reference this.chunkOffsets = new int[this.numberOfChunks]; int lastIndex = this.numberOfChunks - 1; for (int i = 0; i < this.numberOfChunks; i++) { this.chunkOffsets[i] = this.streamEnd; int chunkSize = i == lastIndex ? this.sizeOfLastChunk : CHUNK_SIZE; int chunkIndex = i * CHUNK_SIZE; String current = sortedDocNames[chunkIndex]; writeStreamChars(stream, current.toCharArray()); for (int j = 1; j < chunkSize; j++) { String next = sortedDocNames[chunkIndex + j]; int len1 = current.length(); int len2 = next.length(); int max = len1 < len2 ? len1 : len2; int start = 0; // number of identical characters at the beginning (also the index of first character that is different) while (current.charAt(start) == next.charAt(start)) { start++; if (max == start) break; // current is 'abba', next is 'abbab' } if (start > 255) start = 255; int end = 0; // number of identical characters at the end while (current.charAt(--len1) == next.charAt(--len2)) { end++; if (len2 == start) break; // current is 'abbba', next is 'abba' if (len1 == 0) break; // current is 'xabc', next is 'xyabc' } if (end > 255) end = 255; if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) start; this.streamBuffer[this.bufferIndex++] = (byte) end; this.streamEnd += 2; int last = next.length() - end; writeStreamChars(stream, (start < last ? CharOperation.subarray(next.toCharArray(), start, last) : CharOperation.NO_CHAR)); current = next; } } this.startOfCategoryTables = this.streamEnd + 1; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeCategories(FileOutputStream stream) throws IOException { char[][] categoryNames = this.categoryTables.keyTable; Object[] tables = this.categoryTables.valueTable; for (int i = 0, l = categoryNames.length; i < l; i++) if (categoryNames[i] != null) writeCategoryTable(categoryNames[i], (HashtableOfObject) tables[i], stream); this.categoryTables = null; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeCategoryTable(char[] categoryName, HashtableOfObject wordsToDocs, FileOutputStream stream) throws IOException { // the format of a category table is as follows: // any document number arrays with >= 256 elements are written before the table (the offset to each array is remembered) // then the number of word->int[] pairs in the table is written // for each word -> int[] pair, the word is written followed by: // an int <= 0 if the array size == 1 // an int > 1 & < 256 for the size of the array if its > 1 & < 256, the document array follows immediately // 256 if the array size >= 256 followed by another int which is the offset to the array (written prior to the table) int largeArraySize = 256; Object[] values = wordsToDocs.valueTable; for (int i = 0, l = values.length; i < l; i++) { Object o = values[i]; if (o != null) { if (o instanceof IntList) o = values[i] = ((IntList) values[i]).asArray(); int[] documentNumbers = (int[]) o; if (documentNumbers.length >= largeArraySize) { values[i] = new Integer(this.streamEnd); writeDocumentNumbers(documentNumbers, stream); } } } this.categoryOffsets.put(categoryName, this.streamEnd); // remember the offset to the start of the table this.categoryTables.put(categoryName, null); // flush cached table writeStreamInt(stream, wordsToDocs.elementSize); char[][] words = wordsToDocs.keyTable; for (int i = 0, l = words.length; i < l; i++) { Object o = values[i]; if (o != null) { writeStreamChars(stream, words[i]); if (o instanceof int[]) { int[] documentNumbers = (int[]) o; if (documentNumbers.length == 1) writeStreamInt(stream, -documentNumbers[0]); // store an array of 1 element by negating the documentNumber (can be zero) else writeDocumentNumbers(documentNumbers, stream); } else { writeStreamInt(stream, largeArraySize); // mark to identify that an offset follows writeStreamInt(stream, ((Integer) o).intValue()); // offset in the file of the array of document numbers } } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeDocumentNumbers(int[] documentNumbers, FileOutputStream stream) throws IOException { // must store length as a positive int to detect in-lined array of 1 element int length = documentNumbers.length; writeStreamInt(stream, length); Util.sort(documentNumbers); int start = 0; switch (this.documentReferenceSize) { case 1 : while ((this.bufferIndex + length - start) >= BUFFER_WRITE_SIZE) { // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part int bytesLeft = BUFFER_WRITE_SIZE - this.bufferIndex; for (int i=0; i < bytesLeft; i++) { this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } while (start < length) { this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } this.streamEnd += length; break; case 2 : while ((this.bufferIndex + ((length - start) * 2)) >= BUFFER_WRITE_SIZE) { // when documentNumbers is large, write BUFFER_WRITE_SIZE parts & fall thru to write the last part int shortsLeft = (BUFFER_WRITE_SIZE - this.bufferIndex) / 2; for (int i=0; i < shortsLeft; i++) { this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8); this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } while (start < length) { this.streamBuffer[this.bufferIndex++] = (byte) (documentNumbers[start] >> 8); this.streamBuffer[this.bufferIndex++] = (byte) documentNumbers[start++]; } this.streamEnd += length * 2; break; default : while (start < length) { writeStreamInt(stream, documentNumbers[start++]); } break; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeHeaderInfo(FileOutputStream stream) throws IOException { writeStreamInt(stream, this.numberOfChunks); if ((this.bufferIndex + 3) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) this.sizeOfLastChunk; this.streamBuffer[this.bufferIndex++] = (byte) this.documentReferenceSize; this.streamBuffer[this.bufferIndex++] = (byte) this.separator; this.streamEnd += 3; // apend the file with chunk offsets for (int i = 0; i < this.numberOfChunks; i++) { writeStreamInt(stream, this.chunkOffsets[i]); } writeStreamInt(stream, this.startOfCategoryTables); // append the file with the category offsets... # of name -> offset pairs, followed by each name & an offset to its word->doc# table writeStreamInt(stream, this.categoryOffsets.elementSize); char[][] categoryNames = this.categoryOffsets.keyTable; int[] offsets = this.categoryOffsets.valueTable; for (int i = 0, l = categoryNames.length; i < l; i++) { if (categoryNames[i] != null) { writeStreamChars(stream, categoryNames[i]); writeStreamInt(stream, offsets[i]); } } // ensure buffer is written to the stream if (this.bufferIndex > 0) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeOffsetToHeader(int offsetToHeader) throws IOException { if (offsetToHeader > 0) { RandomAccessFile file = new RandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$ try { file.seek(this.headerInfoOffset); // offset to position in header file.writeInt(offsetToHeader); this.headerInfoOffset = offsetToHeader; // update to reflect the correct offset } finally { file.close(); } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamChars(FileOutputStream stream, char[] array) throws IOException { if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } int length = array.length; this.streamBuffer[this.bufferIndex++] = (byte) ((length >>> 8) & 0xFF); // store chars array length instead of bytes this.streamBuffer[this.bufferIndex++] = (byte) (length & 0xFF); // this will allow to read it faster this.streamEnd += 2; // we're assuming that very few char[] are so large that we need to flush the buffer more than once, if at all int totalBytesNeeded = length * 3; if (totalBytesNeeded <= BUFFER_WRITE_SIZE) { if (this.bufferIndex + totalBytesNeeded > BUFFER_WRITE_SIZE) { // flush the buffer now to make sure there is room for the array stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } writeStreamChars(stream, array, 0, length); } else { int charsPerWrite = BUFFER_WRITE_SIZE / 3; int start = 0; while (start < length) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; int charsLeftToWrite = length - start; int end = start + (charsPerWrite < charsLeftToWrite ? charsPerWrite : charsLeftToWrite); writeStreamChars(stream, array, start, end); start = end; } } }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamChars(FileOutputStream stream, char[] array, int start, int end) throws IOException { // start can NOT be == end // must have checked that there is enough room for end - start * 3 bytes in the buffer int oldIndex = this.bufferIndex; while (start < end) { int ch = array[start++]; if ((ch & 0x007F) == ch) { this.streamBuffer[this.bufferIndex++] = (byte) ch; } else if ((ch & 0x07FF) == ch) { // first two bits are stored in first byte byte b = (byte) (ch >> 6); b &= 0x1F; b |= 0xC0; this.streamBuffer[this.bufferIndex++] = b; // last six bits are stored in second byte b = (byte) (ch & 0x3F); b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; } else { // first four bits are stored in first byte byte b = (byte) (ch >> 12); b &= 0x0F; b |= 0xE0; this.streamBuffer[this.bufferIndex++] = b; // six following bits are stored in second byte b = (byte) (ch >> 6); b &= 0x3F; b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; // last six bits are stored in third byte b = (byte) (ch & 0x3F); b |= 0x80; this.streamBuffer[this.bufferIndex++] = b; } } this.streamEnd += this.bufferIndex - oldIndex; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeStreamInt(FileOutputStream stream, int val) throws IOException { if ((this.bufferIndex + 4) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) (val >> 24); this.streamBuffer[this.bufferIndex++] = (byte) (val >> 16); this.streamBuffer[this.bufferIndex++] = (byte) (val >> 8); this.streamBuffer[this.bufferIndex++] = (byte) val; this.streamEnd += 4; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { index.startQuery(); SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); String containerPath = index.containerPath; char separator = index.separator; for (int i = 0, l = entries.length; i < l; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { // TODO (kent) some clients may not need the document names String[] names = entry.getDocumentNames(index); for (int j = 0, n = names.length; j < n; j++) acceptMatch(names[j], containerPath, separator, decodedResult, requestor, participant, scope, monitor); } } } finally { index.stopQuery(); } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public EntryResult[] queryIn(Index index) throws IOException { return index.query(getIndexCategories(), getIndexKey(), getMatchRule()); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
private IBinaryType getJarBinaryTypeInfo(PackageFragment pkg, boolean fullyInitialize) throws CoreException, IOException, ClassFormatException { JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent(); ZipFile zip = null; try { zip = root.getJar(); String entryName = Util.concatWith(pkg.names, getElementName(), '/'); ZipEntry ze = zip.getEntry(entryName); if (ze != null) { byte contents[] = org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); String fileName = root.getHandleIdentifier() + IDependent.JAR_FILE_ENTRY_SEPARATOR + entryName; return new ClassFileReader(contents, fileName.toCharArray(), fullyInitialize); } } finally { JavaModelManager.getJavaModelManager().closeZipFile(zip); } return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
void load() throws IOException { loadProjects(getJavaModel()); loadVariables(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IAccessRule loadAccessRule() throws IOException { int problemId = loadInt(); IPath pattern = loadPath(); return new ClasspathAccessRule(pattern.toString().toCharArray(), problemId); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IAccessRule[] loadAccessRules() throws IOException { int count = loadInt(); if (count == 0) return ClasspathEntry.NO_ACCESS_RULES; IAccessRule[] rules = new IAccessRule[count]; for (int i = 0; i < count; ++i) rules[i] = loadAccessRule(); return rules; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathAttribute loadAttribute() throws IOException { String name = loadString(); String value = loadString(); return new ClasspathAttribute(name, value); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathAttribute[] loadAttributes() throws IOException { int count = loadInt(); if (count == 0) return ClasspathEntry.NO_EXTRA_ATTRIBUTES; IClasspathAttribute[] attributes = new IClasspathAttribute[count]; for (int i = 0; i < count; ++i) attributes[i] = loadAttribute(); return attributes; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private boolean loadBoolean() throws IOException { return this.in.readBoolean(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry[] loadClasspathEntries() throws IOException { int count = loadInt(); IClasspathEntry[] entries = new IClasspathEntry[count]; for (int i = 0; i < count; ++i) entries[i] = loadClasspathEntry(); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IClasspathEntry loadClasspathEntry() throws IOException { int id = loadInt(); if (id < 0 || id > this.allClasspathEntryCount) throw new IOException("Unexpected classpathentry id"); //$NON-NLS-1$ if (id < this.allClasspathEntryCount) return this.allClasspathEntries[id]; int contentKind = loadInt(); int entryKind = loadInt(); IPath path = loadPath(); IPath[] inclusionPatterns = loadPaths(); IPath[] exclusionPatterns = loadPaths(); IPath sourceAttachmentPath = loadPath(); IPath sourceAttachmentRootPath = loadPath(); IPath specificOutputLocation = loadPath(); boolean isExported = loadBoolean(); IAccessRule[] accessRules = loadAccessRules(); boolean combineAccessRules = loadBoolean(); IClasspathAttribute[] extraAttributes = loadAttributes(); IClasspathEntry entry = new ClasspathEntry(contentKind, entryKind, path, inclusionPatterns, exclusionPatterns, sourceAttachmentPath, sourceAttachmentRootPath, specificOutputLocation, isExported, accessRules, combineAccessRules, extraAttributes); IClasspathEntry[] array = this.allClasspathEntries; if (array == null || id == array.length) { array = new IClasspathEntry[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allClasspathEntries, 0, array, 0, id); this.allClasspathEntries = array; } array[id] = entry; this.allClasspathEntryCount = id + 1; return entry; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadContainers(IJavaProject project) throws IOException { boolean projectIsAccessible = project.getProject().isAccessible(); int count = loadInt(); for (int i = 0; i < count; ++i) { IPath path = loadPath(); IClasspathEntry[] entries = loadClasspathEntries(); if (!projectIsAccessible) // avoid leaking deleted project's persisted container, // but still read the container as it is is part of the file format continue; IClasspathContainer container = new PersistedClasspathContainer(project, path, entries); containerPut(project, path, container); Map oldContainers = (Map) JavaModelManager.this.previousSessionContainers.get(project); if (oldContainers == null) { oldContainers = new HashMap(); JavaModelManager.this.previousSessionContainers.put(project, oldContainers); } oldContainers.put(path, container); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private int loadInt() throws IOException { return this.in.readInt(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IPath loadPath() throws IOException { if (loadBoolean()) return null; String portableString = loadString(); IPath path = (IPath) this.allPaths.get(portableString); if (path == null) { path = Path.fromPortableString(portableString); this.allPaths.put(portableString, path); } return path; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private IPath[] loadPaths() throws IOException { int count = loadInt(); IPath[] pathArray = new IPath[count]; for (int i = 0; i < count; ++i) pathArray[i] = loadPath(); return pathArray; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadProjects(IJavaModel model) throws IOException { int count = loadInt(); for (int i = 0; i < count; ++i) { String projectName = loadString(); loadContainers(model.getJavaProject(projectName)); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private String loadString() throws IOException { int id = loadInt(); if (id < 0 || id > this.allStringsCount) throw new IOException("Unexpected string id"); //$NON-NLS-1$ if (id < this.allStringsCount) return this.allStrings[id]; String string = this.in.readUTF(); String[] array = this.allStrings; if (array == null || id == array.length) { array = new String[id + ARRAY_INCREMENT]; if (id != 0) System.arraycopy(this.allStrings, 0, array, 0, id); this.allStrings = array; } array[id] = string; this.allStringsCount = id + 1; return string; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void loadVariables() throws IOException { int size = loadInt(); Map loadedVars = new HashMap(size); for (int i = 0; i < size; ++i) { String varName = loadString(); IPath varPath = loadPath(); if (varPath != null) loadedVars.put(varName, varPath); } JavaModelManager.this.previousSessionVariables.putAll(loadedVars); JavaModelManager.this.variables.putAll(loadedVars); }
// 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 saveAccessRule(ClasspathAccessRule rule) throws IOException { saveInt(rule.problemId); savePath(rule.getPattern()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAccessRules(IAccessRule[] rules) throws IOException { int count = rules == null ? 0 : rules.length; saveInt(count); for (int i = 0; i < count; ++i) saveAccessRule((ClasspathAccessRule) rules[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAttribute(IClasspathAttribute attribute) throws IOException { saveString(attribute.getName()); saveString(attribute.getValue()); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveAttributes(IClasspathAttribute[] attributes) throws IOException { int count = attributes == null ? 0 : attributes.length; saveInt(count); for (int i = 0; i < count; ++i) saveAttribute(attributes[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathEntries(IClasspathEntry[] entries) throws IOException { int count = entries == null ? 0 : entries.length; saveInt(count); for (int i = 0; i < count; ++i) saveClasspathEntry(entries[i]); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveClasspathEntry(IClasspathEntry entry) throws IOException { if (saveNewId(entry, this.classpathEntryIds)) { saveInt(entry.getContentKind()); saveInt(entry.getEntryKind()); savePath(entry.getPath()); savePaths(entry.getInclusionPatterns()); savePaths(entry.getExclusionPatterns()); savePath(entry.getSourceAttachmentPath()); savePath(entry.getSourceAttachmentRootPath()); savePath(entry.getOutputLocation()); this.out.writeBoolean(entry.isExported()); saveAccessRules(entry.getAccessRules()); this.out.writeBoolean(entry.combineAccessRules()); saveAttributes(entry.getExtraAttributes()); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveContainers(IJavaProject project, Map containerMap) throws IOException { saveInt(containerMap.size()); for (Iterator i = containerMap.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); IPath path = (IPath) entry.getKey(); IClasspathContainer container = (IClasspathContainer) entry.getValue(); IClasspathEntry[] cpEntries = null; if (container == null) { // container has not been initialized yet, use previous // session value // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=73969) container = getPreviousSessionContainer(path, project); } if (container != null) cpEntries = container.getClasspathEntries(); savePath(path); saveClasspathEntries(cpEntries); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveInt(int value) throws IOException { this.out.writeInt(value); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private boolean saveNewId(Object key, HashtableOfObjectToInt map) throws IOException { int id = map.get(key); if (id == -1) { int newId = map.size(); map.put(key, newId); saveInt(newId); return true; } else { saveInt(id); return false; } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void savePath(IPath path) throws IOException { if (path == null) { this.out.writeBoolean(true); } else { this.out.writeBoolean(false); saveString(path.toPortableString()); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void savePaths(IPath[] paths) throws IOException { int count = paths == null ? 0 : paths.length; saveInt(count); for (int i = 0; i < count; ++i) savePath(paths[i]); }
// 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
private void saveString(String string) throws IOException { if (saveNewId(string, this.stringIds)) this.out.writeUTF(string); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
private void saveVariables(Map map) throws IOException { saveInt(map.size()); for (Iterator i = map.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); String varName = (String) entry.getKey(); IPath varPath = (IPath) entry.getValue(); saveString(varName); savePath(varPath); } }
// in model/org/eclipse/jdt/internal/core/builder/State.java
static State read(IProject project, DataInputStream in) throws IOException { if (JavaBuilder.DEBUG) System.out.println("About to read state " + project.getName()); //$NON-NLS-1$ if (VERSION != in.readByte()) { if (JavaBuilder.DEBUG) System.out.println("Found non-compatible state version... answered null for " + project.getName()); //$NON-NLS-1$ return null; } State newState = new State(); newState.javaProjectName = in.readUTF(); if (!project.getName().equals(newState.javaProjectName)) { if (JavaBuilder.DEBUG) System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$ return null; } newState.buildNumber = in.readInt(); newState.lastStructuralBuildTime = in.readLong(); int length = in.readInt(); newState.sourceLocations = new ClasspathMultiDirectory[length]; for (int i = 0; i < length; i++) { IContainer sourceFolder = project, outputFolder = project; String folderName; if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName); if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName); ClasspathMultiDirectory md = (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in), readNames(in)); if (in.readBoolean()) md.hasIndependentOutputFolder = true; newState.sourceLocations[i] = md; } length = in.readInt(); newState.binaryLocations = new ClasspathLocation[length]; IWorkspaceRoot root = project.getWorkspace().getRoot(); for (int i = 0; i < length; i++) { switch (in.readByte()) { case SOURCE_FOLDER : newState.binaryLocations[i] = newState.sourceLocations[in.readInt()]; break; case BINARY_FOLDER : IPath path = new Path(in.readUTF()); IContainer outputFolder = path.segmentCount() == 1 ? (IContainer) root.getProject(path.toString()) : (IContainer) root.getFolder(path); newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean(), readRestriction(in)); break; case EXTERNAL_JAR : newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF(), in.readLong(), readRestriction(in)); break; case INTERNAL_JAR : newState.binaryLocations[i] = ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF())), readRestriction(in)); } } newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong())); String[] internedTypeLocators = new String[length = in.readInt()]; for (int i = 0; i < length; i++) internedTypeLocators[i] = in.readUTF(); newState.typeLocators = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) newState.recordLocatorForType(in.readUTF(), internedTypeLocators[in.readInt()]); char[][] internedRootNames = ReferenceCollection.internSimpleNames(readNames(in), false); char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false); char[][][] internedQualifiedNames = new char[length = in.readInt()][][]; for (int i = 0; i < length; i++) { int qLength = in.readInt(); char[][] qName = new char[qLength][]; for (int j = 0; j < qLength; j++) qName[j] = internedSimpleNames[in.readInt()]; internedQualifiedNames[i] = qName; } internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames, false); newState.references = new SimpleLookupTable(length = in.readInt()); for (int i = 0; i < length; i++) { String typeLocator = internedTypeLocators[in.readInt()]; ReferenceCollection collection = null; switch (in.readByte()) { case 1 : char[][] additionalTypeNames = readNames(in); char[][][] qualifiedNames = new char[in.readInt()][][]; for (int j = 0, m = qualifiedNames.length; j < m; j++) qualifiedNames[j] = internedQualifiedNames[in.readInt()]; char[][] simpleNames = new char[in.readInt()][]; for (int j = 0, m = simpleNames.length; j < m; j++) simpleNames[j] = internedSimpleNames[in.readInt()]; char[][] rootNames = new char[in.readInt()][]; for (int j = 0, m = rootNames.length; j < m; j++) rootNames[j] = internedRootNames[in.readInt()]; collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames, rootNames); break; case 2 : char[][][] qNames = new char[in.readInt()][][]; for (int j = 0, m = qNames.length; j < m; j++) qNames[j] = internedQualifiedNames[in.readInt()]; char[][] sNames = new char[in.readInt()][]; for (int j = 0, m = sNames.length; j < m; j++) sNames[j] = internedSimpleNames[in.readInt()]; char[][] rNames = new char[in.readInt()][]; for (int j = 0, m = rNames.length; j < m; j++) rNames[j] = internedRootNames[in.readInt()]; collection = new ReferenceCollection(qNames, sNames, rNames); } newState.references.put(typeLocator, collection); } if (JavaBuilder.DEBUG) System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$ return newState; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static char[] readName(DataInputStream in) throws IOException { int nLength = in.readInt(); char[] name = new char[nLength]; for (int j = 0; j < nLength; j++) name[j] = in.readChar(); return name; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static char[][] readNames(DataInputStream in) throws IOException { int length = in.readInt(); char[][] names = new char[length][]; for (int i = 0; i < length; i++) names[i] = readName(in); return names; }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private static AccessRuleSet readRestriction(DataInputStream in) throws IOException { int length = in.readInt(); if (length == 0) return null; // no restriction specified AccessRule[] accessRules = new AccessRule[length]; for (int i = 0; i < length; i++) { char[] pattern = readName(in); int problemId = in.readInt(); accessRules[i] = new ClasspathAccessRule(pattern, problemId); } JavaModelManager manager = JavaModelManager.getJavaModelManager(); return new AccessRuleSet(accessRules, in.readByte(), manager.intern(in.readUTF())); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
void write(DataOutputStream out) throws IOException { int length; Object[] keyTable; Object[] valueTable; /* * byte VERSION * String project name * int build number * int last structural build number */ out.writeByte(VERSION); out.writeUTF(this.javaProjectName); out.writeInt(this.buildNumber); out.writeLong(this.lastStructuralBuildTime); /* * ClasspathMultiDirectory[] * int id * String path(s) */ out.writeInt(length = this.sourceLocations.length); for (int i = 0; i < length; i++) { ClasspathMultiDirectory md = this.sourceLocations[i]; out.writeUTF(md.sourceFolder.getProjectRelativePath().toString()); out.writeUTF(md.binaryFolder.getProjectRelativePath().toString()); writeNames(md.inclusionPatterns, out); writeNames(md.exclusionPatterns, out); out.writeBoolean(md.hasIndependentOutputFolder); } /* * ClasspathLocation[] * int id * String path(s) */ out.writeInt(length = this.binaryLocations.length); next : for (int i = 0; i < length; i++) { ClasspathLocation c = this.binaryLocations[i]; if (c instanceof ClasspathMultiDirectory) { out.writeByte(SOURCE_FOLDER); for (int j = 0, m = this.sourceLocations.length; j < m; j++) { if (this.sourceLocations[j] == c) { out.writeInt(j); continue next; } } } else if (c instanceof ClasspathDirectory) { out.writeByte(BINARY_FOLDER); ClasspathDirectory cd = (ClasspathDirectory) c; out.writeUTF(cd.binaryFolder.getFullPath().toString()); out.writeBoolean(cd.isOutputFolder); writeRestriction(cd.accessRuleSet, out); } else { ClasspathJar jar = (ClasspathJar) c; if (jar.resource == null) { out.writeByte(EXTERNAL_JAR); out.writeUTF(jar.zipFilename); out.writeLong(jar.lastModified()); } else { out.writeByte(INTERNAL_JAR); out.writeUTF(jar.resource.getFullPath().toString()); } writeRestriction(jar.accessRuleSet, out); } } /* * Structural build numbers table * String prereq project name * int last structural build number */ out.writeInt(length = this.structuralBuildTimes.elementSize); if (length > 0) { keyTable = this.structuralBuildTimes.keyTable; valueTable = this.structuralBuildTimes.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; out.writeUTF((String) keyTable[i]); out.writeLong(((Long) valueTable[i]).longValue()); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$ } /* * String[] Interned type locators */ out.writeInt(length = this.references.elementSize); SimpleLookupTable internedTypeLocators = new SimpleLookupTable(length); if (length > 0) { keyTable = this.references.keyTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; String key = (String) keyTable[i]; out.writeUTF(key); internedTypeLocators.put(key, new Integer(internedTypeLocators.elementSize)); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("references table is inconsistent"); //$NON-NLS-1$ } /* * Type locators table * String type name * int interned locator id */ out.writeInt(length = this.typeLocators.elementSize); if (length > 0) { keyTable = this.typeLocators.keyTable; valueTable = this.typeLocators.valueTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; out.writeUTF((String) keyTable[i]); Integer index = (Integer) internedTypeLocators.get(valueTable[i]); out.writeInt(index.intValue()); } } if (JavaBuilder.DEBUG && length != 0) System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$ } /* * char[][] Interned root names * char[][][] Interned qualified names * char[][] Interned simple names */ SimpleLookupTable internedRootNames = new SimpleLookupTable(3); SimpleLookupTable internedQualifiedNames = new SimpleLookupTable(31); SimpleLookupTable internedSimpleNames = new SimpleLookupTable(31); valueTable = this.references.valueTable; for (int i = 0, l = valueTable.length; i < l; i++) { if (valueTable[i] != null) { ReferenceCollection collection = (ReferenceCollection) valueTable[i]; char[][] rNames = collection.rootReferences; for (int j = 0, m = rNames.length; j < m; j++) { char[] rName = rNames[j]; if (!internedRootNames.containsKey(rName)) // remember the names have been interned internedRootNames.put(rName, new Integer(internedRootNames.elementSize)); } char[][][] qNames = collection.qualifiedNameReferences; for (int j = 0, m = qNames.length; j < m; j++) { char[][] qName = qNames[j]; if (!internedQualifiedNames.containsKey(qName)) { // remember the names have been interned internedQualifiedNames.put(qName, new Integer(internedQualifiedNames.elementSize)); for (int k = 0, n = qName.length; k < n; k++) { char[] sName = qName[k]; if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize)); } } } char[][] sNames = collection.simpleNameReferences; for (int j = 0, m = sNames.length; j < m; j++) { char[] sName = sNames[j]; if (!internedSimpleNames.containsKey(sName)) // remember the names have been interned internedSimpleNames.put(sName, new Integer(internedSimpleNames.elementSize)); } } } char[][] internedArray = new char[internedRootNames.elementSize][]; Object[] rootNames = internedRootNames.keyTable; Object[] positions = internedRootNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedArray[index] = (char[]) rootNames[i]; } } writeNames(internedArray, out); // now write the interned simple names internedArray = new char[internedSimpleNames.elementSize][]; Object[] simpleNames = internedSimpleNames.keyTable; positions = internedSimpleNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedArray[index] = (char[]) simpleNames[i]; } } writeNames(internedArray, out); // now write the interned qualified names as arrays of interned simple names char[][][] internedQArray = new char[internedQualifiedNames.elementSize][][]; Object[] qualifiedNames = internedQualifiedNames.keyTable; positions = internedQualifiedNames.valueTable; for (int i = positions.length; --i >= 0; ) { if (positions[i] != null) { int index = ((Integer) positions[i]).intValue(); internedQArray[index] = (char[][]) qualifiedNames[i]; } } out.writeInt(length = internedQArray.length); for (int i = 0; i < length; i++) { char[][] qName = internedQArray[i]; int qLength = qName.length; out.writeInt(qLength); for (int j = 0; j < qLength; j++) { Integer index = (Integer) internedSimpleNames.get(qName[j]); out.writeInt(index.intValue()); } } /* * References table * int interned locator id * ReferenceCollection */ out.writeInt(length = this.references.elementSize); if (length > 0) { keyTable = this.references.keyTable; for (int i = 0, l = keyTable.length; i < l; i++) { if (keyTable[i] != null) { length--; Integer index = (Integer) internedTypeLocators.get(keyTable[i]); out.writeInt(index.intValue()); ReferenceCollection collection = (ReferenceCollection) valueTable[i]; if (collection instanceof AdditionalTypeCollection) { out.writeByte(1); AdditionalTypeCollection atc = (AdditionalTypeCollection) collection; writeNames(atc.definedTypeNames, out); } else { out.writeByte(2); } char[][][] qNames = collection.qualifiedNameReferences; int qLength = qNames.length; out.writeInt(qLength); for (int j = 0; j < qLength; j++) { index = (Integer) internedQualifiedNames.get(qNames[j]); out.writeInt(index.intValue()); } char[][] sNames = collection.simpleNameReferences; int sLength = sNames.length; out.writeInt(sLength); for (int j = 0; j < sLength; j++) { index = (Integer) internedSimpleNames.get(sNames[j]); out.writeInt(index.intValue()); } char[][] rNames = collection.rootReferences; int rLength = rNames.length; out.writeInt(rLength); for (int j = 0; j < rLength; j++) { index = (Integer) internedRootNames.get(rNames[j]); out.writeInt(index.intValue()); } } } if (JavaBuilder.DEBUG && length != 0) System.out.println("references table is inconsistent"); //$NON-NLS-1$ } }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeName(char[] name, DataOutputStream out) throws IOException { int nLength = name.length; out.writeInt(nLength); for (int j = 0; j < nLength; j++) out.writeChar(name[j]); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeNames(char[][] names, DataOutputStream out) throws IOException { int length = names == null ? 0 : names.length; out.writeInt(length); for (int i = 0; i < length; i++) writeName(names[i], out); }
// in model/org/eclipse/jdt/internal/core/builder/State.java
private void writeRestriction(AccessRuleSet accessRuleSet, DataOutputStream out) throws IOException { if (accessRuleSet == null) { out.writeInt(0); } else { AccessRule[] accessRules = accessRuleSet.getAccessRules(); int length = accessRules.length; out.writeInt(length); if (length != 0) { for (int i = 0; i < length; i++) { AccessRule accessRule = accessRules[i]; writeName(accessRule.pattern, out); out.writeInt(accessRule.problemId); } out.writeByte(accessRuleSet.classpathEntryType); out.writeUTF(accessRuleSet.classpathEntryName); } } }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
public static State readState(IProject project, DataInputStream in) throws IOException { return State.read(project, in); }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
public static void writeState(Object state, DataOutputStream out) throws IOException { ((State) state).write(out); }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static String serialize(IClasspathEntry[] entries, boolean isSystemLibrary) throws IOException { ByteArrayOutputStream s = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$ XMLWriter xmlWriter = new XMLWriter(writer, null/*use the workspace line delimiter*/, true/*print XML version*/); HashMap library = new HashMap(); library.put(TAG_VERSION, String.valueOf(CURRENT_VERSION)); library.put(TAG_SYSTEMLIBRARY, String.valueOf(isSystemLibrary)); xmlWriter.printTag(TAG_USERLIBRARY, library, true, true, false); for (int i = 0, length = entries.length; i < length; ++i) { ClasspathEntry cpEntry = (ClasspathEntry) entries[i]; HashMap archive = new HashMap(); archive.put(TAG_PATH, cpEntry.getPath().toPortableString()); IPath sourceAttach= cpEntry.getSourceAttachmentPath(); if (sourceAttach != null) archive.put(TAG_SOURCEATTACHMENT, sourceAttach.toPortableString()); IPath sourceAttachRoot= cpEntry.getSourceAttachmentRootPath(); if (sourceAttachRoot != null) archive.put(TAG_SOURCEATTACHMENTROOT, sourceAttachRoot.toPortableString()); boolean hasExtraAttributes = cpEntry.extraAttributes != null && cpEntry.extraAttributes.length != 0; boolean hasRestrictions = cpEntry.getAccessRuleSet() != null; // access rule set is null if no access rules xmlWriter.printTag(TAG_ARCHIVE, archive, true, true, !(hasExtraAttributes || hasRestrictions)); // write extra attributes if necessary if (hasExtraAttributes) { cpEntry.encodeExtraAttributes(xmlWriter, true, true); } // write extra attributes and restriction if necessary if (hasRestrictions) { cpEntry.encodeAccessRules(xmlWriter, true, true); } // write archive end tag if necessary if (hasExtraAttributes || hasRestrictions) { xmlWriter.endTag(TAG_ARCHIVE, true/*insert tab*/, true/*insert new line*/); } } xmlWriter.endTag(TAG_USERLIBRARY, true/*insert tab*/, true/*insert new line*/); writer.flush(); writer.close(); return s.toString("UTF8");//$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
public static UserLibrary createFromString(Reader reader) throws IOException { Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase(TAG_USERLIBRARY)) { throw new IOException(Messages.file_badFormat); } String version= cpElement.getAttribute(TAG_VERSION); boolean isSystem= Boolean.valueOf(cpElement.getAttribute(TAG_SYSTEMLIBRARY)).booleanValue(); NodeList list= cpElement.getChildNodes(); int length = list.getLength(); ArrayList res= new ArrayList(length); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element= (Element) node; if (element.getNodeName().equals(TAG_ARCHIVE)) { String pathString = element.getAttribute(TAG_PATH); String sourceAttachString = element.hasAttribute(TAG_SOURCEATTACHMENT) ? element.getAttribute(TAG_SOURCEATTACHMENT) : null; String sourceAttachRootString = element.hasAttribute(TAG_SOURCEATTACHMENTROOT) ? element.getAttribute(TAG_SOURCEATTACHMENTROOT) : null; IPath entryPath = null; IPath sourceAttachPath = null; IPath sourceAttachRootPath = null; if (version.equals(VERSION_ONE)) { entryPath = Path.fromOSString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromOSString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromOSString(sourceAttachRootString); } else { entryPath = Path.fromPortableString(pathString); if (sourceAttachString != null) sourceAttachPath = Path.fromPortableString(sourceAttachString); if (sourceAttachRootString != null) sourceAttachRootPath = Path.fromPortableString(sourceAttachRootString); } NodeList children = element.getElementsByTagName("*"); //$NON-NLS-1$ boolean[] foundChildren = new boolean[children.getLength()]; NodeList attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ATTRIBUTES, children, foundChildren); IClasspathAttribute[] extraAttributes = ClasspathEntry.decodeExtraAttributes(attributeList); attributeList = ClasspathEntry.getChildAttributes(ClasspathEntry.TAG_ACCESS_RULES, children, foundChildren); IAccessRule[] accessRules = ClasspathEntry.decodeAccessRules(attributeList); IClasspathEntry entry = JavaCore.newLibraryEntry(entryPath, sourceAttachPath, sourceAttachRootPath, accessRules, extraAttributes, false/*not exported*/); res.add(entry); } } } IClasspathEntry[] entries= (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]); return new UserLibrary(entries, isSystem); }
// 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/util/Util.java
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(); } }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] decodeClasspath(String xmlClasspath, Map unknownElements) throws IOException, ClasspathEntry.AssertionFailedException { ArrayList paths = new ArrayList(); IClasspathEntry defaultOutput = null; StringReader reader = new StringReader(xmlClasspath); Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); cpElement = parser.parse(new InputSource(reader)).getDocumentElement(); } catch (SAXException e) { throw new IOException(Messages.file_badFormat); } catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); } finally { reader.close(); } if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) { //$NON-NLS-1$ throw new IOException(Messages.file_badFormat); } NodeList list = cpElement.getElementsByTagName(ClasspathEntry.TAG_CLASSPATHENTRY); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) { defaultOutput = entry; // separate output } else { paths.add(entry); } } } } int pathSize = paths.size(); IClasspathEntry[][] entries = new IClasspathEntry[2][]; entries[0] = new IClasspathEntry[pathSize + (defaultOutput == null ? 0 : 1)]; paths.toArray(entries[0]); if (defaultOutput != null) entries[0][pathSize] = defaultOutput; // ensure output is last item paths.clear(); list = cpElement.getElementsByTagName(ClasspathEntry.TAG_REFERENCED_ENTRY); length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { IClasspathEntry entry = ClasspathEntry.elementDecode((Element)node, this, unknownElements); if (entry != null){ paths.add(entry); } } } entries[1] = new IClasspathEntry[paths.size()]; paths.toArray(entries[1]); return entries; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
public IClasspathEntry[][] readFileEntriesWithException(Map unknownElements) throws CoreException, IOException, ClasspathEntry.AssertionFailedException { IFile rscFile = this.project.getFile(JavaProject.CLASSPATH_FILENAME); byte[] bytes; if (rscFile.exists()) { bytes = Util.getResourceContentsAsByteArray(rscFile); } else { // when a project is imported, we get a first delta for the addition of the .project, but the .classpath is not accessible // so default to using java.io.File // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=96258 URI location = rscFile.getLocationURI(); if (location == null) throw new IOException("Cannot obtain a location URI for " + rscFile); //$NON-NLS-1$ File file = Util.toLocalFile(location, null/*no progress monitor available*/); if (file == null) throw new IOException("Unable to fetch file from " + location); //$NON-NLS-1$ try { bytes = org.eclipse.jdt.internal.compiler.util.Util.getFileByteContent(file); } catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; } } if (hasUTF8BOM(bytes)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=240034 int length = bytes.length-IContentDescription.BOM_UTF_8.length; System.arraycopy(bytes, IContentDescription.BOM_UTF_8.length, bytes = new byte[length], 0, length); } String xmlClasspath; try { xmlClasspath = new String(bytes, org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8 } catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); } return decodeClasspath(xmlClasspath, unknownElements); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/Java2HTMLEntityReader.java
protected String computeSubstitution(int c) throws IOException { StringBuffer buf = new StringBuffer(); // Accumulate *s into the buffer until we see something other than *. while (c == '*') { this.bits &= ~BEGIN_LINE; c = nextChar(); buf.append('*'); } if (c == -1) // Snippet must have ended with *s. Just return them. return buf.toString(); if (c == '/' && buf.length() > 0) { /* * Translate a * that precedes a / to &#42; so it isn't * misinterpreted as the end of the Javadoc comment that contains * the code we are formatting. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=109636 */ buf.setLength(buf.length() - 1); buf.append("&#42;/"); //$NON-NLS-1$ } else if (c == '@' && (this.bits & BEGIN_LINE) != 0) { /* * When @ is first on a line, translate it to &#064; so it isn't * misinterpreted as a Javadoc tag. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=197169 */ buf.append("&#064;"); //$NON-NLS-1$ } else { /* * Ordinary processing. If the character needs an entity in HTML, * add the entity, otherwise add the character. */ String entity = (String) fgEntityLookup.get(String.valueOf((char) c)); if (entity != null) buf.append(entity); else buf.append((char) c); } // Update bits for the benefit of the next character. if (c == '\n' || c == '\r') { this.bits |= BEGIN_LINE; } else if (!ScannerHelper.isWhitespace((char) c)) { this.bits &= ~BEGIN_LINE; } return buf.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public String getString() throws IOException { StringBuffer buf= new StringBuffer(); int ch; while ((ch= read()) != -1) { buf.append((char)ch); } return buf.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
protected int nextChar() throws IOException { this.fReadFromBuffer= (this.fBuffer.length() > 0); if (this.fReadFromBuffer) { char ch= this.fBuffer.charAt(this.fIndex++); if (this.fIndex >= this.fBuffer.length()) { this.fBuffer.setLength(0); this.fIndex= 0; } return ch; } else { int ch= this.fCharAfterWhiteSpace; if (ch == -1) { ch= this.fReader.read(); } if (this.fSkipWhiteSpace && ScannerHelper.isWhitespace((char)ch)) { do { ch= this.fReader.read(); } while (ScannerHelper.isWhitespace((char)ch)); if (ch != -1) { this.fCharAfterWhiteSpace= ch; return ' '; } } else { this.fCharAfterWhiteSpace= -1; } return ch; } }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public int read() throws IOException { int c; do { c= nextChar(); while (!this.fReadFromBuffer && c != -1) { String s= computeSubstitution(c); if (s == null) break; if (s.length() > 0) this.fBuffer.insert(0, s); c= nextChar(); } } while (this.fSkipWhiteSpace && this.fWasWhiteSpace && (c == ' ')); this.fWasWhiteSpace= (c == ' ' || c == '\r' || c == '\n'); return c; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public int read(char cbuf[], int off, int len) throws IOException { int end= off + len; for (int i= off; i < end; i++) { int ch= read(); if (ch == -1) { if (i == off) { return -1; } else { return i - off; } } cbuf[i]= (char)ch; } return len; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public boolean ready() throws IOException { return this.fReader.ready(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public void close() throws IOException { this.fReader.close(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/SubstitutionTextReader.java
public void reset() throws IOException { this.fReader.reset(); this.fWasWhiteSpace= true; this.fCharAfterWhiteSpace= -1; this.fBuffer.setLength(0); this.fIndex= 0; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
protected String computeSubstitution(int c) throws IOException { if (c == '&') return processEntity(); return null; }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
private String processEntity() throws IOException { StringBuffer buf= new StringBuffer(); int ch= nextChar(); while (ScannerHelper.isLetterOrDigit((char) ch) || ch == '#') { buf.append((char) ch); ch= nextChar(); } if (ch == ';') return entity2Text(buf.toString()); buf.insert(0, '&'); if (ch != -1) buf.append((char) ch); return buf.toString(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
public final static void initTables() throws java.io.IOException { final String prefix = FILEPREFIX; int i = 0; lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ char[] chars = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ check_table = new short[chars.length]; for (int c = chars.length; c-- > 0;) { check_table[c] = (short) (chars[c] - 32768); } asb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ asr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ nasb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ nasr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ non_terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ term_action = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_prefix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_suffix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_state_set = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_rhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_state = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ in_symb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ rhs = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ term_check = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ scope_la = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ name = readNameTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ rules_compliance = readLongTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ readableName = readReadableNameTable(READABLE_NAMES_FILE_NAME); reverse_index = computeReverseTable(terminal_index, non_terminal_index, name); recovery_templates_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ recovery_templates = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ statements_recovery_filter = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ base_action = lhs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static byte[] readByteTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } return bytes; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static long[] readLongTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if (length % 8 != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into longs long[] longs = new long[length / 8]; int i = 0; int longIndex = 0; while (true) { longs[longIndex++] = (((long) (bytes[i++] & 0xFF)) << 56) + (((long) (bytes[i++] & 0xFF)) << 48) + (((long) (bytes[i++] & 0xFF)) << 40) + (((long) (bytes[i++] & 0xFF)) << 32) + (((long) (bytes[i++] & 0xFF)) << 24) + (((long) (bytes[i++] & 0xFF)) << 16) + (((long) (bytes[i++] & 0xFF)) << 8) + (bytes[i++] & 0xFF); if (i == length) break; } return longs; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static String[] readNameTable(String filename) throws java.io.IOException { char[] contents = readTable(filename); char[][] nameAsChar = CharOperation.splitOn('\n', contents); String[] result = new String[nameAsChar.length + 1]; result[0] = null; for (int i = 0; i < nameAsChar.length; i++) { result[i + 1] = new String(nameAsChar[i]); } return result; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
protected static char[] readTable(String filename) throws java.io.IOException { //files are located at Parser.class directory InputStream stream = Parser.class.getResourceAsStream(filename); if (stream == null) { throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); } byte[] bytes = null; try { stream = new BufferedInputStream(stream); bytes = Util.getInputStreamAsByteArray(stream, -1); } finally { try { stream.close(); } catch (IOException e) { // ignore } } //minimal integrity check (even size expected) int length = bytes.length; if ((length & 1) != 0) throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); // convert bytes into chars char[] chars = new char[length / 2]; int i = 0; int charIndex = 0; while (true) { chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); if (i == length) break; } return chars; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file) throws ClassFormatException, IOException { return read(file, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(File file, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getFileByteContent(file); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, file.getAbsolutePath().toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName) throws ClassFormatException, IOException { return read(stream, fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(InputStream stream, String fileName, boolean fullyInitialize) throws ClassFormatException, IOException { byte classFileBytes[] = Util.getInputStreamAsByteArray(stream, -1); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, fileName.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename) throws ClassFormatException, java.io.IOException { return read(zip, filename, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read( java.util.zip.ZipFile zip, String filename, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { java.util.zip.ZipEntry ze = zip.getEntry(filename); if (ze == null) return null; byte classFileBytes[] = Util.getZipEntryByteContent(ze, zip); ClassFileReader classFileReader = new ClassFileReader(classFileBytes, filename.toCharArray()); if (fullyInitialize) { classFileReader.initialize(); } return classFileReader; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName) throws ClassFormatException, java.io.IOException { return read(fileName, false); }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
public static ClassFileReader read(String fileName, boolean fullyInitialize) throws ClassFormatException, java.io.IOException { return read(new File(fileName), fullyInitialize); }
// in compiler/org/eclipse/jdt/internal/compiler/util/ManifestAnalyzer.java
public boolean analyzeManifestContents(InputStream inputStream) throws IOException { char[] chars = Util.getInputStreamAsCharArray(inputStream, -1, Util.UTF_8); int state = START, substate = 0; StringBuffer currentJarToken = new StringBuffer(); int currentChar; this.classpathSectionsCount = 0; this.calledFilesNames = null; for (int i = 0, max = chars.length; i < max;) { currentChar = chars[i++]; if (currentChar == '\r') { // skip \r, will consider \n later (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=251079 ) if (i < max) { currentChar = chars[i++]; } } switch (state) { case START: if (currentChar == CLASSPATH_HEADER_TOKEN[0]) { state = IN_CLASSPATH_HEADER; substate = 1; } else { state = SKIP_LINE; } break; case IN_CLASSPATH_HEADER: if (currentChar == '\n') { state = START; } else if (currentChar != CLASSPATH_HEADER_TOKEN[substate++]) { state = SKIP_LINE; } else if (substate == CLASSPATH_HEADER_TOKEN.length) { state = PAST_CLASSPATH_HEADER; } break; case PAST_CLASSPATH_HEADER: if (currentChar == ' ') { state = SKIPPING_WHITESPACE; this.classpathSectionsCount++; } else { return false; } break; case SKIPPING_WHITESPACE: if (currentChar == '\n') { state = CONTINUING; } else if (currentChar != ' ') { currentJarToken.append((char) currentChar); state = READING_JAR; } else { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); } break; case CONTINUING: if (currentChar == '\n') { addCurrentTokenJarWhenNecessary(currentJarToken); state = START; } else if (currentChar == ' ') { state = SKIPPING_WHITESPACE; } else if (currentChar == CLASSPATH_HEADER_TOKEN[0]) { addCurrentTokenJarWhenNecessary(currentJarToken); state = IN_CLASSPATH_HEADER; substate = 1; } else if (this.calledFilesNames == null) { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); state = START; } else { // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); state = SKIP_LINE; } break; case SKIP_LINE: if (currentChar == '\n') { state = START; } break; case READING_JAR: if (currentChar == '\n') { // appends token below state = CONTINUING; // >>>>>>>>>>> Add a break to not add the jar yet as it can continue on the next line break; } else if (currentChar == ' ') { // appends token below state = SKIPPING_WHITESPACE; } else { currentJarToken.append((char) currentChar); break; } addCurrentTokenJarWhenNecessary(currentJarToken); break; } } switch (state) { case START: return true; case IN_CLASSPATH_HEADER: return true; case PAST_CLASSPATH_HEADER: return false; case SKIPPING_WHITESPACE: // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); return true; case CONTINUING: // >>>>>>>>>>>>>>>>>> Add the latest jar read addCurrentTokenJarWhenNecessary(currentJarToken); return true; case SKIP_LINE: if (this.classpathSectionsCount != 0) { if (this.calledFilesNames == null) { return false; } } return true; case READING_JAR: // >>>>>>>>>>>>>>>>>> Add the latest jar read return false; } return true; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static String buildAllDirectoriesInto(String outputPath, String relativeFileName) throws IOException { char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; File f; outputPath = outputPath.replace('/', fileSeparatorChar); // these could be optimized out if we normalized paths once and for // all relativeFileName = relativeFileName.replace('/', fileSeparatorChar); String outputDirPath, fileName; int separatorIndex = relativeFileName.lastIndexOf(fileSeparatorChar); if (separatorIndex == -1) { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath.substring(0, outputPath.length() - 1); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath; fileName = outputPath + fileSeparator + relativeFileName; } } else { if (outputPath.endsWith(fileSeparator)) { outputDirPath = outputPath + relativeFileName.substring(0, separatorIndex); fileName = outputPath + relativeFileName; } else { outputDirPath = outputPath + fileSeparator + relativeFileName.substring(0, separatorIndex); fileName = outputPath + fileSeparator + relativeFileName; } } f = new File(outputDirPath); f.mkdirs(); if (f.isDirectory()) { return fileName; } else { // the directory creation failed for some reason - retry using // a slower algorithm so as to refine the diagnostic if (outputPath.endsWith(fileSeparator)) { outputPath = outputPath.substring(0, outputPath.length() - 1); } f = new File(outputPath); boolean checkFileType = false; if (f.exists()) { checkFileType = true; // pre-existed } else { // we have to create that directory if (!f.mkdirs()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValidAll, f.getAbsolutePath())); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } StringBuffer outDir = new StringBuffer(outputPath); outDir.append(fileSeparator); StringTokenizer tokenizer = new StringTokenizer(relativeFileName, fileSeparator); String token = tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { f = new File(outDir.append(token).append(fileSeparator).toString()); checkFileType = false; // reset if (f.exists()) { checkFileType = true; // this is suboptimal, but it catches corner cases // in which a regular file pre-exists } else { // we have to create that directory if (!f.mkdir()) { if (f.exists()) { // someone else created f -- need to check its type checkFileType = true; } else { // no one could create f -- complain throw new IOException(Messages.bind( Messages.output_notValid, outDir.substring(outputPath.length() + 1, outDir.length() - 1), outputPath)); } } } if (checkFileType) { if (!f.isDirectory()) { throw new IOException(Messages.bind( Messages.output_isFile, f.getAbsolutePath())); } } token = tokenizer.nextToken(); } // token contains the last one return outDir.append(token).toString(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] bytesToChar(byte[] bytes, String encoding) throws IOException { return getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, encoding); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getFileByteContent(File file) throws IOException { InputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); return getInputStreamAsByteArray(stream, (int) file.length()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] getFileCharContent(File file, String encoding) throws IOException { InputStream stream = null; try { stream = new FileInputStream(file); return getInputStreamAsCharArray(stream, (int) file.length(), encoding); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
private static FileOutputStream getFileOutputStream(boolean generatePackagesStructure, String outputPath, String relativeFileName) throws IOException { if (generatePackagesStructure) { return new FileOutputStream(new File(buildAllDirectoriesInto(outputPath, relativeFileName))); } else { String fileName = null; char fileSeparatorChar = File.separatorChar; String fileSeparator = File.separator; // First we ensure that the outputPath exists outputPath = outputPath.replace('/', fileSeparatorChar); // To be able to pass the mkdirs() method we need to remove the extra file separator at the end of the outDir name int indexOfPackageSeparator = relativeFileName.lastIndexOf(fileSeparatorChar); if (indexOfPackageSeparator == -1) { if (outputPath.endsWith(fileSeparator)) { fileName = outputPath + relativeFileName; } else { fileName = outputPath + fileSeparator + relativeFileName; } } else { int length = relativeFileName.length(); if (outputPath.endsWith(fileSeparator)) { fileName = outputPath + relativeFileName.substring(indexOfPackageSeparator + 1, length); } else { fileName = outputPath + fileSeparator + relativeFileName.substring(indexOfPackageSeparator + 1, length); } } return new FileOutputStream(new File(fileName)); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException { byte[] contents; if (length == -1) { contents = new byte[0]; int contentsLength = 0; int amountRead = -1; do { int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (contentsLength + amountRequested > contents.length) { System.arraycopy( contents, 0, contents = new byte[contentsLength + amountRequested], 0, contentsLength); } // read as many bytes as possible amountRead = stream.read(contents, contentsLength, amountRequested); if (amountRead > 0) { // remember length of contents contentsLength += amountRead; } } while (amountRead != -1); // resize contents if necessary if (contentsLength < contents.length) { System.arraycopy( contents, 0, contents = new byte[contentsLength], 0, contentsLength); } } else { contents = new byte[length]; int len = 0; int readSize = 0; while ((readSize != -1) && (len != length)) { // See PR 1FMS89U // We record first the read size. In this case len is the actual read size. len += readSize; readSize = stream.read(contents, len, length - len); } } return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) throws IOException { BufferedReader reader = null; try { reader = encoding == null ? new BufferedReader(new InputStreamReader(stream)) : new BufferedReader(new InputStreamReader(stream, encoding)); } catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); } char[] contents; int totalRead = 0; if (length == -1) { contents = CharOperation.NO_CHAR; } else { // length is a good guess when the encoding produces less or the same amount of characters than the file length contents = new char[length]; // best guess } while (true) { int amountRequested; if (totalRead < length) { // until known length is met, reuse same array sized eagerly amountRequested = length - totalRead; } else { // reading beyond known length int current = reader.read(); if (current < 0) break; amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (totalRead + 1 + amountRequested > contents.length) System.arraycopy(contents, 0, contents = new char[totalRead + 1 + amountRequested], 0, totalRead); // add current character contents[totalRead++] = (char) current; // coming from totalRead==length } // read as many chars as possible int amountRead = reader.read(contents, totalRead, amountRequested); if (amountRead < 0) break; totalRead += amountRead; } // Do not keep first character for UTF-8 BOM encoding int start = 0; if (totalRead > 0 && UTF_8.equals(encoding)) { if (contents[0] == 0xFEFF) { // if BOM char then skip totalRead--; start = 1; } } // resize contents if necessary if (totalRead < contents.length) System.arraycopy(contents, start, contents = new char[totalRead], 0, totalRead); return contents; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static byte[] getZipEntryByteContent(ZipEntry ze, ZipFile zip) throws IOException { InputStream stream = null; try { InputStream inputStream = zip.getInputStream(ze); if (inputStream == null) throw new IOException("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$ stream = new BufferedInputStream(inputStream); return getInputStreamAsByteArray(stream, (int) ze.getSize()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // ignore } } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static void writeToDisk(boolean generatePackagesStructure, String outputPath, String relativeFileName, ClassFile classFile) throws IOException { FileOutputStream file = getFileOutputStream(generatePackagesStructure, outputPath, relativeFileName); /* use java.nio to write if (true) { FileChannel ch = file.getChannel(); try { ByteBuffer buffer = ByteBuffer.allocate(classFile.headerOffset + classFile.contentsOffset); buffer.put(classFile.header, 0, classFile.headerOffset); buffer.put(classFile.contents, 0, classFile.contentsOffset); buffer.flip(); while (true) { if (ch.write(buffer) == 0) break; } } finally { ch.close(); } return; } */ BufferedOutputStream output = new BufferedOutputStream(file, DEFAULT_WRITING_SIZE); // BufferedOutputStream output = new BufferedOutputStream(file); try { // if no IOException occured, output cannot be null output.write(classFile.header, 0, classFile.headerOffset); output.write(classFile.contents, 0, classFile.contentsOffset); output.flush(); } catch(IOException e) { throw e; } finally { output.close(); } }
156
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IOException e) { //ignore }
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
// in scripts/GenerateBuildScript.java
catch (IOException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (IOException e) { // should not happen as we know that the file exists this.path = directory.getAbsolutePath(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathDirectory.java
catch (IOException e) { // treat as if file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { return null; }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // best effort }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // treat as if class file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathJar.java
catch (IOException e) { // in case of error, simply return the absolute path this.path = this.file.getAbsolutePath(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/ClasspathSourceJar.java
catch (IOException e) { // treat as if source file is missing }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch (IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch(IOException exception) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/FileSystem.java
catch (IOException e) { // this should not happen as the file exists continue; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { // ignore; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { logNoClassFileCreated(outputPath, relativeFileName, e); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e1) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { // ignore }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IOException e) { this.logger.logNoClassFileCreated(currentDestinationPath, relativeStringName, e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (IOException e) { // cannot read class file: return null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/search/indexing/SaveIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to save index " + this.containerPath + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexBinaryFolder.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.folder + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // failed to read the existing file or its no longer compatible if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt if (VERBOSE) Util.verbose("-> cannot reuse existing index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ rebuildIndex(indexLocation, containerPath); return null; } /*index = null;*/ // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { if (VERBOSE) Util.verbose("-> unable to create empty index: "+indexLocationString+" path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ // The file could not be created. Possible reason: the project has been deleted. return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read javaLikeNames file"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to recreate index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // The file could not be created. Possible reason: the project has been deleted. if (VERBOSE) { Util.verbose("-> failed to reset index for path: "+containerPathString); //$NON-NLS-1$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(IOException e) { if (VERBOSE) { Util.verbose("-> got the following exception while saving:", System.err); //$NON-NLS-1$ e.printStackTrace(); } allSaved = false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read saved index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to read participant index file names"); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write javaLikeNames file", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write participant index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException ignored) { if (VERBOSE) Util.verbose("Failed to write saved index file names", System.err); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch (IOException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/RemoveFolderFromIndex.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } return false; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
catch (IOException e) { if (JobManager.VERBOSE) { Util.verbose("-> failed to index " + this.project + " because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } this.manager.removeIndex(this.containerPath); return false; }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
catch (IOException e) { if (e instanceof java.io.EOFException) e.printStackTrace(); return FAILED; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { this.cachedChunks = null; throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException e) { // leave info null }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // not a zip file if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) { Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$ e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (IOException e) { // best effort }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // problem occured closing zip file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { classpath = new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; if (Messages.file_badFormat.equals(e.getMessage())) status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_xmlFormatError, javaProject.getElementName(), Messages.file_badFormat)); else status = new JavaModelStatus( IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT, Messages.bind(Messages.classpath_cannotReadClasspathFile, javaProject.getElementName())); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // problem occured closing zip file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (cacheFile.exists()) Util.log(e, "Unable to read non-chaining jar cache file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(IOException e){ // problem loading xml file: nothing we can do }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { Util.log(e, "Could not recreate persisted container: \n" + containerString); //$NON-NLS-1$ entries = JavaProject.INVALID_CLASSPATH; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathDirectory.java
catch (IOException e) { return null; }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch(IOException e) { // ignore it }
// in model/org/eclipse/jdt/internal/core/builder/ClasspathJar.java
catch (IOException e) { // treat as if class file is missing }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (CoreException e1) { if (e1.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) { // workspace was moved // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=241400 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=252571 ) project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } else { // .project or folder on disk have been deleted, recreate them IPath stateLocation = JavaCore.getPlugin().getStateLocation(); IPath projectPath = stateLocation.append(EXTERNAL_PROJECT_NAME); projectPath.toFile().mkdirs(); try { FileOutputStream output = new FileOutputStream(projectPath.append(".project").toOSString()); //$NON-NLS-1$ try { output.write(( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$ "<projectDescription>\n" + //$NON-NLS-1$ " <name>" + EXTERNAL_PROJECT_NAME + "</name>\n" + //$NON-NLS-1$ //$NON-NLS-2$ " <comment></comment>\n" + //$NON-NLS-1$ " <projects>\n" + //$NON-NLS-1$ " </projects>\n" + //$NON-NLS-1$ " <buildSpec>\n" + //$NON-NLS-1$ " </buildSpec>\n" + //$NON-NLS-1$ " <natures>\n" + //$NON-NLS-1$ " </natures>\n" + //$NON-NLS-1$ "</projectDescription>").getBytes()); //$NON-NLS-1$ } finally { output.close(); } } catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); } } project.open(monitor); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch (IOException e) { // fallback to re-creating the project project.delete(false/*don't delete content*/, true/*force*/, monitor); createExternalFoldersProject(project, monitor); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (java.io.IOException e) { if (TypeHierarchy.DEBUG) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { if (timestampsFile.exists()) Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { // nothing we can do: ignore }
// in model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
catch (IOException e) { // could not read file: returns an empty array }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // default to original path return externalPath; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // bad format return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { return null; // never happens since all is done in memory }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // problems loading preference store - quietly ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { // ignore problems with close }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { Util.log(e, "Exception while reading " + getPath().append(JavaProject.CLASSPATH_FILENAME)); //$NON-NLS-1$ return new IClasspathEntry[][]{JavaProject.INVALID_CLASSPATH, ClasspathEntry.NO_ENTRIES}; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while initializing user library " + libName); //$NON-NLS-1$ instancePreferences.remove(propertyName); preferencesNeedFlush = true; continue; }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while decoding user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (IOException e) { Util.log(e, "Exception while serializing user library " + libName); //$NON-NLS-1$ return; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch (IOException e) { // ignore }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { return null; }
// in model/org/eclipse/jdt/core/ToolFactory.java
catch(IOException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (IOException e) { // should not happen CommentFormatterUtil.log(e); return; }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { /* ignore */ }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String errorMessage = Messages.bind(Messages.CaughtException, "IOException", e.getLocalizedMessage()); //$NON-NLS-1$ Util.log(e, errorMessage); System.err.println(Messages.bind(Messages.ExceptionSkip ,errorMessage)); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = file.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") //$NON-NLS-1$ }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } Util.log(e, errorMessage); System.err.println(errorMessage); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); }
// in formatter/org/eclipse/jdt/core/formatter/CodeFormatterApplication.java
catch (IOException e) { /* ignore */ }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (IOException e) { e.printStackTrace(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e1) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException ex) { System.out.println(Messages.parser_incorrectPath); return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch(IOException e) { throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IOException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IOException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch(IOException e) { // go to the next unit continue; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch(IOException e) { // go to the next unit continue; }
30
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (IOException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/CompilationUnit.java
catch (IOException e) { this.contents = CharOperation.NO_CHAR; // assume no source if asked again throw new AbortCompilationUnit(null, e, this.encoding); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { this.cachedChunks = null; throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException e) { if (newDiskIndex.indexFile.exists() && !newDiskIndex.indexFile.delete()) if (DEBUG) System.out.println("mergeWith - Failed to delete temp index " + newDiskIndex.indexFile); //$NON-NLS-1$ throw e; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (IOException ioe) { this.streamBuffer = null; throw ioe; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { addInvalidArchive(path); throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Messages.status_IOException, e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving non-chaining jar cache", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving variables and containers", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$ throw new CoreException(status); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { if (!file.exists()) return new IClasspathEntry[][]{defaultClasspath(), ClasspathEntry.NO_ENTRIES}; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(java.io.IOException ex){ throw new ExceptionInInitializerError(ex.getMessage()); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch(IOException e) { throw e; }
3
unknown (Lib) IllegalAccessException 0 0 0 10
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (IllegalAccessException e) { // should never happen }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalAccessException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (IllegalAccessException ignored) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IllegalAccessException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/ProblemReferenceBinding.java
catch (IllegalAccessException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalAccessException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
runtime (Lib) IllegalArgumentException 529
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void setLog(String logFileName) { final Date date = new Date(); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.getDefault()); try { int index = logFileName.lastIndexOf('.'); if (index != -1) { if (logFileName.substring(index).toLowerCase().equals(".xml")) { //$NON-NLS-1$ this.log = new GenericXMLWriter(new OutputStreamWriter(new FileOutputStream(logFileName, false), Util.UTF_8), Util.LINE_SEPARATOR, true); this.tagBits |= Logger.XML; // insert time stamp as comment this.log.println("<!-- " + dateFormat.format(date) + " -->");//$NON-NLS-1$//$NON-NLS-2$ this.log.println(Logger.XML_DTD_DECLARATION); this.parameters.put(Logger.COMPILER_NAME, this.main.bind("compiler.name")); //$NON-NLS-1$ this.parameters.put(Logger.COMPILER_VERSION, this.main.bind("compiler.version")); //$NON-NLS-1$ this.parameters.put(Logger.COMPILER_COPYRIGHT, this.main.bind("compiler.copyright")); //$NON-NLS-1$ printTag(Logger.COMPILER, this.parameters, true, false); } else { this.log = new PrintWriter(new FileOutputStream(logFileName, false)); this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$ } } else { this.log = new PrintWriter(new FileOutputStream(logFileName, false)); this.log.println("# " + dateFormat.format(date));//$NON-NLS-1$ } } catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void addNewEntry(ArrayList paths, String currentClasspathName, ArrayList currentRuleSpecs, String customEncoding, String destPath, boolean isSourceOnly, boolean rejectDestinationPathOnJars) { int rulesSpecsSize = currentRuleSpecs.size(); AccessRuleSet accessRuleSet = null; if (rulesSpecsSize != 0) { AccessRule[] accessRules = new AccessRule[currentRuleSpecs.size()]; boolean rulesOK = true; Iterator i = currentRuleSpecs.iterator(); int j = 0; while (i.hasNext()) { String ruleSpec = (String) i.next(); char key = ruleSpec.charAt(0); String pattern = ruleSpec.substring(1); if (pattern.length() > 0) { switch (key) { case '+': accessRules[j++] = new AccessRule(pattern .toCharArray(), 0); break; case '~': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.DiscouragedReference); break; case '-': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.ForbiddenReference); break; case '?': accessRules[j++] = new AccessRule(pattern .toCharArray(), IProblem.ForbiddenReference, true/*keep looking for accessible type*/); break; default: rulesOK = false; } } else { rulesOK = false; } } if (rulesOK) { accessRuleSet = new AccessRuleSet(accessRules, AccessRestriction.COMMAND_LINE, currentClasspathName); } else { if (currentClasspathName.length() != 0) { // we go on anyway addPendingErrors(this.bind("configure.incorrectClasspath", currentClasspathName));//$NON-NLS-1$ } return; } } if (NONE.equals(destPath)) { destPath = NONE; // keep == comparison valid } if (rejectDestinationPathOnJars && destPath != null && Util.isPotentialZipArchive(currentClasspathName)) { throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntryFile", //$NON-NLS-1$ currentClasspathName)); } FileSystem.Classpath currentClasspath = FileSystem.getClasspath( currentClasspathName, customEncoding, isSourceOnly, accessRuleSet, destPath); if (currentClasspath != null) { paths.add(currentClasspath); } else if (currentClasspathName.length() != 0) { // we go on anyway addPendingErrors(this.bind("configure.incorrectClasspath", currentClasspathName));//$NON-NLS-1$ } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void configure(String[] argv) { if ((argv == null) || (argv.length == 0)) { printUsage(); return; } final int INSIDE_CLASSPATH_start = 1; final int INSIDE_DESTINATION_PATH = 3; final int INSIDE_TARGET = 4; final int INSIDE_LOG = 5; final int INSIDE_REPETITION = 6; final int INSIDE_SOURCE = 7; final int INSIDE_DEFAULT_ENCODING = 8; final int INSIDE_BOOTCLASSPATH_start = 9; final int INSIDE_MAX_PROBLEMS = 11; final int INSIDE_EXT_DIRS = 12; final int INSIDE_SOURCE_PATH_start = 13; final int INSIDE_ENDORSED_DIRS = 15; final int INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH = 16; final int INSIDE_PROCESSOR_PATH_start = 17; final int INSIDE_PROCESSOR_start = 18; final int INSIDE_S_start = 19; final int INSIDE_CLASS_NAMES = 20; final int INSIDE_WARNINGS_PROPERTIES = 21; final int DEFAULT = 0; ArrayList bootclasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); String sourcepathClasspathArg = null; ArrayList sourcepathClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); ArrayList classpaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); ArrayList extdirsClasspaths = null; ArrayList endorsedDirClasspaths = null; int index = -1; int filesCount = 0; int classCount = 0; int argCount = argv.length; int mode = DEFAULT; this.maxRepetition = 0; boolean printUsageRequired = false; String usageSection = null; boolean printVersionRequired = false; boolean didSpecifyDeprecation = false; boolean didSpecifyCompliance = false; boolean didSpecifyDisabledAnnotationProcessing = false; String customEncoding = null; String customDestinationPath = null; String currentSourceDirectory = null; String currentArg = Util.EMPTY_STRING; Set specifiedEncodings = null; // expand the command line if necessary boolean needExpansion = false; loop: for (int i = 0; i < argCount; i++) { if (argv[i].startsWith("@")) { //$NON-NLS-1$ needExpansion = true; break loop; } } String[] newCommandLineArgs = null; if (needExpansion) { newCommandLineArgs = new String[argCount]; index = 0; for (int i = 0; i < argCount; i++) { String[] newArgs = null; String arg = argv[i].trim(); if (arg.startsWith("@")) { //$NON-NLS-1$ try { LineNumberReader reader = new LineNumberReader(new StringReader(new String(Util.getFileCharContent(new File(arg.substring(1)), null)))); StringBuffer buffer = new StringBuffer(); String line; while((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { //$NON-NLS-1$ buffer.append(line).append(" "); //$NON-NLS-1$ } } newArgs = tokenize(buffer.toString()); } catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ } } if (newArgs != null) { int newCommandLineArgsLength = newCommandLineArgs.length; int newArgsLength = newArgs.length; System.arraycopy(newCommandLineArgs, 0, (newCommandLineArgs = new String[newCommandLineArgsLength + newArgsLength - 1]), 0, index); System.arraycopy(newArgs, 0, newCommandLineArgs, index, newArgsLength); index += newArgsLength; } else { newCommandLineArgs[index++] = arg; } } index = -1; } else { newCommandLineArgs = argv; for (int i = 0; i < argCount; i++) { newCommandLineArgs[i] = newCommandLineArgs[i].trim(); } } argCount = newCommandLineArgs.length; this.expandedCommandLine = newCommandLineArgs; while (++index < argCount) { if (customEncoding != null) { throw new IllegalArgumentException( this.bind("configure.unexpectedCustomEncoding", currentArg, customEncoding)); //$NON-NLS-1$ } currentArg = newCommandLineArgs[index]; switch(mode) { case DEFAULT : if (currentArg.startsWith("[")) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } if (currentArg.endsWith("]")) { //$NON-NLS-1$ // look for encoding specification int encodingStart = currentArg.indexOf('[') + 1; if (encodingStart <= 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", currentArg)); //$NON-NLS-1$ } int encodingEnd = currentArg.length() - 1; if (encodingStart >= 1) { if (encodingStart < encodingEnd) { customEncoding = currentArg.substring(encodingStart, encodingEnd); try { // ensure encoding is supported new InputStreamReader(new ByteArrayInputStream(new byte[0]), customEncoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ } } currentArg = currentArg.substring(0, encodingStart - 1); } } if (currentArg.endsWith(SuffixConstants.SUFFIX_STRING_java)) { if (this.filenames == null) { this.filenames = new String[argCount - index]; this.encodings = new String[argCount - index]; this.destinationPaths = new String[argCount - index]; } else if (filesCount == this.filenames.length) { int length = this.filenames.length; System.arraycopy( this.filenames, 0, (this.filenames = new String[length + argCount - index]), 0, length); System.arraycopy( this.encodings, 0, (this.encodings = new String[length + argCount - index]), 0, length); System.arraycopy( this.destinationPaths, 0, (this.destinationPaths = new String[length + argCount - index]), 0, length); } this.filenames[filesCount] = currentArg; this.encodings[filesCount++] = customEncoding; // destination path cannot be specified upon an individual file customEncoding = null; mode = DEFAULT; continue; } if (currentArg.equals("-log")) { //$NON-NLS-1$ if (this.log != null) throw new IllegalArgumentException( this.bind("configure.duplicateLog", currentArg)); //$NON-NLS-1$ mode = INSIDE_LOG; continue; } if (currentArg.equals("-repeat")) { //$NON-NLS-1$ if (this.maxRepetition > 0) throw new IllegalArgumentException( this.bind("configure.duplicateRepeat", currentArg)); //$NON-NLS-1$ mode = INSIDE_REPETITION; continue; } if (currentArg.equals("-maxProblems")) { //$NON-NLS-1$ if (this.maxProblems > 0) throw new IllegalArgumentException( this.bind("configure.duplicateMaxProblems", currentArg)); //$NON-NLS-1$ mode = INSIDE_MAX_PROBLEMS; continue; } if (currentArg.equals("-source")) { //$NON-NLS-1$ mode = INSIDE_SOURCE; continue; } if (currentArg.equals("-encoding")) { //$NON-NLS-1$ mode = INSIDE_DEFAULT_ENCODING; continue; } if (currentArg.equals("-1.3")) { //$NON-NLS-1$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg));//$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_3); mode = DEFAULT; continue; } if (currentArg.equals("-1.4")) { //$NON-NLS-1$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); mode = DEFAULT; continue; } if (currentArg.equals("-1.5") || currentArg.equals("-5") || currentArg.equals("-5.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); mode = DEFAULT; continue; } if (currentArg.equals("-1.6") || currentArg.equals("-6") || currentArg.equals("-6.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6); mode = DEFAULT; continue; } if (currentArg.equals("-1.7") || currentArg.equals("-7") || currentArg.equals("-7.0")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (didSpecifyCompliance) { throw new IllegalArgumentException( this.bind("configure.duplicateCompliance", currentArg)); //$NON-NLS-1$ } didSpecifyCompliance = true; this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7); mode = DEFAULT; continue; } if (currentArg.equals("-d")) { //$NON-NLS-1$ if (this.destinationPath != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateOutputPath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_DESTINATION_PATH; continue; } if (currentArg.equals("-classpath") //$NON-NLS-1$ || currentArg.equals("-cp")) { //$NON-NLS-1$ mode = INSIDE_CLASSPATH_start; continue; } if (currentArg.equals("-bootclasspath")) {//$NON-NLS-1$ if (bootclasspaths.size() > 0) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateBootClasspath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_BOOTCLASSPATH_start; continue; } if (currentArg.equals("-sourcepath")) {//$NON-NLS-1$ if (sourcepathClasspathArg != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateSourcepath", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_SOURCE_PATH_start; continue; } if (currentArg.equals("-extdirs")) {//$NON-NLS-1$ if (extdirsClasspaths != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateExtDirs", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_EXT_DIRS; continue; } if (currentArg.equals("-endorseddirs")) { //$NON-NLS-1$ if (endorsedDirClasspaths != null) { StringBuffer errorMessage = new StringBuffer(); errorMessage.append(currentArg); if ((index + 1) < argCount) { errorMessage.append(' '); errorMessage.append(newCommandLineArgs[index + 1]); } throw new IllegalArgumentException( this.bind("configure.duplicateEndorsedDirs", errorMessage.toString())); //$NON-NLS-1$ } mode = INSIDE_ENDORSED_DIRS; continue; } if (currentArg.equals("-progress")) { //$NON-NLS-1$ mode = DEFAULT; this.showProgress = true; continue; } if (currentArg.startsWith("-proceedOnError")) { //$NON-NLS-1$ mode = DEFAULT; int length = currentArg.length(); if (length > 15) { if (currentArg.equals("-proceedOnError:Fatal")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_FatalOptionalError, CompilerOptions.ENABLED); } else { throw new IllegalArgumentException( this.bind("configure.invalidWarningConfiguration", currentArg)); //$NON-NLS-1$ } } else { this.options.put(CompilerOptions.OPTION_FatalOptionalError, CompilerOptions.DISABLED); } this.proceedOnError = true; continue; } if (currentArg.equals("-time")) { //$NON-NLS-1$ mode = DEFAULT; this.timing = TIMING_ENABLED; continue; } if (currentArg.equals("-time:detail")) { //$NON-NLS-1$ mode = DEFAULT; this.timing = TIMING_ENABLED|TIMING_DETAILED; continue; } if (currentArg.equals("-version") //$NON-NLS-1$ || currentArg.equals("-v")) { //$NON-NLS-1$ this.logger.logVersion(true); this.proceed = false; return; } if (currentArg.equals("-showversion")) { //$NON-NLS-1$ printVersionRequired = true; mode = DEFAULT; continue; } if ("-deprecation".equals(currentArg)) { //$NON-NLS-1$ didSpecifyDeprecation = true; this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); mode = DEFAULT; continue; } if (currentArg.equals("-help") || currentArg.equals("-?")) { //$NON-NLS-1$ //$NON-NLS-2$ printUsageRequired = true; mode = DEFAULT; continue; } if (currentArg.equals("-help:warn") || //$NON-NLS-1$ currentArg.equals("-?:warn")) { //$NON-NLS-1$ printUsageRequired = true; usageSection = "misc.usage.warn"; //$NON-NLS-1$ continue; } if (currentArg.equals("-noExit")) { //$NON-NLS-1$ this.systemExitWhenFinished = false; mode = DEFAULT; continue; } if (currentArg.equals("-verbose")) { //$NON-NLS-1$ this.verbose = true; mode = DEFAULT; continue; } if (currentArg.equals("-referenceInfo")) { //$NON-NLS-1$ this.produceRefInfo = true; mode = DEFAULT; continue; } if (currentArg.equals("-inlineJSR")) { //$NON-NLS-1$ mode = DEFAULT; this.options.put( CompilerOptions.OPTION_InlineJsr, CompilerOptions.ENABLED); continue; } if (currentArg.startsWith("-g")) { //$NON-NLS-1$ mode = DEFAULT; String debugOption = currentArg; int length = currentArg.length(); if (length == 2) { this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); continue; } if (length > 3) { this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE); this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE); this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE); if (length == 7 && debugOption.equals("-g:" + NONE)) //$NON-NLS-1$ continue; StringTokenizer tokenizer = new StringTokenizer(debugOption.substring(3, debugOption.length()), ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.equals("vars")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); } else if (token.equals("lines")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); } else if (token.equals("source")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } else { throw new IllegalArgumentException( this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$ } } continue; } throw new IllegalArgumentException( this.bind("configure.invalidDebugOption", debugOption)); //$NON-NLS-1$ } if (currentArg.startsWith("-nowarn")) { //$NON-NLS-1$ disableWarnings(); mode = DEFAULT; continue; } if (currentArg.startsWith("-warn")) { //$NON-NLS-1$ mode = DEFAULT; String warningOption = currentArg; int length = currentArg.length(); if (length == 10 && warningOption.equals("-warn:" + NONE)) { //$NON-NLS-1$ disableWarnings(); continue; } if (length <= 6) { throw new IllegalArgumentException( this.bind("configure.invalidWarningConfiguration", warningOption)); //$NON-NLS-1$ } int warnTokenStart; boolean isEnabling, allowPlusOrMinus; switch (warningOption.charAt(6)) { case '+' : warnTokenStart = 7; isEnabling = true; allowPlusOrMinus = true; break; case '-' : warnTokenStart = 7; isEnabling = false; // specified warnings are disabled allowPlusOrMinus = true; break; default: disableWarnings(); warnTokenStart = 6; isEnabling = true; allowPlusOrMinus = false; } StringTokenizer tokenizer = new StringTokenizer(warningOption.substring(warnTokenStart, warningOption.length()), ","); //$NON-NLS-1$ int tokenCounter = 0; if (didSpecifyDeprecation) { // deprecation could have also been set through -deprecation option this.options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING); } while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); tokenCounter++; switch(token.charAt(0)) { case '+' : if (allowPlusOrMinus) { isEnabling = true; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$ } break; case '-' : if (allowPlusOrMinus) { isEnabling = false; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$ } } handleWarningToken(token, isEnabling); } if (tokenCounter == 0) { throw new IllegalArgumentException( this.bind("configure.invalidWarningOption", currentArg)); //$NON-NLS-1$ } continue; } if (currentArg.startsWith("-err")) { //$NON-NLS-1$ mode = DEFAULT; String errorOption = currentArg; int length = currentArg.length(); if (length <= 5) { throw new IllegalArgumentException( this.bind("configure.invalidErrorConfiguration", errorOption)); //$NON-NLS-1$ } int errorTokenStart; boolean isEnabling, allowPlusOrMinus; switch (errorOption.charAt(5)) { case '+' : errorTokenStart = 6; isEnabling = true; allowPlusOrMinus = true; break; case '-' : errorTokenStart = 6; isEnabling = false; // specified errors are disabled allowPlusOrMinus = true; break; default: disableErrors(); errorTokenStart = 5; isEnabling = true; allowPlusOrMinus = false; } StringTokenizer tokenizer = new StringTokenizer(errorOption.substring(errorTokenStart, errorOption.length()), ","); //$NON-NLS-1$ int tokenCounter = 0; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); tokenCounter++; switch(token.charAt(0)) { case '+' : if (allowPlusOrMinus) { isEnabling = true; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfPlusOption", token)); //$NON-NLS-1$ } break; case '-' : if (allowPlusOrMinus) { isEnabling = false; token = token.substring(1); } else { throw new IllegalArgumentException( this.bind("configure.invalidUsageOfMinusOption", token)); //$NON-NLS-1$ } break; } handleErrorToken(token, isEnabling); } if (tokenCounter == 0) { throw new IllegalArgumentException( this.bind("configure.invalidErrorOption", currentArg)); //$NON-NLS-1$ } continue; } if (currentArg.equals("-target")) { //$NON-NLS-1$ mode = INSIDE_TARGET; continue; } if (currentArg.equals("-preserveAllLocals")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); mode = DEFAULT; continue; } if (currentArg.equals("-enableJavadoc")) {//$NON-NLS-1$ mode = DEFAULT; this.enableJavadocOn = true; continue; } if (currentArg.equals("-Xemacs")) { //$NON-NLS-1$ mode = DEFAULT; this.logger.setEmacs(); continue; } // annotation processing if (currentArg.startsWith("-A")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-processorpath")) { //$NON-NLS-1$ mode = INSIDE_PROCESSOR_PATH_start; continue; } if (currentArg.equals("-processor")) { //$NON-NLS-1$ mode = INSIDE_PROCESSOR_start; continue; } if (currentArg.equals("-proc:only")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_GenerateClassFiles, CompilerOptions.DISABLED); mode = DEFAULT; continue; } if (currentArg.equals("-proc:none")) { //$NON-NLS-1$ didSpecifyDisabledAnnotationProcessing = true; this.options.put( CompilerOptions.OPTION_Process_Annotations, CompilerOptions.DISABLED); mode = DEFAULT; continue; } if (currentArg.equals("-s")) { //$NON-NLS-1$ mode = INSIDE_S_start; continue; } if (currentArg.equals("-XprintProcessorInfo") //$NON-NLS-1$ || currentArg.equals("-XprintRounds")) { //$NON-NLS-1$ mode = DEFAULT; continue; } // tolerated javac options - quietly filtered out if (currentArg.startsWith("-X")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.startsWith("-J")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-O")) { //$NON-NLS-1$ mode = DEFAULT; continue; } if (currentArg.equals("-classNames")) { //$NON-NLS-1$ mode = INSIDE_CLASS_NAMES; continue; } if (currentArg.equals("-properties")) { //$NON-NLS-1$ mode = INSIDE_WARNINGS_PROPERTIES; continue; } break; case INSIDE_TARGET : if (this.didSpecifyTarget) { throw new IllegalArgumentException( this.bind("configure.duplicateTarget", currentArg));//$NON-NLS-1$ } this.didSpecifyTarget = true; if (currentArg.equals("1.1")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1); } else if (currentArg.equals("1.2")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } else if (currentArg.equals("1.3")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3); } else if (currentArg.equals("1.4")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } else if (currentArg.equals("jsr14")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_JSR14); } else if (currentArg.equals("cldc1.1")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_CLDC1_1); this.options.put(CompilerOptions.OPTION_InlineJsr, CompilerOptions.ENABLED); }else { throw new IllegalArgumentException(this.bind("configure.targetJDK", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_LOG : this.log = currentArg; mode = DEFAULT; continue; case INSIDE_REPETITION : try { this.maxRepetition = Integer.parseInt(currentArg); if (this.maxRepetition <= 0) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ } } catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_MAX_PROBLEMS : try { this.maxProblems = Integer.parseInt(currentArg); if (this.maxProblems <= 0) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ } this.options.put(CompilerOptions.OPTION_MaxProblemPerUnit, currentArg); } catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_SOURCE : if (this.didSpecifySource) { throw new IllegalArgumentException( this.bind("configure.duplicateSource", currentArg));//$NON-NLS-1$ } this.didSpecifySource = true; if (currentArg.equals("1.3")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); } else if (currentArg.equals("1.4")) { //$NON-NLS-1$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4); } else if (currentArg.equals("1.5") || currentArg.equals("5") || currentArg.equals("5.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); } else if (currentArg.equals("1.6") || currentArg.equals("6") || currentArg.equals("6.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6); } else if (currentArg.equals("1.7") || currentArg.equals("7") || currentArg.equals("7.0")) { //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7); } else { throw new IllegalArgumentException(this.bind("configure.source", currentArg)); //$NON-NLS-1$ } mode = DEFAULT; continue; case INSIDE_DEFAULT_ENCODING : if (specifiedEncodings != null) { // check already defined encoding if (!specifiedEncodings.contains(currentArg)) { if (specifiedEncodings.size() > 1) { this.logger.logWarning( this.bind("configure.differentencodings", //$NON-NLS-1$ currentArg, getAllEncodings(specifiedEncodings))); } else { this.logger.logWarning( this.bind("configure.differentencoding", //$NON-NLS-1$ currentArg, getAllEncodings(specifiedEncodings))); } } } else { specifiedEncodings = new HashSet(); } try { // ensure encoding is supported new InputStreamReader(new ByteArrayInputStream(new byte[0]), currentArg); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ } specifiedEncodings.add(currentArg); this.options.put(CompilerOptions.OPTION_Encoding, currentArg); mode = DEFAULT; continue; case INSIDE_DESTINATION_PATH : setDestinationPath(currentArg.equals(NONE) ? NONE : currentArg); mode = DEFAULT; continue; case INSIDE_CLASSPATH_start: mode = DEFAULT; index += processPaths(newCommandLineArgs, index, currentArg, classpaths); continue; case INSIDE_BOOTCLASSPATH_start: mode = DEFAULT; index += processPaths(newCommandLineArgs, index, currentArg, bootclasspaths); continue; case INSIDE_SOURCE_PATH_start: mode = DEFAULT; String[] sourcePaths = new String[1]; index += processPaths(newCommandLineArgs, index, currentArg, sourcePaths); sourcepathClasspathArg = sourcePaths[0]; continue; case INSIDE_EXT_DIRS: if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$ "-extdir")); //$NON-NLS-1$ } StringTokenizer tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false); extdirsClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); while (tokenizer.hasMoreTokens()) extdirsClasspaths.add(tokenizer.nextToken()); mode = DEFAULT; continue; case INSIDE_ENDORSED_DIRS: if (currentArg.indexOf("[-d") != -1) { //$NON-NLS-1$ throw new IllegalArgumentException( this.bind("configure.unexpectedDestinationPathEntry", //$NON-NLS-1$ "-endorseddirs")); //$NON-NLS-1$ } tokenizer = new StringTokenizer(currentArg, File.pathSeparator, false); endorsedDirClasspaths = new ArrayList(DEFAULT_SIZE_CLASSPATH); while (tokenizer.hasMoreTokens()) endorsedDirClasspaths.add(tokenizer.nextToken()); mode = DEFAULT; continue; case INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH: if (currentArg.endsWith("]")) { //$NON-NLS-1$ customDestinationPath = currentArg.substring(0, currentArg.length() - 1); } else { throw new IllegalArgumentException( this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$ "[-d " + currentArg)); //$NON-NLS-1$ } break; case INSIDE_PROCESSOR_PATH_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_PROCESSOR_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_S_start : // nothing to do here. This is consumed again by the AnnotationProcessorManager mode = DEFAULT; continue; case INSIDE_CLASS_NAMES : tokenizer = new StringTokenizer(currentArg, ","); //$NON-NLS-1$ if (this.classNames == null) { this.classNames = new String[DEFAULT_SIZE_CLASSPATH]; } while (tokenizer.hasMoreTokens()) { if (this.classNames.length == classCount) { // resize System.arraycopy( this.classNames, 0, (this.classNames = new String[classCount * 2]), 0, classCount); } this.classNames[classCount++] = tokenizer.nextToken(); } mode = DEFAULT; continue; case INSIDE_WARNINGS_PROPERTIES : initializeWarnings(currentArg); mode = DEFAULT; continue; } // default is input directory, if no custom destination path exists if (customDestinationPath == null) { if (File.separatorChar != '/') { currentArg = currentArg.replace('/', File.separatorChar); } if (currentArg.endsWith("[-d")) { //$NON-NLS-1$ currentSourceDirectory = currentArg.substring(0, currentArg.length() - 3); mode = INSIDE_SOURCE_DIRECTORY_DESTINATION_PATH; continue; } currentSourceDirectory = currentArg; } File dir = new File(currentSourceDirectory); if (!dir.isDirectory()) { throw new IllegalArgumentException( this.bind("configure.unrecognizedOption", currentSourceDirectory)); //$NON-NLS-1$ } String[] result = FileFinder.find(dir, SuffixConstants.SUFFIX_STRING_JAVA); if (NONE.equals(customDestinationPath)) { customDestinationPath = NONE; // ensure == comparison } if (this.filenames != null) { // some source files were specified explicitly int length = result.length; System.arraycopy( this.filenames, 0, (this.filenames = new String[length + filesCount]), 0, filesCount); System.arraycopy( this.encodings, 0, (this.encodings = new String[length + filesCount]), 0, filesCount); System.arraycopy( this.destinationPaths, 0, (this.destinationPaths = new String[length + filesCount]), 0, filesCount); System.arraycopy(result, 0, this.filenames, filesCount, length); for (int i = 0; i < length; i++) { this.encodings[filesCount + i] = customEncoding; this.destinationPaths[filesCount + i] = customDestinationPath; } filesCount += length; customEncoding = null; customDestinationPath = null; currentSourceDirectory = null; } else { this.filenames = result; filesCount = this.filenames.length; this.encodings = new String[filesCount]; this.destinationPaths = new String[filesCount]; for (int i = 0; i < filesCount; i++) { this.encodings[i] = customEncoding; this.destinationPaths[i] = customDestinationPath; } customEncoding = null; customDestinationPath = null; currentSourceDirectory = null; } mode = DEFAULT; continue; } // set DocCommentSupport, with appropriate side effects on defaults if // javadoc is not enabled if (this.enableJavadocOn) { this.options.put( CompilerOptions.OPTION_DocCommentSupport, CompilerOptions.ENABLED); } else if (this.warnJavadocOn || this.warnAllJavadocOn) { this.options.put( CompilerOptions.OPTION_DocCommentSupport, CompilerOptions.ENABLED); // override defaults: references that are embedded in javadoc are ignored // from the perspective of parameters and thrown exceptions usage this.options.put( CompilerOptions.OPTION_ReportUnusedParameterIncludeDocCommentReference, CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportUnusedDeclaredThrownExceptionIncludeDocCommentReference, CompilerOptions.DISABLED); } // configure warnings for javadoc contents if (this.warnJavadocOn) { this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTags, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTagsDeprecatedRef, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportInvalidJavadocTagsNotVisibleRef, CompilerOptions.ENABLED); this.options.put( CompilerOptions.OPTION_ReportMissingJavadocTagsVisibility, CompilerOptions.PRIVATE); } if (printUsageRequired || (filesCount == 0 && classCount == 0)) { if (usageSection == null) { printUsage(); // default } else { printUsage(usageSection); } this.proceed = false; return; } if (this.log != null) { this.logger.setLog(this.log); } else { this.showProgress = false; } this.logger.logVersion(printVersionRequired); validateOptions(didSpecifyCompliance); // Enable annotation processing by default in batch mode when compliance is at least 1.6 // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=185768 if (!didSpecifyDisabledAnnotationProcessing && CompilerOptions.versionToJdkLevel(this.options.get(CompilerOptions.OPTION_Compliance)) >= ClassFileConstants.JDK1_6) { this.options.put(CompilerOptions.OPTION_Process_Annotations, CompilerOptions.ENABLED); } this.logger.logCommandLineArguments(newCommandLineArgs); this.logger.logOptions(this.options); if (this.maxRepetition == 0) { this.maxRepetition = 1; } if (this.maxRepetition >= 3 && (this.timing & TIMING_ENABLED) != 0) { this.compilerStats = new CompilerStats[this.maxRepetition]; } if (filesCount != 0) { System.arraycopy( this.filenames, 0, (this.filenames = new String[filesCount]), 0, filesCount); } if (classCount != 0) { System.arraycopy( this.classNames, 0, (this.classNames = new String[classCount]), 0, classCount); } setPaths(bootclasspaths, sourcepathClasspathArg, sourcepathClasspaths, classpaths, extdirsClasspaths, endorsedDirClasspaths, customEncoding); if (specifiedEncodings != null && specifiedEncodings.size() > 1) { this.logger.logWarning(this.bind("configure.multipleencodings", //$NON-NLS-1$ (String) this.options.get(CompilerOptions.OPTION_Encoding), getAllEncodings(specifiedEncodings))); } if (this.pendingErrors != null) { for (Iterator iterator = this.pendingErrors.iterator(); iterator.hasNext(); ) { String message = (String) iterator.next(); this.logger.logPendingError(message); } this.pendingErrors = null; } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private void initializeWarnings(String propertiesFile) { File file = new File(propertiesFile); if (!file.exists()) { throw new IllegalArgumentException(this.bind("configure.missingwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ } BufferedInputStream stream = null; Properties properties = null; try { stream = new BufferedInputStream(new FileInputStream(propertiesFile)); properties = new Properties(); properties.load(stream); } catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ } finally { if (stream != null) { try { stream.close(); } catch(IOException e) { // ignore } } } for (Iterator iterator = properties.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); final String key = (String) entry.getKey(); if (key.startsWith("org.eclipse.jdt.core.compiler.problem")) { //$NON-NLS-1$ this.options.put(key, entry.getValue()); } } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public CompilationUnit[] getCompilationUnits() { int fileCount = this.filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = (String) this.options.get(CompilerOptions.OPTION_Encoding); if (Util.EMPTY_STRING.equals(defaultEncoding)) defaultEncoding = null; for (int i = 0; i < fileCount; i++) { char[] charName = this.filenames[i].toCharArray(); if (knownFileNames.get(charName) != null) throw new IllegalArgumentException(this.bind("unit.more", this.filenames[i])); //$NON-NLS-1$ knownFileNames.put(charName, charName); File file = new File(this.filenames[i]); if (!file.exists()) throw new IllegalArgumentException(this.bind("unit.missing", this.filenames[i])); //$NON-NLS-1$ String encoding = this.encodings[i]; if (encoding == null) encoding = defaultEncoding; units[i] = new CompilationUnit(null, this.filenames[i], encoding, this.destinationPaths[i]); } return units; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private void handleErrorOrWarningToken(String token, boolean isEnabling, int severity) { if (token.length() == 0) return; switch(token.charAt(0)) { case 'a' : if (token.equals("allDeprecation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeprecation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("allJavadoc")) { //$NON-NLS-1$ this.warnAllJavadocOn = this.warnJavadocOn = isEnabling; setSeverity(CompilerOptions.OPTION_ReportInvalidJavadoc, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocTags, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocComments, severity, isEnabling); return; } else if (token.equals("assertIdentifier")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAssertIdentifier, severity, isEnabling); return; } else if (token.equals("allDeadCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeadCode, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("allOver-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingOverrideAnnotation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportMissingOverrideAnnotationForInterfaceMethodImplementation, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("all-static-method")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMethodCanBePotentiallyStatic, severity, isEnabling); return; } break; case 'b' : if (token.equals("boxing")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAutoboxing, severity, isEnabling); return; } break; case 'c' : if (token.equals("constructorName")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodWithConstructorName, severity, isEnabling); return; } else if (token.equals("conditionAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportPossibleAccidentalBooleanAssignment, severity, isEnabling); return; } else if (token.equals("compareIdentical")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportComparingIdentical, severity, isEnabling); return; } else if (token.equals("charConcat") /*|| token.equals("noImplicitStringConversion")/*backward compatible*/) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoImplicitStringConversion, severity, isEnabling); return; } break; case 'd' : if (token.equals("deprecation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeprecation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED); return; } else if (token.equals("dep-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingDeprecatedAnnotation, severity, isEnabling); return; } else if (token.equals("discouraged")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDiscouragedReference, severity, isEnabling); return; } else if (token.equals("deadCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportDeadCode, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportDeadCodeInTrivialIfStatement, CompilerOptions.DISABLED); return; } break; case 'e' : if (token.equals("enumSwitch") //$NON-NLS-1$ || token.equals("incomplete-switch")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportIncompleteEnumSwitch, severity, isEnabling); return; } else if (token.equals("emptyBlock")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUndocumentedEmptyBlock, severity, isEnabling); return; } else if (token.equals("enumIdentifier")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportEnumIdentifier, severity, isEnabling); return; } break; case 'f' : if (token.equals("fieldHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFieldHiding, severity, isEnabling); return; } else if (token.equals("finalBound")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFinalParameterBound, severity, isEnabling); return; } else if (token.equals("finally")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFinallyBlockNotCompletingNormally, severity, isEnabling); return; } else if (token.equals("forbidden")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportForbiddenReference, severity, isEnabling); return; } else if (token.equals("fallthrough")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportFallthroughCase, severity, isEnabling); return; } break; case 'h' : if (token.equals("hiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportHiddenCatchBlock, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportLocalVariableHiding, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportFieldHiding, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportTypeParameterHiding, severity, isEnabling); return; } else if (token.equals("hashCode")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingHashCodeMethod, severity, isEnabling); return; } break; case 'i' : if (token.equals("indirectStatic")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportIndirectStaticAccess, severity, isEnabling); return; } else if (token.equals("intfNonInherited") || token.equals("interfaceNonInherited")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportIncompatibleNonInheritedInterfaceMethod, severity, isEnabling); return; } else if (token.equals("intfAnnotation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportAnnotationSuperInterface, severity, isEnabling); return; } else if (token.equals("intfRedundant") /*|| token.equals("redundantSuperinterface")*/) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling); return; } else if (token.equals("includeAssertNull")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_IncludeNullInfoFromAsserts, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } break; case 'j' : if (token.equals("javadoc")) {//$NON-NLS-1$ this.warnJavadocOn = isEnabling; setSeverity(CompilerOptions.OPTION_ReportInvalidJavadoc, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportMissingJavadocTags, severity, isEnabling); return; } break; case 'l' : if (token.equals("localHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportLocalVariableHiding, severity, isEnabling); return; } break; case 'm' : if (token.equals("maskedCatchBlock") || token.equals("maskedCatchBlocks")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportHiddenCatchBlock, severity, isEnabling); return; } break; case 'n' : if (token.equals("nls")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, severity, isEnabling); return; } else if (token.equals("noEffectAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoEffectAssignment, severity, isEnabling); return; } else if (/*token.equals("charConcat") ||*/ token.equals("noImplicitStringConversion")/*backward compatible*/) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNoImplicitStringConversion, severity, isEnabling); return; } else if (token.equals("null")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNullReference, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportPotentialNullReference, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, severity, isEnabling); return; } else if (token.equals("nullDereference")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNullReference, severity, isEnabling); if (!isEnabling) { setSeverity(CompilerOptions.OPTION_ReportPotentialNullReference, ProblemSeverities.Ignore, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantNullCheck, ProblemSeverities.Ignore, isEnabling); } return; } break; case 'o' : if (token.equals("over-sync") /*|| token.equals("syncOverride")*/) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSynchronizedOnInheritedMethod, severity, isEnabling); return; } else if (token.equals("over-ann")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingOverrideAnnotation, severity, isEnabling); this.options.put( CompilerOptions.OPTION_ReportMissingOverrideAnnotationForInterfaceMethodImplementation, CompilerOptions.DISABLED); return; } break; case 'p' : if (token.equals("pkgDefaultMethod") || token.equals("packageDefaultMethod")/*backward compatible*/ ) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, severity, isEnabling); return; } else if (token.equals("paramAssign")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportParameterAssignment, severity, isEnabling); return; } break; case 'r' : if (token.equals("raw")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRawTypeReference, severity, isEnabling); return; } else if (/*token.equals("intfRedundant") ||*/ token.equals("redundantSuperinterface")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportRedundantSuperinterface, severity, isEnabling); return; } break; case 's' : if (token.equals("specialParamHiding")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_ReportSpecialParameterHidingField, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } else if (token.equals("syntheticAccess") || token.equals("synthetic-access")) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, severity, isEnabling); return; } else if (token.equals("staticReceiver")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonStaticAccessToStatic, severity, isEnabling); return; } else if (/*token.equals("over-sync") ||*/ token.equals("syncOverride")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSynchronizedOnInheritedMethod, severity, isEnabling); return; } else if (token.equals("semicolon")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportEmptyStatement, severity, isEnabling); return; } else if (token.equals("serial")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMissingSerialVersion, severity, isEnabling); return; } else if (token.equals("suppress")) {//$NON-NLS-1$ switch(severity) { case ProblemSeverities.Warning : this.options.put( CompilerOptions.OPTION_SuppressWarnings, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_SuppressOptionalErrors, CompilerOptions.DISABLED); break; case ProblemSeverities.Error : this.options.put( CompilerOptions.OPTION_SuppressWarnings, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); this.options.put( CompilerOptions.OPTION_SuppressOptionalErrors, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); } return; } else if (token.equals("static-access")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportNonStaticAccessToStatic, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportIndirectStaticAccess, severity, isEnabling); return; } else if (token.equals("super")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportOverridingMethodWithoutSuperInvocation, severity, isEnabling); return; } else if (token.equals("static-method")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportMethodCanBeStatic, severity, isEnabling); return; } break; case 't' : if (token.startsWith("tasks")) { //$NON-NLS-1$ String taskTags = Util.EMPTY_STRING; int start = token.indexOf('('); int end = token.indexOf(')'); if (start >= 0 && end >= 0 && start < end){ taskTags = token.substring(start+1, end).trim(); taskTags = taskTags.replace('|',','); } if (taskTags.length() == 0){ throw new IllegalArgumentException(this.bind("configure.invalidTaskTag", token)); //$NON-NLS-1$ } this.options.put( CompilerOptions.OPTION_TaskTags, isEnabling ? taskTags : Util.EMPTY_STRING); setSeverity(CompilerOptions.OPTION_ReportTasks, severity, isEnabling); return; } else if (token.equals("typeHiding")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportTypeParameterHiding, severity, isEnabling); return; } break; case 'u' : if (token.equals("unusedLocal") || token.equals("unusedLocals")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedLocal, severity, isEnabling); return; } else if (token.equals("unusedArgument") || token.equals("unusedArguments")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedParameter, severity, isEnabling); return; } else if (token.equals("unusedImport") || token.equals("unusedImports")/*backward compatible*/) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnusedImport, severity, isEnabling); return; } else if (token.equals("unusedAllocation")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedObjectAllocation, severity, isEnabling); return; } else if (token.equals("unusedPrivate")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedPrivateMember, severity, isEnabling); return; } else if (token.equals("unusedLabel")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedLabel, severity, isEnabling); return; } else if (token.equals("uselessTypeCheck")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnnecessaryTypeCheck, severity, isEnabling); return; } else if (token.equals("unchecked") || token.equals("unsafe")) {//$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUncheckedTypeOperation, severity, isEnabling); return; } else if (token.equals("unnecessaryElse")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnnecessaryElse, severity, isEnabling); return; } else if (token.equals("unusedThrown")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedDeclaredThrownException, severity, isEnabling); return; } else if (token.equals("unqualifiedField") || token.equals("unqualified-field-access")) { //$NON-NLS-1$ //$NON-NLS-2$ setSeverity(CompilerOptions.OPTION_ReportUnqualifiedFieldAccess, severity, isEnabling); return; } else if (token.equals("unused")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedLocal, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedParameter, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedImport, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedPrivateMember, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedDeclaredThrownException, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedLabel, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedTypeArgumentsForMethodInvocation, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantSpecificationOfTypeArguments, severity, isEnabling); return; } else if (token.equals("unusedTypeArgs")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnusedTypeArgumentsForMethodInvocation, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportRedundantSpecificationOfTypeArguments, severity, isEnabling); return; } else if (token.equals("unavoidableGenericProblems")) { //$NON-NLS-1$ this.options.put( CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, isEnabling ? CompilerOptions.ENABLED : CompilerOptions.DISABLED); return; } break; case 'v' : if (token.equals("varargsCast")) { //$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportVarargsArgumentNeedCast, severity, isEnabling); return; } break; case 'w' : if (token.equals("warningToken")) {//$NON-NLS-1$ setSeverity(CompilerOptions.OPTION_ReportUnhandledWarningToken, severity, isEnabling); setSeverity(CompilerOptions.OPTION_ReportUnusedWarningToken, severity, isEnabling); return; } break; } String message = null; switch(severity) { case ProblemSeverities.Warning : message = this.bind("configure.invalidWarning", token); //$NON-NLS-1$ break; case ProblemSeverities.Error : message = this.bind("configure.invalidError", token); //$NON-NLS-1$ } addPendingErrors(message); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private ReferenceBinding[] processClassNames(LookupEnvironment environment) { // check for .class file presence in case of apt processing int length = this.classNames.length; ReferenceBinding[] referenceBindings = new ReferenceBinding[length]; for (int i = 0; i < length; i++) { String currentName = this.classNames[i]; char[][] compoundName = null; if (currentName.indexOf('.') != -1) { // consider names with '.' as fully qualified names char[] typeName = currentName.toCharArray(); compoundName = CharOperation.splitOn('.', typeName); } else { compoundName = new char[][] { currentName.toCharArray() }; } ReferenceBinding type = environment.getType(compoundName); if (type != null && type.isValidBinding()) { if (type.isBinaryBinding()) { referenceBindings[i] = type; } } else { throw new IllegalArgumentException( this.bind("configure.invalidClassName", currentName));//$NON-NLS-1$ } } return referenceBindings; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
public void processPathEntries(final int defaultSize, final ArrayList paths, final String currentPath, String customEncoding, boolean isSourceOnly, boolean rejectDestinationPathOnJars) { String currentClasspathName = null; String currentDestinationPath = null; ArrayList currentRuleSpecs = new ArrayList(defaultSize); StringTokenizer tokenizer = new StringTokenizer(currentPath, File.pathSeparator + "[]", true); //$NON-NLS-1$ ArrayList tokens = new ArrayList(); while (tokenizer.hasMoreTokens()) { tokens.add(tokenizer.nextToken()); } // state machine final int start = 0; final int readyToClose = 1; // 'path' 'path1[rule];path2' final int readyToCloseEndingWithRules = 2; // 'path[rule]' 'path1;path2[rule]' final int readyToCloseOrOtherEntry = 3; // 'path[rule];' 'path;' 'path1;path2;' final int rulesNeedAnotherRule = 4; // 'path[rule1;' final int rulesStart = 5; // 'path[' 'path1;path2[' final int rulesReadyToClose = 6; // 'path[rule' 'path[rule1;rule2' final int destinationPathReadyToClose = 7; // 'path[-d bin' final int readyToCloseEndingWithDestinationPath = 8; // 'path[-d bin]' 'path[rule][-d bin]' final int destinationPathStart = 9; // 'path[rule][' final int bracketOpened = 10; // '.*[.*' final int bracketClosed = 11; // '.*([.*])+' final int error = 99; int state = start; String token = null; int cursor = 0, tokensNb = tokens.size(), bracket = -1; while (cursor < tokensNb && state != error) { token = (String) tokens.get(cursor++); if (token.equals(File.pathSeparator)) { switch (state) { case start: case readyToCloseOrOtherEntry: case bracketOpened: break; case readyToClose: case readyToCloseEndingWithRules: case readyToCloseEndingWithDestinationPath: state = readyToCloseOrOtherEntry; addNewEntry(paths, currentClasspathName, currentRuleSpecs, customEncoding, currentDestinationPath, isSourceOnly, rejectDestinationPathOnJars); currentRuleSpecs.clear(); break; case rulesReadyToClose: state = rulesNeedAnotherRule; break; case destinationPathReadyToClose: throw new IllegalArgumentException( this.bind("configure.incorrectDestinationPathEntry", //$NON-NLS-1$ currentPath)); case bracketClosed: cursor = bracket + 1; state = rulesStart; break; default: state = error; } } else if (token.equals("[")) { //$NON-NLS-1$ switch (state) { case start: currentClasspathName = ""; //$NON-NLS-1$ //$FALL-THROUGH$ case readyToClose: bracket = cursor - 1; //$FALL-THROUGH$ case bracketClosed: state = bracketOpened; break; case readyToCloseEndingWithRules: state = destinationPathStart; break; case readyToCloseEndingWithDestinationPath: state = rulesStart; break; case bracketOpened: default: state = error; } } else if (token.equals("]")) { //$NON-NLS-1$ switch (state) { case rulesReadyToClose: state = readyToCloseEndingWithRules; break; case destinationPathReadyToClose: state = readyToCloseEndingWithDestinationPath; break; case bracketOpened: state = bracketClosed; break; case bracketClosed: default: state = error; } } else { // regular word switch (state) { case start: case readyToCloseOrOtherEntry: state = readyToClose; currentClasspathName = token; break; case rulesStart: if (token.startsWith("-d ")) { //$NON-NLS-1$ if (currentDestinationPath != null) { throw new IllegalArgumentException( this.bind("configure.duplicateDestinationPathEntry", //$NON-NLS-1$ currentPath)); } currentDestinationPath = token.substring(3).trim(); state = destinationPathReadyToClose; break; } // else we proceed with a rule //$FALL-THROUGH$ case rulesNeedAnotherRule: if (currentDestinationPath != null) { throw new IllegalArgumentException( this.bind("configure.accessRuleAfterDestinationPath", //$NON-NLS-1$ currentPath)); } state = rulesReadyToClose; currentRuleSpecs.add(token); break; case destinationPathStart: if (!token.startsWith("-d ")) { //$NON-NLS-1$ state = error; } else { currentDestinationPath = token.substring(3).trim(); state = destinationPathReadyToClose; } break; case bracketClosed: for (int i = bracket; i < cursor ; i++) { currentClasspathName += (String) tokens.get(i); } state = readyToClose; break; case bracketOpened: break; default: state = error; } } if (state == bracketClosed && cursor == tokensNb) { cursor = bracket + 1; state = rulesStart; } } switch(state) { case readyToCloseOrOtherEntry: break; case readyToClose: case readyToCloseEndingWithRules: case readyToCloseEndingWithDestinationPath: addNewEntry(paths, currentClasspathName, currentRuleSpecs, customEncoding, currentDestinationPath, isSourceOnly, rejectDestinationPathOnJars); break; case bracketOpened: case bracketClosed: default : // we go on anyway if (currentPath.length() != 0) { addPendingErrors(this.bind("configure.incorrectClasspath", currentPath));//$NON-NLS-1$ } } }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private int processPaths(String[] args, int index, String currentArg, ArrayList paths) { int localIndex = index; int count = 0; for (int i = 0, max = currentArg.length(); i < max; i++) { switch(currentArg.charAt(i)) { case '[' : count++; break; case ']' : count--; break; } } if (count == 0) { paths.add(currentArg); } else if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } else { StringBuffer currentPath = new StringBuffer(currentArg); while (true) { if (localIndex >= args.length) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } localIndex++; String nextArg = args[localIndex]; for (int i = 0, max = nextArg.length(); i < max; i++) { switch(nextArg.charAt(i)) { case '[' : if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ nextArg)); } count++; break; case ']' : count--; break; } } if (count == 0) { currentPath.append(' '); currentPath.append(nextArg); paths.add(currentPath.toString()); return localIndex - index; } else if (count < 0) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ nextArg)); } else { currentPath.append(' '); currentPath.append(nextArg); } } } return localIndex - index; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
private int processPaths(String[] args, int index, String currentArg, String[] paths) { int localIndex = index; int count = 0; for (int i = 0, max = currentArg.length(); i < max; i++) { switch(currentArg.charAt(i)) { case '[' : count++; break; case ']' : count--; break; } } if (count == 0) { paths[0] = currentArg; } else { StringBuffer currentPath = new StringBuffer(currentArg); while (true) { localIndex++; if (localIndex >= args.length) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } String nextArg = args[localIndex]; for (int i = 0, max = nextArg.length(); i < max; i++) { switch(nextArg.charAt(i)) { case '[' : if (count > 1) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } count++; break; case ']' : count--; break; } } if (count == 0) { currentPath.append(' '); currentPath.append(nextArg); paths[0] = currentPath.toString(); return localIndex - index; } else if (count < 0) { throw new IllegalArgumentException( this.bind("configure.unexpectedBracket", //$NON-NLS-1$ currentArg)); } else { currentPath.append(' '); currentPath.append(nextArg); } } } return localIndex - index; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
protected void validateOptions(boolean didSpecifyCompliance) { if (didSpecifyCompliance) { Object version = this.options.get(CompilerOptions.OPTION_Compliance); if (CompilerOptions.VERSION_1_3.equals(version)) { if (!this.didSpecifySource) this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1); } else if (CompilerOptions.VERSION_1_4.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } else if (CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2); } } else if (CompilerOptions.VERSION_1_5.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } } else if (CompilerOptions.VERSION_1_6.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source) || CompilerOptions.VERSION_1_6.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } } else if (CompilerOptions.VERSION_1_7.equals(version)) { if (this.didSpecifySource) { Object source = this.options.get(CompilerOptions.OPTION_Source); if (CompilerOptions.VERSION_1_3.equals(source) || CompilerOptions.VERSION_1_4.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(source) || CompilerOptions.VERSION_1_6.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (CompilerOptions.VERSION_1_7.equals(source)) { if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } else { this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } } else if (this.didSpecifySource) { Object version = this.options.get(CompilerOptions.OPTION_Source); // default is source 1.3 target 1.2 and compliance 1.4 if (CompilerOptions.VERSION_1_4.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4); } else if (CompilerOptions.VERSION_1_5.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5); } else if (CompilerOptions.VERSION_1_6.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6); } else if (CompilerOptions.VERSION_1_7.equals(version)) { if (!didSpecifyCompliance) this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7); if (!this.didSpecifyTarget) this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7); } } final Object sourceVersion = this.options.get(CompilerOptions.OPTION_Source); final Object compliance = this.options.get(CompilerOptions.OPTION_Compliance); if (sourceVersion.equals(CompilerOptions.VERSION_1_7) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_7) { // compliance must be 1.7 if source is 1.7 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_7)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_6) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_6) { // compliance must be 1.6 if source is 1.6 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_6)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_5) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_5) { // compliance must be 1.5 if source is 1.5 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_5)); //$NON-NLS-1$ } else if (sourceVersion.equals(CompilerOptions.VERSION_1_4) && CompilerOptions.versionToJdkLevel(compliance) < ClassFileConstants.JDK1_4) { // compliance must be 1.4 if source is 1.4 throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForSource", (String)this.options.get(CompilerOptions.OPTION_Compliance), CompilerOptions.VERSION_1_4)); //$NON-NLS-1$ } // check and set compliance/source/target compatibilities if (this.didSpecifyTarget) { final Object targetVersion = this.options.get(CompilerOptions.OPTION_TargetPlatform); // tolerate jsr14 target if (CompilerOptions.VERSION_JSR14.equals(targetVersion)) { // expecting source >= 1.5 if (CompilerOptions.versionToJdkLevel(sourceVersion) < ClassFileConstants.JDK1_5) { throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForGenericSource", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } } else if (CompilerOptions.VERSION_CLDC1_1.equals(targetVersion)) { if (this.didSpecifySource && CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_4) { throw new IllegalArgumentException(this.bind("configure.incompatibleSourceForCldcTarget", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } if (CompilerOptions.versionToJdkLevel(compliance) >= ClassFileConstants.JDK1_5) { throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForCldcTarget", (String) targetVersion, (String) sourceVersion)); //$NON-NLS-1$ } } else { // target must be 1.7 if source is 1.7 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_7 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_7){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_7)); //$NON-NLS-1$ } // target must be 1.6 if source is 1.6 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_6 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_6){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_6)); //$NON-NLS-1$ } // target must be 1.5 if source is 1.5 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_5 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_5){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_5)); //$NON-NLS-1$ } // target must be 1.4 if source is 1.4 if (CompilerOptions.versionToJdkLevel(sourceVersion) >= ClassFileConstants.JDK1_4 && CompilerOptions.versionToJdkLevel(targetVersion) < ClassFileConstants.JDK1_4){ throw new IllegalArgumentException(this.bind("configure.incompatibleTargetForSource", (String) targetVersion, CompilerOptions.VERSION_1_4)); //$NON-NLS-1$ } // target cannot be greater than compliance level if (CompilerOptions.versionToJdkLevel(compliance) < CompilerOptions.versionToJdkLevel(targetVersion)){ throw new IllegalArgumentException(this.bind("configure.incompatibleComplianceForTarget", (String)this.options.get(CompilerOptions.OPTION_Compliance), (String) targetVersion)); //$NON-NLS-1$ } } } }
// 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/indexing/IndexManager.java
private synchronized void updateIndexState(IPath indexLocation, Integer indexState) { if (indexLocation.isEmpty()) throw new IllegalArgumentException(); getIndexStates(); // ensure the states are initialized if (indexState != null) { if (indexState.equals(this.indexStates.get(indexLocation))) return; // not changed this.indexStates.put(indexLocation, indexState); } else { if (!this.indexStates.containsKey(indexLocation)) return; // did not exist anyway this.indexStates.removeKey(indexLocation); } writeSavedIndexNamesFile(); if (VERBOSE) { if (indexState == null) { Util.verbose("-> index state removed for: "+indexLocation); //$NON-NLS-1$ } else { String state = "?"; //$NON-NLS-1$ if (indexState == SAVED_STATE) state = "SAVED"; //$NON-NLS-1$ else if (indexState == UPDATING_STATE) state = "UPDATING"; //$NON-NLS-1$ else if (indexState == UNKNOWN_STATE) state = "UNKNOWN"; //$NON-NLS-1$ else if (indexState == REBUILDING_STATE) state = "REBUILDING"; //$NON-NLS-1$ Util.verbose("-> index state updated to: " + state + " for: "+indexLocation); //$NON-NLS-1$ //$NON-NLS-2$ } } }
// in search/org/eclipse/jdt/internal/core/index/Index.java
public String containerRelativePath(String documentPath) { int index = documentPath.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR); if (index == -1) { index = this.containerPath.length(); if (documentPath.length() <= index) throw new IllegalArgumentException("Document path " + documentPath + " must be relative to " + this.containerPath); //$NON-NLS-1$ //$NON-NLS-2$ } return documentPath.substring(index + 1); }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
synchronized String readDocumentName(int docNumber) throws IOException { if (this.cachedChunks == null) this.cachedChunks = new String[this.numberOfChunks][]; int chunkNumber = docNumber / CHUNK_SIZE; String[] chunk = this.cachedChunks[chunkNumber]; if (chunk == null) { boolean isLastChunk = chunkNumber == this.numberOfChunks - 1; int start = this.chunkOffsets[chunkNumber]; int numberOfBytes = (isLastChunk ? this.startOfCategoryTables : this.chunkOffsets[chunkNumber + 1]) - start; if (numberOfBytes < 0) throw new IllegalArgumentException(); this.streamBuffer = new byte[numberOfBytes]; this.bufferIndex = 0; FileInputStream file = new FileInputStream(this.indexFile); try { file.skip(start); if (file.read(this.streamBuffer, 0, numberOfBytes) != numberOfBytes) throw new IOException(); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } finally { file.close(); } int numberOfNames = isLastChunk ? this.sizeOfLastChunk : CHUNK_SIZE; chunk = new String[numberOfNames]; try { readChunk(chunk, null, 0, numberOfNames); } catch (IOException ioe) { this.streamBuffer = null; throw ioe; } this.cachedChunks[chunkNumber] = chunk; } this.streamBuffer = null; return chunk[docNumber - (chunkNumber * CHUNK_SIZE)]; }
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private void writeAllDocumentNames(String[] sortedDocNames, FileOutputStream stream) throws IOException { if (sortedDocNames.length == 0) throw new IllegalArgumentException(); // assume the file was just created by initializeFrom() this.streamBuffer = new byte[BUFFER_WRITE_SIZE]; this.bufferIndex = 0; this.streamEnd = 0; // in order, write: SIGNATURE & headerInfoOffset place holder, then each compressed chunk of document names writeStreamChars(stream, SIGNATURE_CHARS); this.headerInfoOffset = this.streamEnd; writeStreamInt(stream, -1); // will overwrite with correct value later int size = sortedDocNames.length; this.numberOfChunks = (size / CHUNK_SIZE) + 1; this.sizeOfLastChunk = size % CHUNK_SIZE; if (this.sizeOfLastChunk == 0) { this.numberOfChunks--; this.sizeOfLastChunk = CHUNK_SIZE; } this.documentReferenceSize = size <= 0x7F ? 1 : (size <= 0x7FFF ? 2 : 4); // number of bytes used to encode a reference this.chunkOffsets = new int[this.numberOfChunks]; int lastIndex = this.numberOfChunks - 1; for (int i = 0; i < this.numberOfChunks; i++) { this.chunkOffsets[i] = this.streamEnd; int chunkSize = i == lastIndex ? this.sizeOfLastChunk : CHUNK_SIZE; int chunkIndex = i * CHUNK_SIZE; String current = sortedDocNames[chunkIndex]; writeStreamChars(stream, current.toCharArray()); for (int j = 1; j < chunkSize; j++) { String next = sortedDocNames[chunkIndex + j]; int len1 = current.length(); int len2 = next.length(); int max = len1 < len2 ? len1 : len2; int start = 0; // number of identical characters at the beginning (also the index of first character that is different) while (current.charAt(start) == next.charAt(start)) { start++; if (max == start) break; // current is 'abba', next is 'abbab' } if (start > 255) start = 255; int end = 0; // number of identical characters at the end while (current.charAt(--len1) == next.charAt(--len2)) { end++; if (len2 == start) break; // current is 'abbba', next is 'abba' if (len1 == 0) break; // current is 'xabc', next is 'xyabc' } if (end > 255) end = 255; if ((this.bufferIndex + 2) >= BUFFER_WRITE_SIZE) { stream.write(this.streamBuffer, 0, this.bufferIndex); this.bufferIndex = 0; } this.streamBuffer[this.bufferIndex++] = (byte) start; this.streamBuffer[this.bufferIndex++] = (byte) end; this.streamEnd += 2; int last = next.length() - end; writeStreamChars(stream, (start < last ? CharOperation.subarray(next.toCharArray(), start, last) : CharOperation.NO_CHAR)); current = next; } } this.startOfCategoryTables = this.streamEnd + 1; }
// 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/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, 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 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/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/NameLookup.java
public IPackageFragment findPackageFragment(IPath path) { if (!path.isAbsolute()) { throw new IllegalArgumentException(Messages.path_mustBeAbsolute); } /* * TODO (jerome) this code should rather use the package fragment map to find the candidate package, then * check if the respective enclosing root maps to the one on this given IPath. */ IResource possibleFragment = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (possibleFragment == null) { //external jar for (int i = 0; i < this.packageFragmentRoots.length; i++) { IPackageFragmentRoot root = this.packageFragmentRoots[i]; if (!root.isExternal()) { continue; } IPath rootPath = root.getPath(); if (rootPath.isPrefixOf(path)) { String name = path.toOSString(); // + 1 is for the File.separatorChar name = name.substring(rootPath.toOSString().length() + 1, name.length()); name = name.replace(File.separatorChar, '.'); IJavaElement[] list = null; try { list = root.getChildren(); } catch (JavaModelException npe) { continue; // the package fragment root is not present; } int elementCount = list.length; for (int j = 0; j < elementCount; j++) { IPackageFragment packageFragment = (IPackageFragment) list[j]; if (nameMatches(name, packageFragment, false)) { return packageFragment; } } } } } else { IJavaElement fromFactory = JavaCore.create(possibleFragment); if (fromFactory == null) { return null; } switch (fromFactory.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: return (IPackageFragment) fromFactory; case IJavaElement.JAVA_PROJECT: // default package in a default root JavaProject project = (JavaProject) fromFactory; try { IClasspathEntry entry = project.getClasspathEntryFor(path); if (entry != null) { IPackageFragmentRoot root = project.getPackageFragmentRoot(project.getResource()); Object defaultPkgRoot = this.packageFragments.get(CharOperation.NO_STRINGS); if (defaultPkgRoot == null) { return null; } if (defaultPkgRoot instanceof PackageFragmentRoot && defaultPkgRoot.equals(root)) return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS); else { IPackageFragmentRoot[] roots = (IPackageFragmentRoot[]) defaultPkgRoot; for (int i = 0; i < roots.length; i++) { if (roots[i].equals(root)) { return ((PackageFragmentRoot) root).getPackageFragment(CharOperation.NO_STRINGS); } } } } } catch (JavaModelException e) { return null; } return null; case IJavaElement.PACKAGE_FRAGMENT_ROOT: return ((PackageFragmentRoot)fromFactory).getPackageFragment(CharOperation.NO_STRINGS); } } return null; }
// 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/JavaModel.java
public IJavaProject getJavaProject(IResource resource) { switch(resource.getType()){ case IResource.FOLDER: return new JavaProject(((IFolder)resource).getProject(), this); case IResource.FILE: return new JavaProject(((IFile)resource).getProject(), this); case IResource.PROJECT: return new JavaProject((IProject)resource, this); default: throw new IllegalArgumentException(Messages.element_invalidResourceForProject); } }
// 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 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 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
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/OverflowingLRUCache.java
public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException { if(newLoadFactor <= 1.0 && newLoadFactor > 0.0) this.loadFactor = newLoadFactor; else throw new IllegalArgumentException(Messages.cache_invalidLoadFactor); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getImport(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public void setName(String name) { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } becomeDetailed(); super.setName(name); this.fOnDemand = name.endsWith(".*"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getPackageDeclaration(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { return ((IType)parent).getField(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); setTypeAltered(true); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setType(String typeName) throws IllegalArgumentException { if (typeName == null) { throw new IllegalArgumentException(Messages.element_nullType); } becomeDetailed(); expand(); fragment(); setTypeAltered(true); setNameAltered(true); this.fType= typeName; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void addSuperInterface(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_addNullInterface); } if (this.fSuperInterfaces == null) { this.fSuperInterfaces= new String[1]; this.fSuperInterfaces[0]= name; } else { this.fSuperInterfaces= appendString(this.fSuperInterfaces, name); } setSuperInterfaces(this.fSuperInterfaces); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { switch (parent.getElementType()) { case IJavaElement.COMPILATION_UNIT: return ((ICompilationUnit)parent).getType(getName()); case IJavaElement.TYPE: return ((IType)parent).getType(getName()); // Note: creating local/anonymous type is not supported default: throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } super.setName(name); Enumeration children= getChildren(); while (children.hasMoreElements()) { IDOMNode child= (IDOMNode)children.nextElement(); if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setSuperInterfaces(String[] names) { becomeDetailed(); if (names == null) { throw new IllegalArgumentException(Messages.dom_nullInterfaces); } fragment(); this.fSuperInterfaces= names; if (names.length == 0) { this.fInterfaces= null; this.fSuperInterfaces= CharOperation.NO_STRINGS; setMask(MASK_TYPE_HAS_INTERFACES, false); } else { setMask(MASK_TYPE_HAS_INTERFACES, true); CharArrayBuffer buffer = new CharArrayBuffer(); for (int i = 0; i < names.length; i++) { if (i > 0) { buffer.append(", "); //$NON-NLS-1$ } buffer.append(names[i]); } this.fInterfaces = buffer.getContents(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { return ((IPackageFragment)parent).getCompilationUnit(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { int count = 1; IDOMNode previousNode = getPreviousNode(); while (previousNode != null) { if (previousNode instanceof DOMInitializer) { count++; } previousNode = previousNode.getPreviousNode(); } return ((IType) parent).getInitializer(count); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addException(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullExceptionType); } if (this.fExceptions == null) { this.fExceptions= new String[1]; this.fExceptions[0]= name; } else { this.fExceptions= appendString(this.fExceptions, name); } setExceptions(this.fExceptions); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addParameter(String type, String name) throws IllegalArgumentException { if (type == null) { throw new IllegalArgumentException(Messages.dom_nullTypeParameter); } if (name == null) { throw new IllegalArgumentException(Messages.dom_nullNameParameter); } if (this.fParameterNames == null) { this.fParameterNames= new String[1]; this.fParameterNames[0]= name; } else { this.fParameterNames= appendString(this.fParameterNames, name); } if (this.fParameterTypes == null) { this.fParameterTypes= new String[1]; this.fParameterTypes[0]= type; } else { this.fParameterTypes= appendString(this.fParameterTypes, type); } setParameters(this.fParameterTypes, this.fParameterNames); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { // translate parameter types to signatures String[] sigs= null; if (this.fParameterTypes != null) { sigs= new String[this.fParameterTypes.length]; int i; for (i= 0; i < this.fParameterTypes.length; i++) { sigs[i]= Signature.createTypeSignature(this.fParameterTypes[i].toCharArray(), false); } } String name= null; if (isConstructor()) { name= getConstructorName(); } else { name= getName(); } return ((IType)parent).getMethod(name, sigs); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setName(String name) { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setParameters(String[] types, String[] names) throws IllegalArgumentException { becomeDetailed(); if (types== null || names == null) { if (types == null && names == null) { this.fParameterTypes= null; this.fParameterNames= null; this.fParameterList= new char[] {'(',')'}; } else { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } } else if (names.length != types.length) { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } else if (names.length == 0) { setParameters(null, null); } else { this.fParameterNames= names; this.fParameterTypes= types; CharArrayBuffer parametersBuffer = new CharArrayBuffer(); parametersBuffer.append("("); //$NON-NLS-1$ char[] comma = new char[] {',', ' '}; for (int i = 0; i < names.length; i++) { if (i > 0) { parametersBuffer.append(comma); } parametersBuffer .append(types[i]) .append(' ') .append(names[i]); } parametersBuffer.append(')'); this.fParameterList= parametersBuffer.getContents(); } fragment(); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setReturnType(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullReturnType); } becomeDetailed(); fragment(); setReturnTypeAltered(true); this.fReturnType= name; }
// 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/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 IClassFile getClassFile(String classFileName) { if (!org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(classFileName)) { throw new IllegalArgumentException(Messages.bind(Messages.element_invalidClassFileName, classFileName)); } // don't hold on the .class file extension to save memory // also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary int length = classFileName.length() - 6; char[] nameWithoutExtension = new char[length]; classFileName.getChars(0, length, nameWithoutExtension, 0); return new ClassFile(this, new String(nameWithoutExtension)); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
public ICompilationUnit getCompilationUnit(String cuName) { if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(cuName)) { throw new IllegalArgumentException(Messages.convention_unit_notJavaName); } return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY); }
// 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/Member.java
public IType getType(String typeName, int count) { if (isBinary()) { throw new IllegalArgumentException("Not a source member " + toStringWithAncestors()); //$NON-NLS-1$ } else { SourceType type = new SourceType(this, typeName); type.occurrenceCount = count; return type; } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static void logRepeatedMessage(String key, Exception e) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$ } if (fgRepeatedMessages.contains(key)) { return; } fgRepeatedMessages.add(key); log(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
public static void logRepeatedMessage(String key, int statusErrorID, String message) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); //$NON-NLS-1$ } if (fgRepeatedMessages.contains(key)) { return; } fgRepeatedMessages.add(key); log(statusErrorID, message); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static void appendArrayTypeSignature(char[] string, int start, StringBuffer buffer, boolean compact) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == Signature.C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } c = string[++index]; } appendTypeSignature(string, index, buffer, compact); for(int i = 0, dims = index - start; i < dims; i++) { buffer.append('[').append(']'); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
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(); } StringBuffer buffer = new StringBuffer(methodSignature.length + 10); // selector if (methodName != null) { buffer.append(methodName); } // parameters 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; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } 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 new IllegalArgumentException(); // a var args is an array type } } 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 new IllegalArgumentException(); } } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendTypeArgumentSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } 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); } }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendCaptureTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_CAPTURE) { throw new IllegalArgumentException(); } return appendTypeArgumentSignatureForAnchor(string, start + 1, buffer); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendArrayTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer, boolean isVarArgs) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != Signature.C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == Signature.C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } 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; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
private static int appendClassTypeSignatureForAnchor(char[] string, int start, StringBuffer buffer) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != Signature.C_RESOLVED && c != Signature.C_UNRESOLVED) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; switch(c) { case Signature.C_SEMICOLON : // all done return p; case Signature.C_GENERIC_START : int e = scanGenericEnd(string, p + 1); // once we hit type arguments there are no more package prefixes p = e; break; case Signature.C_DOT : buffer.append('.'); break; case '/' : buffer.append('/'); break; case Signature.C_DOLLAR : // once we hit "$" there are no more package prefixes /** * Convert '$' in resolved type signatures into '.'. * NOTE: This assumes that the type signature is an inner type * signature. This is true in most cases, but someone can define a * non-inner type name containing a '$'. */ buffer.append('.'); break; default : buffer.append(c); } p++; } }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public ASTNode[] parseClassBodyDeclarations( char[] source, int offset, int length, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies; final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); parser.setMethodsFullRecovery(false); parser.setStatementsRecovery(enabledStatementRecovery); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); final CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length); ASTNode[] result = parser.parseClassBodyDeclarations(source, offset, length, compilationUnitDeclaration); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } return result; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public CompilationUnitDeclaration parseCompilationUnit(char[] source, Map settings, boolean recordParsingInformation) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies; CommentRecorderParser parser = new CommentRecorderParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())), false); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } if (compilationUnitDeclaration.ignoreMethodBodies) { compilationUnitDeclaration.ignoreFurtherInvestigation = true; // if initial diet parse did not work, no need to dig into method bodies. return compilationUnitDeclaration; } //fill the methods bodies in order for the code to be generated //real parse of the method.... parser.scanner.setSource(compilationResult); org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types; if (types != null) { for (int i = 0, length = types.length; i < length; i++) { types[i].parseMethods(parser, compilationUnitDeclaration); } } if (recordParsingInformation) { this.recordedParsingInformation.updateRecordedParsingInformation(compilationResult); } return compilationUnitDeclaration; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public Expression parseExpression(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); // in this case we don't want to ignore method bodies since we are parsing only an expression final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration unit = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length); Expression result = parser.parseExpression(source, offset, length, unit); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, unit.comments); } return result; }
// in model/org/eclipse/jdt/internal/core/util/CodeSnippetParsingUtil.java
public ConstructorDeclaration parseStatements( char[] source, int offset, int length, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) { if (source == null) { throw new IllegalArgumentException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); // in this case we don't want to ignore method bodies since we are parsing only statements final ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory(Locale.getDefault())); CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false); parser.setMethodsFullRecovery(false); parser.setStatementsRecovery(enabledStatementRecovery); ICompilationUnit sourceUnit = new CompilationUnit( source, "", //$NON-NLS-1$ compilerOptions.defaultEncoding); final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length); ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult); constructorDeclaration.sourceEnd = -1; constructorDeclaration.declarationSourceEnd = offset + length - 1; constructorDeclaration.bodyStart = offset; constructorDeclaration.bodyEnd = offset + length - 1; parser.scanner.setSource(compilationResult); parser.scanner.resetTo(offset, offset + length); parser.parse(constructorDeclaration, compilationUnitDeclaration, true); if (recordParsingInformation) { this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments); } return constructorDeclaration; }
// 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 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/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 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, 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 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/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, 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 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/core/JavaCore.java
public static IResource[] getGeneratedResources(IRegion region, boolean includesNonJavaResources) { if (region == null) throw new IllegalArgumentException("region cannot be null"); //$NON-NLS-1$ IJavaElement[] elements = region.getElements(); HashMap projectsStates = new HashMap(); ArrayList collector = new ArrayList(); for (int i = 0, max = elements.length; i < max; i++) { // collect all the java project IJavaElement element = elements[i]; IJavaProject javaProject = element.getJavaProject(); IProject project = javaProject.getProject(); State state = null; State currentState = (State) projectsStates.get(project); if (currentState != null) { state = currentState; } else { state = (State) JavaModelManager.getJavaModelManager().getLastBuiltState(project, null); if (state != null) { projectsStates.put(project, state); } } if (state == null) continue; if (element.getElementType() == IJavaElement.JAVA_PROJECT) { IPackageFragmentRoot[] roots = null; try { roots = javaProject.getPackageFragmentRoots(); } catch (JavaModelException e) { // ignore } if (roots == null) continue; IRegion region2 = JavaCore.newRegion(); for (int j = 0; j < roots.length; j++) { region2.add(roots[j]); } IResource[] res = getGeneratedResources(region2, includesNonJavaResources); for (int j = 0, max2 = res.length; j < max2; j++) { collector.add(res[j]); } continue; } IPath outputLocation = null; try { outputLocation = javaProject.getOutputLocation(); } catch (JavaModelException e) { // ignore } IJavaElement root = element; while (root != null && root.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) { root = root.getParent(); } if (root == null) continue; IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) root; int rootPathSegmentCounts = packageFragmentRoot.getPath().segmentCount(); try { IClasspathEntry entry = packageFragmentRoot.getRawClasspathEntry(); IPath entryOutputLocation = entry.getOutputLocation(); if (entryOutputLocation != null) { outputLocation = entryOutputLocation; } } catch (JavaModelException e) { e.printStackTrace(); } if (outputLocation == null) continue; IContainer container = (IContainer) project.getWorkspace().getRoot().findMember(outputLocation); switch(element.getElementType()) { case IJavaElement.COMPILATION_UNIT : // get the .class files generated when this element was built ICompilationUnit unit = (ICompilationUnit) element; getGeneratedResource(unit, container, state, rootPathSegmentCounts, collector); break; case IJavaElement.PACKAGE_FRAGMENT : // collect all the .class files generated when all the units in this package were built IPackageFragment fragment = (IPackageFragment) element; ICompilationUnit[] compilationUnits = null; try { compilationUnits = fragment.getCompilationUnits(); } catch (JavaModelException e) { // ignore } if (compilationUnits == null) continue; for (int j = 0, max2 = compilationUnits.length; j < max2; j++) { getGeneratedResource(compilationUnits[j], container, state, rootPathSegmentCounts, collector); } if (includesNonJavaResources) { // retrieve all non-java resources from the output location using the package fragment path Object[] nonJavaResources = null; try { nonJavaResources = fragment.getNonJavaResources(); } catch (JavaModelException e) { // ignore } if (nonJavaResources != null) { addNonJavaResources(nonJavaResources, container, rootPathSegmentCounts, collector); } } break; case IJavaElement.PACKAGE_FRAGMENT_ROOT : // collect all the .class files generated when all the units in this package were built IPackageFragmentRoot fragmentRoot = (IPackageFragmentRoot) element; if (fragmentRoot.isArchive()) continue; IJavaElement[] children = null; try { children = fragmentRoot.getChildren(); } catch (JavaModelException e) { // ignore } if (children == null) continue; for (int j = 0, max2 = children.length; j < max2; j++) { fragment = (IPackageFragment) children[j]; ICompilationUnit[] units = null; try { units = fragment.getCompilationUnits(); } catch (JavaModelException e) { // ignore } if (units == null) continue; for (int n = 0, max3 = units.length; n < max3; n++) { getGeneratedResource(units[n], container, state, rootPathSegmentCounts, collector); } if (includesNonJavaResources) { // retrieve all non-java resources from the output location using the package fragment path Object[] nonJavaResources = null; try { nonJavaResources = fragment.getNonJavaResources(); } catch (JavaModelException e) { // ignore } if (nonJavaResources != null) { addNonJavaResources(nonJavaResources, container, rootPathSegmentCounts, collector); } } } break; } } int size = collector.size(); if (size != 0) { IResource[] result = new IResource[size]; collector.toArray(result); return result; } return NO_GENERATED_RESOURCES; }
// 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/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/CorrectionEngine.java
private void computeCorrections(ICompilationUnit unit, int id, int start, int end, String[] arguments, ICorrectionRequestor requestor) { if(id == -1 || arguments == null || start == -1 || end == -1) return; if (requestor == null) { throw new IllegalArgumentException(Messages.correction_nullRequestor); } this.correctionRequestor = requestor; this.correctionStart = start; this.correctionEnd = end; this.compilationUnit = unit; String argument = null; try { switch (id) { // Type correction case IProblem.ImportNotFound : this.filter = IMPORT; argument = arguments[0]; break; case IProblem.UndefinedType : this.filter = CLASSES | INTERFACES; argument = arguments[0]; break; // Method correction case IProblem.UndefinedMethod : this.filter = METHOD; argument = arguments[1]; break; // Field and local variable correction case IProblem.UndefinedField : this.filter = FIELD; argument = arguments[0]; break; case IProblem.UndefinedName : case IProblem.UnresolvedVariable : this.filter = FIELD | LOCAL; argument = arguments[0]; break; } } catch (ArrayIndexOutOfBoundsException e) { return; } if(argument != null) { correct(argument.toCharArray()); } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendArrayTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_ARRAY) { throw new IllegalArgumentException(); } int index = start; c = string[++index]; while(c == C_ARRAY) { // need a minimum 2 char if (index >= length - 1) { throw new IllegalArgumentException(); } c = string[++index]; } int e = appendTypeSignature(string, index, fullyQualifyTypeNames, buffer); 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; }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendCaptureTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_CAPTURE) { throw new IllegalArgumentException(); } buffer.append(CAPTURE).append(' '); return appendTypeArgumentSignature(string, start + 1, fullyQualifyTypeNames, buffer); }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendClassTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != C_RESOLVED && c != C_UNRESOLVED) { throw new IllegalArgumentException(); } boolean resolved = (c == C_RESOLVED); boolean removePackageQualifiers = !fullyQualifyTypeNames; if (!resolved) { // keep everything in an unresolved name removePackageQualifiers = false; } int p = start + 1; int checkpoint = buffer.length(); int innerTypeStart = -1; boolean inAnonymousType = false; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; switch(c) { case C_SEMICOLON : // all done return p; case C_GENERIC_START : int e = appendTypeArgumentSignatures(string, p, fullyQualifyTypeNames, buffer); // once we hit type arguments there are no more package prefixes removePackageQualifiers = false; p = e; break; case C_DOT : if (removePackageQualifiers) { // erase package prefix buffer.setLength(checkpoint); } else { buffer.append('.'); } break; case '/' : if (removePackageQualifiers) { // erase package prefix buffer.setLength(checkpoint); } else { buffer.append('/'); } break; case C_DOLLAR : innerTypeStart = buffer.length(); inAnonymousType = false; if (resolved) { // once we hit "$" there are no more package prefixes removePackageQualifiers = false; /** * Convert '$' in resolved type signatures into '.'. * NOTE: This assumes that the type signature is an inner type * signature. This is true in most cases, but someone can define a * non-inner type name containing a '$'. */ buffer.append('.'); } break; default : if (innerTypeStart != -1 && !inAnonymousType && Character.isDigit(c)) { inAnonymousType = true; buffer.setLength(innerTypeStart); // remove '.' buffer.insert(checkpoint, "new "); //$NON-NLS-1$ buffer.append("(){}"); //$NON-NLS-1$ } if (!inAnonymousType) buffer.append(c); innerTypeStart = -1; } p++; } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendIntersectionTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_INTERSECTION) { throw new IllegalArgumentException(); } start = appendClassTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); if (start < string.length - 1) { start++; if (string[start] != C_COLON) { throw new IllegalArgumentException("should be a colon at this location"); //$NON-NLS-1$ } while (string[start] == C_COLON) { buffer.append(" | "); //$NON-NLS-1$ start = appendClassTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); if (start == string.length - 1) { return start; } else if (start > string.length - 1) { throw new IllegalArgumentException("Should be at the end"); //$NON-NLS-1$ } start++; } } return start; }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeArgumentSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch(c) { case C_STAR : buffer.append('?'); return start; case C_EXTENDS : buffer.append("? extends "); //$NON-NLS-1$ return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); case C_SUPER : buffer.append("? super "); //$NON-NLS-1$ return appendTypeSignature(string, start + 1, fullyQualifyTypeNames, buffer); default : return appendTypeSignature(string, start, fullyQualifyTypeNames, buffer); } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeArgumentSignatures(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer) { // need a minimum 2 char "<>" if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } buffer.append('<'); int p = start + 1; int count = 0; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_GENERIC_END) { buffer.append('>'); return p; } if (count != 0) { buffer.append(','); } int e = appendTypeArgumentSignature(string, p, fullyQualifyTypeNames, buffer); count++; p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
private static int appendTypeSignature(char[] string, int start, boolean fullyQualifyTypeNames, StringBuffer buffer, boolean isVarArgs) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; if (isVarArgs) { switch (c) { case C_ARRAY : return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer, true); case C_RESOLVED : case C_UNRESOLVED : case C_TYPE_VARIABLE : case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : case C_STAR: case C_EXTENDS: case C_SUPER: case C_CAPTURE: case C_INTERSECTION : default: throw new IllegalArgumentException(); // a var args is an array type } } else { switch (c) { case C_ARRAY : return appendArrayTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_RESOLVED : case C_UNRESOLVED : return appendClassTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_TYPE_VARIABLE : int e = Util.scanTypeVariableSignature(string, start); buffer.append(string, start + 1, e - start - 1); return e; case C_BOOLEAN : buffer.append(BOOLEAN); return start; case C_BYTE : buffer.append(BYTE); return start; case C_CHAR : buffer.append(CHAR); return start; case C_DOUBLE : buffer.append(DOUBLE); return start; case C_FLOAT : buffer.append(FLOAT); return start; case C_INT : buffer.append(INT); return start; case C_LONG : buffer.append(LONG); return start; case C_SHORT : buffer.append(SHORT); return start; case C_VOID : buffer.append(VOID); return start; case C_CAPTURE : return appendCaptureTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_INTERSECTION : return appendIntersectionTypeSignature(string, start, fullyQualifyTypeNames, buffer); case C_STAR: case C_EXTENDS: case C_SUPER: return appendTypeArgumentSignature(string, start, fullyQualifyTypeNames, buffer); default : throw new IllegalArgumentException(); } } }
// in model/org/eclipse/jdt/core/Signature.java
private static int checkNextChar(char[] typeName, char expectedChar, int pos, int length, boolean isOptional) { pos = consumeWhitespace(typeName, pos, length); if (pos < length && typeName[pos] == expectedChar) return pos + 1; if (!isOptional) throw new IllegalArgumentException(new String(typeName)); return -1; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) { if (typeName == null) throw new IllegalArgumentException("null"); //$NON-NLS-1$ int length = typeName.length; if (length == 0) throw new IllegalArgumentException(new String(typeName)); StringBuffer buffer = new StringBuffer(5); int pos = encodeTypeSignature(typeName, 0, isResolved, length, buffer); pos = consumeWhitespace(typeName, pos, length); if (pos < length) throw new IllegalArgumentException(new String(typeName)); char[] result = new char[length = buffer.length()]; buffer.getChars(0, length, result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
private static int encodeQualifiedName(char[] typeName, int pos, int length, StringBuffer buffer) { int count = 0; char lastAppendedChar = 0; nameLoop: while (pos < length) { char currentChar = typeName[pos]; switch (currentChar) { case '<' : case '>' : case '[' : case ',' : break nameLoop; case '.' : buffer.append(C_DOT); lastAppendedChar = C_DOT; count++; break; default: if (currentChar == ' ' || ScannerHelper.isWhitespace(currentChar)) { if (lastAppendedChar == C_DOT) { // allow spaces after a dot pos = consumeWhitespace(typeName, pos, length) - 1; // will be incremented break; } // allow spaces before a dot int checkPos = checkNextChar(typeName, '.', pos, length, true); if (checkPos > 0) { buffer.append(C_DOT); // process dot immediately to avoid one iteration lastAppendedChar = C_DOT; count++; pos = checkPos; break; } break nameLoop; } buffer.append(currentChar); lastAppendedChar = currentChar; count++; break; } pos++; } if (count == 0) throw new IllegalArgumentException(new String(typeName)); return pos; }
// in model/org/eclipse/jdt/core/Signature.java
private static int encodeTypeSignature(char[] typeName, int start, boolean isResolved, int length, StringBuffer buffer) { int pos = start; pos = consumeWhitespace(typeName, pos, length); if (pos >= length) throw new IllegalArgumentException(new String(typeName)); int checkPos; char currentChar = typeName[pos]; switch (currentChar) { // primitive type? case 'b' : checkPos = checkName(BOOLEAN, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_BOOLEAN); return pos; } checkPos = checkName(BYTE, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_BYTE); return pos; } break; case 'd': checkPos = checkName(DOUBLE, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_DOUBLE); return pos; } break; case 'f': checkPos = checkName(FLOAT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_FLOAT); return pos; } break; case 'i': checkPos = checkName(INT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_INT); return pos; } break; case 'l': checkPos = checkName(LONG, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_LONG); return pos; } break; case 's': checkPos = checkName(SHORT, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_SHORT); return pos; } break; case 'v': checkPos = checkName(VOID, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_VOID); return pos; } break; case 'c': checkPos = checkName(CHAR, typeName, pos, length); if (checkPos > 0) { pos = encodeArrayDimension(typeName, checkPos, length, buffer); buffer.append(C_CHAR); return pos; } else { checkPos = checkName(CAPTURE, typeName, pos, length); if (checkPos > 0) { pos = consumeWhitespace(typeName, checkPos, length); if (typeName[pos] != '?') { break; } } else { break; } } buffer.append(C_CAPTURE); //$FALL-THROUGH$ for wildcard part of capture typecheckPos case '?': // wildcard pos = consumeWhitespace(typeName, pos+1, length); checkPos = checkName(EXTENDS, typeName, pos, length); if (checkPos > 0) { buffer.append(C_EXTENDS); pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); return pos; } checkPos = checkName(SUPER, typeName, pos, length); if (checkPos > 0) { buffer.append(C_SUPER); pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); return pos; } buffer.append(C_STAR); return pos; } // non primitive type checkPos = checkArrayDimension(typeName, pos, length); int end; if (checkPos > 0) { end = encodeArrayDimension(typeName, checkPos, length, buffer); } else { end = -1; } buffer.append(isResolved ? C_RESOLVED : C_UNRESOLVED); while (true) { // loop on qualifiedName[<args>][.qualifiedName[<args>]* pos = encodeQualifiedName(typeName, pos, length, buffer); checkPos = checkNextChar(typeName, '<', pos, length, true); if (checkPos > 0) { buffer.append(C_GENERIC_START); // Stop gap fix for <>. if ((pos = checkNextChar(typeName, '>', checkPos, length, true)) > 0) { buffer.append(C_GENERIC_END); } else { pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); while ((checkPos = checkNextChar(typeName, ',', pos, length, true)) > 0) { pos = encodeTypeSignature(typeName, checkPos, isResolved, length, buffer); } pos = checkNextChar(typeName, '>', pos, length, false); buffer.append(C_GENERIC_END); } } checkPos = checkNextChar(typeName, '.', pos, length, true); if (checkPos > 0) { buffer.append(C_DOT); pos = checkPos; } else { break; } } buffer.append(C_NAME_END); if (end > 0) pos = end; // skip array dimension which were preprocessed return pos; }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { try { int count = 0; while (typeSignature[count] == C_ARRAY) { ++count; } return count; } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getIntersectionTypeBounds(char[] intersectionTypeSignature) throws IllegalArgumentException { if (getTypeSignatureKind(intersectionTypeSignature) != INTERSECTION_TYPE_SIGNATURE) { return CharOperation.NO_CHAR_CHAR; } ArrayList args = new ArrayList(); int i = 1; // skip the '|' int length = intersectionTypeSignature.length; for (;;) { int e = Util.scanClassTypeSignature(intersectionTypeSignature, i); if (e < 0) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } args.add(CharOperation.subarray(intersectionTypeSignature, i, e + 1)); if (e == length - 1) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } else if (intersectionTypeSignature[e + 1] != C_COLON) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } i = e + 2; // add one to skip C_COLON } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { try { int count = getParameterCount(methodSignature); char[][] result = new char[count][]; if (count == 0) { return result; } int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } int t = 0; for (;;) { if (methodSignature[i] == C_PARAM_END) { return result; } int e = Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } result[t] = CharOperation.subarray(methodSignature, i, e + 1); t++; i = e + 1; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // there could be thrown exceptions behind, thus scan one type exactly int last = Util.scanTypeSignature(methodSignature, paren+1); return CharOperation.subarray(methodSignature, paren + 1, last+1); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getThrownExceptionTypes(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int exceptionStart = CharOperation.indexOf(C_EXCEPTION_START, methodSignature); if (exceptionStart == -1) { int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // ignore return type exceptionStart = Util.scanTypeSignature(methodSignature, paren+1) + 1; int length = methodSignature.length; if (exceptionStart == length) return CharOperation.NO_CHAR_CHAR; throw new IllegalArgumentException(); } int length = methodSignature.length; int i = exceptionStart; ArrayList exceptionList = new ArrayList(1); while (i < length) { if (methodSignature[i] == C_EXCEPTION_START) { exceptionStart++; i++; } else { throw new IllegalArgumentException(); } i = Util.scanTypeSignature(methodSignature, i) + 1; exceptionList.add(CharOperation.subarray(methodSignature, exceptionStart,i)); exceptionStart = i; } char[][] result; exceptionList.toArray(result = new char[exceptionList.size()][]); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeArguments(char[] parameterizedTypeSignature) throws IllegalArgumentException { int length = parameterizedTypeSignature.length; if (length < 2 || parameterizedTypeSignature[length-2] != C_GENERIC_END) // cannot have type arguments otherwise signature would end by ">;" return CharOperation.NO_CHAR_CHAR; int count = 1; // start to count generic end/start peers int start = length - 2; while (start >= 0 && count > 0) { switch (parameterizedTypeSignature[--start]) { case C_GENERIC_START: count--; break; case C_GENERIC_END: count++; break; } } if (start < 0) // invalid number of generic start/end throw new IllegalArgumentException(); ArrayList args = new ArrayList(); int p = start + 1; while (true) { if (p >= parameterizedTypeSignature.length) { throw new IllegalArgumentException(); } char c = parameterizedTypeSignature[p]; if (c == C_GENERIC_END) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } int e = Util.scanTypeArgumentSignature(parameterizedTypeSignature, p); args.add(CharOperation.subarray(parameterizedTypeSignature, p, e+1)); p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeErasure(char[] parameterizedTypeSignature) throws IllegalArgumentException { int end = CharOperation.indexOf(C_GENERIC_START, parameterizedTypeSignature); if (end == -1) return parameterizedTypeSignature; int length = parameterizedTypeSignature.length; char[] result = new char[length]; int pos = 0; int start = 0; int deep= 0; for (int idx=end; idx<length; idx++) { switch (parameterizedTypeSignature[idx]) { case C_GENERIC_START: if (deep == 0) { int size = idx-start; System.arraycopy(parameterizedTypeSignature, start, result, pos, size); end = idx; pos += size; } deep++; break; case C_GENERIC_END: deep--; if (deep < 0) throw new IllegalArgumentException(); if (deep == 0) start = idx+1; break; } } if (deep > 0) throw new IllegalArgumentException(); int size = pos+length-start; char[] resized = new char[size]; System.arraycopy(result, 0, resized, 0, pos); System.arraycopy(parameterizedTypeSignature, start, resized, pos, length-start); return resized; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p1 < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } if (p1 == formalTypeParameterSignature.length - 1) { // no class or interface bounds return CharOperation.NO_CHAR_CHAR; } int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); char[] classBound; if (p2 < 0) { // no interface bounds classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); return new char[][] {classBound}; } if (p2 == p1 + 1) { // no class bound, but 1 or more interface bounds classBound = null; } else { classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); } char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); if (classBound == null) { return interfaceBounds; } int resultLength = interfaceBounds.length + 1; char[][] result = new char[resultLength][]; result[0] = classBound; System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { try { int length = methodOrTypeSignature.length; if (length == 0) return CharOperation.NO_CHAR_CHAR; if (methodOrTypeSignature[0] != C_GENERIC_START) return CharOperation.NO_CHAR_CHAR; ArrayList paramList = new ArrayList(1); int paramStart = 1, i = 1; // start after leading '<' while (i < length) { if (methodOrTypeSignature[i] == C_GENERIC_END) { int size = paramList.size(); if (size == 0) throw new IllegalArgumentException(); char[][] result; paramList.toArray(result = new char[size][]); return result; } i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); if (i < 0 || i >= length) throw new IllegalArgumentException(); // iterate over bounds while (methodOrTypeSignature[i] == ':') { i++; // skip colon switch (methodOrTypeSignature[i]) { case ':': // no class bound break; case C_GENERIC_END: break; case C_RESOLVED: try { i = Util.scanClassTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter } break; case C_ARRAY: try { i = Util.scanArrayTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter } break; case C_TYPE_VARIABLE: try { i = Util.scanTypeVariableSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter } break; // default: another type parameter is starting } } paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); paramStart = i; // next param start from here } } catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through } throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
public static int getTypeSignatureKind(char[] typeSignature) { // need a minimum 1 char if (typeSignature.length < 1) { throw new IllegalArgumentException(); } char c = typeSignature[0]; if (c == C_GENERIC_START) { int count = 1; for (int i = 1, length = typeSignature.length; i < length; i++) { switch (typeSignature[i]) { case C_GENERIC_START: count++; break; case C_GENERIC_END: count--; break; } if (count == 0) { if (i+1 < length) c = typeSignature[i+1]; break; } } } switch (c) { case C_ARRAY : return ARRAY_TYPE_SIGNATURE; case C_RESOLVED : case C_UNRESOLVED : return CLASS_TYPE_SIGNATURE; case C_TYPE_VARIABLE : return TYPE_VARIABLE_SIGNATURE; case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : return BASE_TYPE_SIGNATURE; case C_STAR : case C_SUPER : case C_EXTENDS : return WILDCARD_TYPE_SIGNATURE; case C_CAPTURE : return CAPTURE_TYPE_SIGNATURE; case C_INTERSECTION : return INTERSECTION_TYPE_SIGNATURE; default : throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeVariable(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } return CharOperation.subarray(formalTypeParameterSignature, 0, p); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] signature) throws IllegalArgumentException { int sigLength = signature.length; if (sigLength == 0) { throw new IllegalArgumentException(); } if (signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); } StringBuffer buffer = new StringBuffer(signature.length + 10); appendTypeSignature(signature, 0, true, buffer); char[] result = new char[buffer.length()]; buffer.getChars(0, buffer.length(), result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType, boolean isVargArgs) { int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); if (firstParen == -1) { throw new IllegalArgumentException(); } StringBuffer buffer = new StringBuffer(methodSignature.length + 10); // return type if (includeReturnType) { char[] rts = getReturnType(methodSignature); appendTypeSignature(rts, 0 , fullyQualifyTypeNames, buffer); buffer.append(' '); } // selector if (methodName != null) { buffer.append(methodName); } // parameters buffer.append('('); char[][] pts = getParameterTypes(methodSignature); // search for the last array in the signature int max = pts.length; int index = max - 1; loop: for (int i = index; i >= 0; i--) { if (pts[i][0] == Signature.C_ARRAY) { break loop; } index--; } for (int i = 0; i < max; i++) { if (i == index) { appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer, isVargArgs); } else { appendTypeSignature(pts[i], 0 , fullyQualifyTypeNames, buffer); } if (parameterNames != null) { buffer.append(' '); buffer.append(parameterNames[i]); } 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; }
// in model/org/eclipse/jdt/core/util/CompilationUnitSorter.java
private static void checkASTLevel(int level) { switch (level) { case AST.JLS2 : case AST.JLS3 : case AST.JLS4 : break; default : throw new IllegalArgumentException(); } }
// 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/CompletionRequestor.java
public boolean isIgnored(int completionProposalKind) { if (completionProposalKind < CompletionProposal.FIRST_KIND || completionProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$ } return 0 != (this.ignoreSet & (1 << completionProposalKind)); }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public void setIgnored(int completionProposalKind, boolean ignore) { if (completionProposalKind < CompletionProposal.FIRST_KIND || completionProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+completionProposalKind); //$NON-NLS-1$ } if (ignore) { this.ignoreSet |= (1 << completionProposalKind); } else { this.ignoreSet &= ~(1 << completionProposalKind); } }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public boolean isAllowingRequiredProposals(int proposalKind, int requiredProposalKind) { if (proposalKind < CompletionProposal.FIRST_KIND || proposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (requiredProposalKind < CompletionProposal.FIRST_KIND || requiredProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (this.requiredProposalAllowSet == null) return false; return 0 != (this.requiredProposalAllowSet[proposalKind] & (1 << requiredProposalKind)); }
// in model/org/eclipse/jdt/core/CompletionRequestor.java
public void setAllowsRequiredProposals(int proposalKind, int requiredProposalKind, boolean allow) { if (proposalKind < CompletionProposal.FIRST_KIND || proposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (requiredProposalKind < CompletionProposal.FIRST_KIND || requiredProposalKind > CompletionProposal.LAST_KIND) { throw new IllegalArgumentException("Unknown required kind of completion proposal: "+requiredProposalKind); //$NON-NLS-1$ } if (this.requiredProposalAllowSet == null) { this.requiredProposalAllowSet = new int[CompletionProposal.LAST_KIND + 1]; } if (allow) { this.requiredProposalAllowSet[proposalKind] |= (1 << requiredProposalKind); } else { this.requiredProposalAllowSet[proposalKind] &= ~(1 << requiredProposalKind); } }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) { int length= string.length(); if (0 < 0 || length < 0 || 0 + length > string.length()) { throw new IllegalArgumentException("offset or length outside of string. offset: " + 0 + ", length: " + length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } return ToolFactory.createCodeFormatter(options).format(kind, string, 0, length, indentationLevel, lineSeparator); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException { Document doc= new Document(content); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { if (this.fOffset < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < this.fOffset + this.fLength)) { this.fPosition.offset= this.fOffset + this.fLength; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public String createIndentationString(final int indentationLevel) { if (indentationLevel < 0) { throw new IllegalArgumentException(); } int tabs = 0; int spaces = 0; switch(this.preferences.tab_char) { case DefaultCodeFormatterOptions.SPACE : spaces = indentationLevel * this.preferences.tab_size; break; case DefaultCodeFormatterOptions.TAB : tabs = indentationLevel; break; case DefaultCodeFormatterOptions.MIXED : int tabSize = this.preferences.tab_size; if (tabSize != 0) { int spaceEquivalents = indentationLevel * this.preferences.indentation_size; tabs = spaceEquivalents / tabSize; spaces = spaceEquivalents % tabSize; } break; default: return Util.EMPTY_STRING; } if (tabs == 0 && spaces == 0) { return Util.EMPTY_STRING; } StringBuffer buffer = new StringBuffer(tabs + spaces); for(int i = 0; i < tabs; i++) { buffer.append('\t'); } for(int i = 0; i < spaces; i++) { buffer.append(' '); } return buffer.toString(); }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { if (offset < 0 || length < 0 || length > source.length()) { throw new IllegalArgumentException(); } switch(kind & K_MASK) { case K_JAVA_DOC : // https://bugs.eclipse.org/bugs/show_bug.cgi?id=102780 // use the integrated comment formatter to format comment return formatComment(kind & K_MASK, source, indentationLevel, lineSeparator, new IRegion[] {new Region(offset, length)}); // $FALL-THROUGH$ - fall through next case when old comment formatter is activated case K_MULTI_LINE_COMMENT : case K_SINGLE_LINE_COMMENT : return formatComment(kind & K_MASK, source, indentationLevel, lineSeparator, new IRegion[] {new Region(offset, length)}); } return format(kind, source, new IRegion[] {new Region(offset, length)}, indentationLevel, lineSeparator); }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
public TextEdit format(int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) { if (!regionsSatisfiesPreconditions(regions, source.length())) { throw new IllegalArgumentException(); } this.codeSnippetParsingUtil = new CodeSnippetParsingUtil(); boolean includeComments = (kind & F_INCLUDE_COMMENTS) != 0; switch(kind & K_MASK) { case K_CLASS_BODY_DECLARATIONS : return formatClassBodyDeclarations(source, indentationLevel, lineSeparator, regions, includeComments); case K_COMPILATION_UNIT : return formatCompilationUnit(source, indentationLevel, lineSeparator, regions, includeComments); case K_EXPRESSION : return formatExpression(source, indentationLevel, lineSeparator, regions, includeComments); case K_STATEMENTS : return formatStatements(source, indentationLevel, lineSeparator, regions, includeComments); case K_UNKNOWN : return probeFormatting(source, indentationLevel, lineSeparator, regions, includeComments); case K_JAVA_DOC : case K_MULTI_LINE_COMMENT : case K_SINGLE_LINE_COMMENT : //https://bugs.eclipse.org/bugs/show_bug.cgi?id=204091 throw new IllegalArgumentException(); } return null; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int measureIndentUnits(CharSequence line, int tabWidth, int indentWidth) { if (indentWidth < 0 || tabWidth < 0 || line == null) { throw new IllegalArgumentException(); } if (indentWidth == 0) return 0; int visualLength= measureIndentInSpaces(line, tabWidth); return visualLength / indentWidth; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int measureIndentInSpaces(CharSequence line, int tabWidth) { if (tabWidth < 0 || line == null) { throw new IllegalArgumentException(); } int length= 0; int max= line.length(); for (int i= 0; i < max; i++) { char ch= line.charAt(i); if (ch == '\t') { length = calculateSpaceEquivalents(tabWidth, length); } else if (isIndentChar(ch)) { length++; } else { return length; } } return length; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String extractIndentString(String line, int tabWidth, int indentWidth) { if (tabWidth < 0 || indentWidth < 0 || line == null) { throw new IllegalArgumentException(); } int size = line.length(); int end = 0; int spaceEquivs = 0; int characters = 0; for (int i = 0; i < size; i++) { char c = line.charAt(i); if (c == '\t') { spaceEquivs = calculateSpaceEquivalents(tabWidth, spaceEquivs); characters++; } else if (isIndentChar(c)) { spaceEquivs++; characters++; } else { break; } if (spaceEquivs >= indentWidth) { end += characters; characters = 0; if(indentWidth == 0) { spaceEquivs = 0; } else { spaceEquivs = spaceEquivs % indentWidth; } } } if (end == 0) { return Util.EMPTY_STRING; } else if (end == size) { return line; } else { return line.substring(0, end); } }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String trimIndent(String line, int indentUnitsToRemove, int tabWidth, int indentWidth) { if (tabWidth < 0 || indentWidth < 0 || line == null) { throw new IllegalArgumentException(); } if (indentUnitsToRemove <= 0 || indentWidth == 0) { return line; } final int spaceEquivalentsToRemove= indentUnitsToRemove * indentWidth; int start= 0; int spaceEquivalents= 0; int size= line.length(); String prefix= null; for (int i= 0; i < size; i++) { char c= line.charAt(i); if (c == '\t') { spaceEquivalents = calculateSpaceEquivalents(tabWidth, spaceEquivalents); } else if (isIndentChar(c)) { spaceEquivalents++; } else { // Assert.isTrue(false, "Line does not have requested number of indents"); start= i; break; } if (spaceEquivalents == spaceEquivalentsToRemove) { start= i + 1; break; } if (spaceEquivalents > spaceEquivalentsToRemove) { // can happen if tabSize > indentSize, e.g tabsize==8, indent==4, indentsToRemove==1, line prefixed with one tab // this implements the third option start= i + 1; // remove the tab // and add the missing spaces char[] missing= new char[spaceEquivalents - spaceEquivalentsToRemove]; Arrays.fill(missing, ' '); prefix= new String(missing); break; } } String trimmed; if (start == size) trimmed= Util.EMPTY_STRING; else trimmed= line.substring(start); if (prefix == null) return trimmed; return prefix + trimmed; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static String changeIndent(String code, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString, String lineDelim) { if (tabWidth < 0 || indentWidth < 0 || code == null || indentUnitsToRemove < 0 || newIndentString == null || lineDelim == null) { throw new IllegalArgumentException(); } try { ILineTracker tracker= new DefaultLineTracker(); tracker.set(code); int nLines= tracker.getNumberOfLines(); if (nLines == 1) { return code; } StringBuffer buf= new StringBuffer(); for (int i= 0; i < nLines; i++) { IRegion region= tracker.getLineInformation(i); int start= region.getOffset(); int end= start + region.getLength(); String line= code.substring(start, end); if (i == 0) { // no indent for first line (contained in the formatted string) buf.append(line); } else { // no new line after last line buf.append(lineDelim); buf.append(newIndentString); if(indentWidth != 0) { buf.append(trimIndent(line, indentUnitsToRemove, tabWidth, indentWidth)); } else { buf.append(line); } } } return buf.toString(); } catch (BadLocationException e) { // can not happen return code; } }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static ReplaceEdit[] getChangeIndentEdits(String source, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString) { if (tabWidth < 0 || indentWidth < 0 || source == null || indentUnitsToRemove < 0 || newIndentString == null) { throw new IllegalArgumentException(); } ArrayList result= new ArrayList(); try { ILineTracker tracker= new DefaultLineTracker(); tracker.set(source); int nLines= tracker.getNumberOfLines(); if (nLines == 1) return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]); for (int i= 1; i < nLines; i++) { IRegion region= tracker.getLineInformation(i); int offset= region.getOffset(); String line= source.substring(offset, offset + region.getLength()); int length= indexOfIndent(line, indentUnitsToRemove, tabWidth, indentWidth); if (length >= 0) { result.add(new ReplaceEdit(offset, length, newIndentString)); } else { length= measureIndentUnits(line, tabWidth, indentWidth); result.add(new ReplaceEdit(offset, length, "")); //$NON-NLS-1$ } } } catch (BadLocationException cannotHappen) { // can not happen } return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int getTabWidth(Map options) { if (options == null) { throw new IllegalArgumentException(); } return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4); }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
public static int getIndentWidth(Map options) { if (options == null) { throw new IllegalArgumentException(); } int tabWidth=getTabWidth(options); boolean isMixedMode= DefaultCodeFormatterConstants.MIXED.equals(options.get(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)); if (isMixedMode) { return getIntValue(options, DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, tabWidth); } return tabWidth; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setTokenRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { throw new IllegalArgumentException(); } this.tokenStart = startIndex; this.tokenEnd = endIndex; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setReplaceRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { throw new IllegalArgumentException(); } this.replaceStart = startIndex; this.replaceEnd = endIndex; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
public void setRelevance(int rating) { if (rating <= 0) { throw new IllegalArgumentException(); } this.relevance = rating; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
private int getParametersCount(char[] methodSignature) { int i = CharOperation.indexOf('(', methodSignature); i++; char currentCharacter = methodSignature[i]; if (currentCharacter == ')') { return 0; } int result = 0; while (true) { currentCharacter = methodSignature[i]; if (currentCharacter == ')') { return result; } switch (currentCharacter) { case '[': // array type int scanType = scanType(methodSignature, i + 1); result++; i = scanType + 1; break; case 'L': scanType = CharOperation.indexOf(';', methodSignature, i + 1); result++; i = scanType + 1; break; case 'Z': case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': result++; i++; break; default: throw new IllegalArgumentException("Invalid starting type character : " + currentCharacter); //$NON-NLS-1$ } } }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
private int scanType(char[] methodSignature, int index) { switch (methodSignature[index]) { case '[': // array type return scanType(methodSignature, index + 1); case 'L': return CharOperation.indexOf(';', methodSignature, index + 1); case 'Z': case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': return index; default: throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/codegen/StackMapFrame.java
public void addStackItem(VerificationTypeInfo info) { if (info == null) { throw new IllegalArgumentException("info cannot be null"); //$NON-NLS-1$ } if (this.stackItems == null) { this.stackItems = new VerificationTypeInfo[1]; this.stackItems[0] = info; this.numberOfStackItems = 1; } else { final int length = this.stackItems.length; if (this.numberOfStackItems == length) { System.arraycopy(this.stackItems, 0, this.stackItems = new VerificationTypeInfo[length + 1], 0, length); } this.stackItems[this.numberOfStackItems++] = info; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int getParameterCount(char[] methodSignature) { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_ARRAY : return scanArrayTypeSignature(string, start); case C_RESOLVED : case C_UNRESOLVED : return scanClassTypeSignature(string, start); case C_TYPE_VARIABLE : return scanTypeVariableSignature(string, start); case C_BOOLEAN : case C_BYTE : case C_CHAR : case C_DOUBLE : case C_FLOAT : case C_INT : case C_LONG : case C_SHORT : case C_VOID : return scanBaseTypeSignature(string, start); case C_CAPTURE : return scanCaptureTypeSignature(string, start); case C_EXTENDS: case C_SUPER: case C_STAR: return scanTypeBoundSignature(string, start); default : throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanBaseTypeSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; if ("BCDFIJSVZ".indexOf(c) >= 0) { //$NON-NLS-1$ return start; } else { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanArrayTypeSignature(char[] string, int start) { int length = string.length; // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_ARRAY) { throw new IllegalArgumentException(); } c = string[++start]; while(c == C_ARRAY) { // need a minimum 2 char if (start >= length - 1) { throw new IllegalArgumentException(); } c = string[++start]; } return scanTypeSignature(string, start); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanCaptureTypeSignature(char[] string, int start) { // need a minimum 2 char if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_CAPTURE) { throw new IllegalArgumentException(); } return scanTypeBoundSignature(string, start + 1); }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeVariableSignature(char[] string, int start) { // need a minimum 3 chars "Tx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "T" char c = string[start]; if (c != C_TYPE_VARIABLE) { throw new IllegalArgumentException(); } int id = scanIdentifier(string, start + 1); c = string[id + 1]; if (c == C_SEMICOLON) { return id + 1; } else { throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanIdentifier(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } int p = start; while (true) { char c = string[p]; if (c == '<' || c == '>' || c == ':' || c == ';' || c == '.' || c == '/') { return p - 1; } p++; if (p == string.length) { return p - 1; } } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanClassTypeSignature(char[] string, int start) { // need a minimum 3 chars "Lx;" if (start >= string.length - 2) { throw new IllegalArgumentException(); } // must start in "L" or "Q" char c = string[start]; if (c != C_RESOLVED && c != C_UNRESOLVED) { return -1; } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_SEMICOLON) { // all done return p; } else if (c == C_GENERIC_START) { int e = scanTypeArgumentSignatures(string, p); p = e; } else if (c == C_DOT || c == '/') { int id = scanIdentifier(string, p + 1); p = id; } p++; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeBoundSignature(char[] string, int start) { // need a minimum 1 char for wildcard if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_STAR : return start; case C_SUPER : case C_EXTENDS : // need a minimum 3 chars "+[I" if (start >= string.length - 2) { throw new IllegalArgumentException(); } break; default : // must start in "+/-" throw new IllegalArgumentException(); } c = string[++start]; switch (c) { case C_CAPTURE : return scanCaptureTypeSignature(string, start); case C_SUPER : case C_EXTENDS : return scanTypeBoundSignature(string, start); case C_RESOLVED : case C_UNRESOLVED : return scanClassTypeSignature(string, start); case C_TYPE_VARIABLE : return scanTypeVariableSignature(string, start); case C_ARRAY : return scanArrayTypeSignature(string, start); case C_STAR: return start; default: throw new IllegalArgumentException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeArgumentSignatures(char[] string, int start) { // need a minimum 2 char "<>" if (start >= string.length - 1) { throw new IllegalArgumentException(); } char c = string[start]; if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length) { throw new IllegalArgumentException(); } c = string[p]; if (c == C_GENERIC_END) { return p; } int e = scanTypeArgumentSignature(string, p); p = e + 1; } }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static int scanTypeArgumentSignature(char[] string, int start) { // need a minimum 1 char if (start >= string.length) { throw new IllegalArgumentException(); } char c = string[start]; switch (c) { case C_STAR : return start; case C_EXTENDS : case C_SUPER : return scanTypeBoundSignature(string, start); default : return scanTypeSignature(string, start); } }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSetOfCharArray.java
public void asArray(Object[] copy) { if (this.elementSize != copy.length) throw new IllegalArgumentException(); int index = this.elementSize; for (int i = 0, l = this.values.length; i < l && index > 0; i++) if (this.values[i] != null) copy[--index] = this.values[i]; }
// in compiler/org/eclipse/jdt/internal/compiler/util/SimpleSet.java
public void asArray(Object[] copy) { if (this.elementSize != copy.length) throw new IllegalArgumentException(); int index = this.elementSize; for (int i = 0, l = this.values.length; i < l && index > 0; i++) if (this.values[i] != null) copy[--index] = this.values[i]; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public final void markAsTracked(ASTNode node, TextEditGroup editGroup) { if (getTrackedNodeData(node) != null) { throw new IllegalArgumentException("Node is already marked as tracked"); //$NON-NLS-1$ } setTrackedNodeData(node, editGroup); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public final CopySourceInfo createRangeCopy(ASTNode parent, StructuralPropertyDescriptor childProperty, ASTNode first, ASTNode last, boolean isMove, ASTNode internalPlaceholder, ASTNode replacingNode, TextEditGroup editGroup) { CopySourceInfo copyInfo= createCopySourceInfo(null, internalPlaceholder, isMove); internalPlaceholder.setProperty(INTERNAL_PLACEHOLDER_PROPERTY, internalPlaceholder); NodeRangeInfo copyRangeInfo= new NodeRangeInfo(parent, childProperty, first, last, copyInfo, replacingNode, editGroup); ListRewriteEvent listEvent= getListEvent(parent, childProperty, true); int indexFirst= listEvent.getIndex(first, ListRewriteEvent.OLD); if (indexFirst == -1) { throw new IllegalArgumentException("Start node is not a original child of the given list"); //$NON-NLS-1$ } int indexLast= listEvent.getIndex(last, ListRewriteEvent.OLD); if (indexLast == -1) { throw new IllegalArgumentException("End node is not a original child of the given list"); //$NON-NLS-1$ } if (indexFirst > indexLast) { throw new IllegalArgumentException("Start node must be before end node"); //$NON-NLS-1$ } if (this.nodeRangeInfos == null) { this.nodeRangeInfos= new HashMap(); } PropertyLocation loc= new PropertyLocation(parent, childProperty); List innerList= (List) this.nodeRangeInfos.get(loc); if (innerList == null) { innerList= new ArrayList(2); this.nodeRangeInfos.put(loc, innerList); } else { assertNoOverlap(listEvent, indexFirst, indexLast, innerList); } innerList.add(copyRangeInfo); return copyInfo; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void assertNoOverlap(ListRewriteEvent listEvent, int indexFirst, int indexLast, List innerList) { for (Iterator iter= innerList.iterator(); iter.hasNext();) { NodeRangeInfo curr= (NodeRangeInfo) iter.next(); int currStart= listEvent.getIndex(curr.getStartNode(), ListRewriteEvent.BOTH); int currEnd= listEvent.getIndex(curr.getEndNode(), ListRewriteEvent.BOTH); if (currStart < indexFirst && currEnd < indexLast && currEnd >= indexFirst || currStart > indexFirst && currStart <= currEnd && currEnd > indexLast) { throw new IllegalArgumentException("Range overlapps with an existing copy or move range"); //$NON-NLS-1$ } } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateIsListProperty(StructuralPropertyDescriptor property) { if (!property.isChildListProperty()) { String message= property.getId() + " is not a list property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateHasChildProperty(ASTNode parent, StructuralPropertyDescriptor property) { if (!parent.structuralPropertiesForType().contains(property)) { String message= Signature.getSimpleName(parent.getClass().getName()) + " has no property " + property.getId(); //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
private void validateIsNodeProperty(StructuralPropertyDescriptor property) { if (property.isChildListProperty()) { String message= property.getId() + " is not a node property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ListRewriteEvent.java
public RewriteEvent replaceEntry(ASTNode entry, ASTNode newEntry) { if (entry == null) { throw new IllegalArgumentException(); } List entries= getEntries(); int nEntries= entries.size(); for (int i= 0; i < nEntries; i++) { NodeRewriteEvent curr= (NodeRewriteEvent) entries.get(i); if (curr.getOriginalValue() == entry || curr.getNewValue() == entry) { curr.setNewValue(newEntry); if (curr.getNewValue() == null && curr.getOriginalValue() == null) { // removed an inserted node entries.remove(i); return null; } return curr; } } return null; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { Document doc= new Document(string); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { int start= this.fOffset; int end= start + this.fLength; if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) { this.fPosition.offset= end; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setOperator(Assignment.Operator assignmentOperator) { if (assignmentOperator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.assignmentOperator = assignmentOperator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setLeftHandSide(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an Assignment may occur inside a Expression - must check cycles ASTNode oldChild = this.leftHandSide; preReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY); this.leftHandSide = expression; postReplaceChild(oldChild, expression, LEFT_HAND_SIDE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Assignment.java
public void setRightHandSide(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an Assignment may occur inside a Expression - must check cycles ASTNode oldChild = this.rightHandSide; preReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY); this.rightHandSide = expression; postReplaceChild(oldChild, expression, RIGHT_HAND_SIDE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setName(SimpleName variableName) { if (variableName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.variableName; preReplaceChild(oldChild, variableName, NAME_PROPERTY); this.variableName = variableName; postReplaceChild(oldChild, variableName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleVariableDeclaration.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
public void setName(SimpleName methodName) { if (methodName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, methodName, NAME_PROPERTY); this.methodName = methodName; postReplaceChild(oldChild, methodName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
void internalSetReturnType(Type type) { supportedOnlyIn2(); if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.returnType; preReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY); this.returnType = type; postReplaceChild(oldChild, type, RETURN_TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodDeclaration.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedName.java
public void setQualifier(Name qualifier) { if (qualifier == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.qualifier; preReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY); this.qualifier = qualifier; postReplaceChild(oldChild, qualifier, QUALIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedName.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SimpleType.java
public void setName(Name typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, NAME_PROPERTY); this.typeName = typeName; postReplaceChild(oldChild, typeName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void remove(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } RewriteEvent event= getEvent().removeEntry(node); if (editGroup != null) { getRewriteStore().setEventEditGroup(event, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } RewriteEvent event= getEvent().replaceEntry(node, replacement); if (editGroup != null) { getRewriteStore().setEventEditGroup(event, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertAfter(ASTNode node, ASTNode previousElement, TextEditGroup editGroup) { if (node == null || previousElement == null) { throw new IllegalArgumentException(); } int index= getEvent().getIndex(previousElement, ListRewriteEvent.BOTH); if (index == -1) { throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$ } internalInsertAt(node, index + 1, true, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertBefore(ASTNode node, ASTNode nextElement, TextEditGroup editGroup) { if (node == null || nextElement == null) { throw new IllegalArgumentException(); } int index= getEvent().getIndex(nextElement, ListRewriteEvent.BOTH); if (index == -1) { throw new IllegalArgumentException("Node does not exist"); //$NON-NLS-1$ } internalInsertAt(node, index, false, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertFirst(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, 0, false, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertLast(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, -1, true, editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
public void insertAt(ASTNode node, int index, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } internalInsertAt(node, index, isInsertBoundToPreviousByDefault(node), editGroup); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ListRewrite.java
private ASTNode createTargetNode(ASTNode first, ASTNode last, boolean isMove, ASTNode replacingNode, TextEditGroup editGroup) { if (first == null || last == null) { throw new IllegalArgumentException(); } NodeInfoStore nodeStore= this.rewriter.getNodeStore(); ASTNode placeholder= nodeStore.newPlaceholderNode(first.getNodeType()); // revisit: could use list type if (placeholder == null) { throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + first.getClass().getName()); //$NON-NLS-1$ } Block internalPlaceHolder= nodeStore.createCollapsePlaceholder(); CopySourceInfo info= getRewriteStore().createRangeCopy(this.parent, this.childProperty, first, last, isMove, internalPlaceHolder, replacingNode, editGroup); nodeStore.markAsCopyTarget(placeholder, info); return placeholder; }
// 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/ImportRewrite.java
public static ImportRewrite create(CompilationUnit astRoot, boolean restoreExistingImports) { if (astRoot == null) { throw new IllegalArgumentException("AST must not be null"); //$NON-NLS-1$ } ITypeRoot typeRoot = astRoot.getTypeRoot(); if (!(typeRoot instanceof ICompilationUnit)) { throw new IllegalArgumentException("AST must have been constructed from a Java element"); //$NON-NLS-1$ } List existingImport= null; if (restoreExistingImports) { existingImport= new ArrayList(); List imports= astRoot.imports(); for (int i= 0; i < imports.size(); i++) { ImportDeclaration curr= (ImportDeclaration) imports.get(i); StringBuffer buf= new StringBuffer(); buf.append(curr.isStatic() ? STATIC_PREFIX : NORMAL_PREFIX).append(curr.getName().getFullyQualifiedName()); if (curr.isOnDemand()) { if (buf.length() > 1) buf.append('.'); buf.append('*'); } existingImport.add(buf.toString()); } } return new ImportRewrite((ICompilationUnit) typeRoot, astRoot, existingImport); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setImportOrder(String[] order) { if (order == null) throw new IllegalArgumentException("Order must not be null"); //$NON-NLS-1$ this.importOrder= order; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setOnDemandImportThreshold(int threshold) { if (threshold <= 0) throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$ this.importOnDemandThreshold= threshold; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public void setStaticOnDemandImportThreshold(int threshold) { if (threshold <= 0) throw new IllegalArgumentException("Threshold must be positive."); //$NON-NLS-1$ this.staticImportOnDemandThreshold= threshold; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public Type addImportFromSignature(String typeSig, AST ast, ImportRewriteContext context) { if (typeSig == null || typeSig.length() == 0) { throw new IllegalArgumentException("Invalid type signature: empty or null"); //$NON-NLS-1$ } int sigKind= Signature.getTypeSignatureKind(typeSig); switch (sigKind) { case Signature.BASE_TYPE_SIGNATURE: return ast.newPrimitiveType(PrimitiveType.toCode(Signature.toString(typeSig))); case Signature.ARRAY_TYPE_SIGNATURE: Type elementType= addImportFromSignature(Signature.getElementType(typeSig), ast, context); return ast.newArrayType(elementType, Signature.getArrayCount(typeSig)); case Signature.CLASS_TYPE_SIGNATURE: String erasureSig= Signature.getTypeErasure(typeSig); String erasureName= Signature.toString(erasureSig); if (erasureSig.charAt(0) == Signature.C_RESOLVED) { erasureName= internalAddImport(erasureName, context); } Type baseType= ast.newSimpleType(ast.newName(erasureName)); String[] typeArguments= Signature.getTypeArguments(typeSig); if (typeArguments.length > 0) { ParameterizedType type= ast.newParameterizedType(baseType); List argNodes= type.typeArguments(); for (int i= 0; i < typeArguments.length; i++) { String curr= typeArguments[i]; if (containsNestedCapture(curr)) { // see bug 103044 argNodes.add(ast.newWildcardType()); } else { argNodes.add(addImportFromSignature(curr, ast, context)); } } return type; } return baseType; case Signature.TYPE_VARIABLE_SIGNATURE: return ast.newSimpleType(ast.newSimpleName(Signature.toString(typeSig))); case Signature.WILDCARD_TYPE_SIGNATURE: WildcardType wildcardType= ast.newWildcardType(); char ch= typeSig.charAt(0); if (ch != Signature.C_STAR) { Type bound= addImportFromSignature(typeSig.substring(1), ast, context); wildcardType.setBound(bound, ch == Signature.C_EXTENDS); } return wildcardType; case Signature.CAPTURE_TYPE_SIGNATURE: return addImportFromSignature(typeSig.substring(1), ast, context); default: throw new IllegalArgumentException("Unknown type signature kind: " + typeSig); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ImportRewrite.java
public String addStaticImport(IBinding binding, ImportRewriteContext context) { if (Modifier.isStatic(binding.getModifiers())) { if (binding instanceof IVariableBinding) { IVariableBinding variableBinding= (IVariableBinding) binding; if (variableBinding.isField()) { ITypeBinding declaringType= variableBinding.getDeclaringClass(); return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), true, context); } } else if (binding instanceof IMethodBinding) { ITypeBinding declaringType= ((IMethodBinding) binding).getDeclaringClass(); return addStaticImport(getRawQualifiedName(declaringType), binding.getName(), false, context); } } throw new IllegalArgumentException("Binding must be a static field or method."); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException { if (document == null) { throw new IllegalArgumentException(); } ASTNode rootNode= getRootNode(); if (rootNode == null) { return new MultiTextEdit(); // no changes } char[] content= document.get().toCharArray(); LineInformation lineInfo= LineInformation.create(document); String lineDelim= TextUtilities.getDefaultLineDelimiter(document); ASTNode astRoot= rootNode.getRoot(); List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null; Map currentOptions = options == null ? JavaCore.getOptions() : options; return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData()); }
// 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/rewrite/ASTRewrite.java
public final void remove(ASTNode node, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } StructuralPropertyDescriptor property; ASTNode parent; if (RewriteEventStore.isNewNode(node)) { // remove a new node, bug 164862 PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW); if (location != null) { property= location.getProperty(); parent= location.getParent(); } else { throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ } } else { property= node.getLocationInParent(); parent= node.getParent(); } if (property.isChildListProperty()) { getListRewrite(parent, (ChildListPropertyDescriptor) property).remove(node, editGroup); } else { set(parent, property, null, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) { if (node == null) { throw new IllegalArgumentException(); } StructuralPropertyDescriptor property; ASTNode parent; if (RewriteEventStore.isNewNode(node)) { // replace a new node, bug 164862 PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW); if (location != null) { property= location.getProperty(); parent= location.getParent(); } else { throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ } } else { property= node.getLocationInParent(); parent= node.getParent(); } if (property.isChildListProperty()) { getListRewrite(parent, (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup); } else { set(parent, property, replacement, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void set(ASTNode node, StructuralPropertyDescriptor property, Object value, TextEditGroup editGroup) { if (node == null || property == null) { throw new IllegalArgumentException(); } validateIsCorrectAST(node); validatePropertyType(property, value); validateIsPropertyOfNode(property, node); NodeRewriteEvent nodeEvent= this.eventStore.getNodeEvent(node, property, true); nodeEvent.setNewValue(value); if (editGroup != null) { this.eventStore.setEventEditGroup(nodeEvent, editGroup); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public Object get(ASTNode node, StructuralPropertyDescriptor property) { if (node == null || property == null) { throw new IllegalArgumentException(); } if (property.isChildListProperty()) { throw new IllegalArgumentException("Use the list rewriter to access nodes in a list"); //$NON-NLS-1$ } return this.eventStore.getNewValue(node, property); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor property) { if (node == null || property == null) { throw new IllegalArgumentException(); } validateIsCorrectAST(node); validateIsListProperty(property); validateIsPropertyOfNode(property, node); return new ListRewrite(this, node, property); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final Object getProperty(String propertyName) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // rewrite has no properties at all return null; } if (this.property1 instanceof String) { // rewrite has only a single property if (propertyName.equals(this.property1)) { return this.property2; } else { return null; } } // otherwise rewrite has table of properties Map m = (Map) this.property1; return m.get(propertyName); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ITrackedNodePosition track(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } TextEditGroup group= this.eventStore.getTrackedNodeData(node); if (group == null) { group= new TextEditGroup("internal"); //$NON-NLS-1$ this.eventStore.setTrackedNodeData(node, group); } return new TrackedNodePosition(group, node); }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsExistingNode(ASTNode node) { if (node.getStartPosition() == -1) { throw new IllegalArgumentException("Node is not an existing node"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsCorrectAST(ASTNode node) { if (node.getAST() != getAST()) { throw new IllegalArgumentException("Node is not inside the AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsListProperty(StructuralPropertyDescriptor property) { if (!property.isChildListProperty()) { String message= property.getId() + " is not a list property"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validateIsPropertyOfNode(StructuralPropertyDescriptor property, ASTNode node) { if (!property.getNodeClass().isInstance(node)) { String message= property.getId() + " is not a property of type " + node.getClass().getName(); //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private void validatePropertyType(StructuralPropertyDescriptor prop, Object node) { if (prop.isChildListProperty()) { String message= "Can not modify a list property, use a list rewriter"; //$NON-NLS-1$ throw new IllegalArgumentException(message); } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ASTNode createStringPlaceholder(String code, int nodeType) { if (code == null) { throw new IllegalArgumentException(); } ASTNode placeholder= getNodeStore().newPlaceholderNode(nodeType); if (placeholder == null) { throw new IllegalArgumentException("String placeholder is not supported for type" + nodeType); //$NON-NLS-1$ } getNodeStore().markAsStringPlaceholder(placeholder, code); return placeholder; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final ASTNode createGroupNode(ASTNode[] targetNodes) { if (targetNodes == null || targetNodes.length == 0) { throw new IllegalArgumentException(); } Block res= getNodeStore().createCollapsePlaceholder(); ListRewrite listRewrite= getListRewrite(res, Block.STATEMENTS_PROPERTY); for (int i= 0; i < targetNodes.length; i++) { listRewrite.insertLast(targetNodes[i], null); } return res; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
private ASTNode createTargetNode(ASTNode node, boolean isMove) { if (node == null) { throw new IllegalArgumentException(); } validateIsExistingNode(node); validateIsCorrectAST(node); CopySourceInfo info= getRewriteEventStore().markAsCopySource(node.getParent(), node.getLocationInParent(), node, isMove); ASTNode placeholder= getNodeStore().newPlaceholderNode(node.getNodeType()); if (placeholder == null) { throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + node.getClass().getName()); //$NON-NLS-1$ } getNodeStore().markAsCopyTarget(placeholder, info); return placeholder; }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public final void setProperty(String propertyName, Object data) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // rewrite has no properties at all if (data == null) { // rewrite already knows this return; } // rewrite gets its fist property this.property1 = propertyName; this.property2 = data; return; } if (this.property1 instanceof String) { // rewrite has only a single property if (propertyName.equals(this.property1)) { // we're in luck if (data == null) { // just delete last property this.property1 = null; this.property2 = null; } else { this.property2 = data; } return; } if (data == null) { // we already know this return; } // rewrite already has one property - getting its second // convert to more flexible representation Map m = new HashMap(3); m.put(this.property1, this.property2); m.put(propertyName, data); this.property1 = m; this.property2 = null; return; } // rewrite has two or more properties Map m = (Map) this.property1; if (data == null) { m.remove(propertyName); // check for just one property left if (m.size() == 1) { // convert to more efficient representation Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]); this.property1 = entries[0].getKey(); this.property2 = entries[0].getValue(); } return; } else { m.put(propertyName, data); // still has two or more properties return; } }
// in dom/org/eclipse/jdt/core/dom/Statement.java
public void setLeadingComment(String comment) { if (comment != null) { char[] source = comment.toCharArray(); Scanner scanner = this.ast.scanner; scanner.resetTo(0, source.length); scanner.setSource(source); try { int token; boolean onlyOneComment = false; while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameCOMMENT_BLOCK : case TerminalTokens.TokenNameCOMMENT_JAVADOC : case TerminalTokens.TokenNameCOMMENT_LINE : if (onlyOneComment) { throw new IllegalArgumentException(); } onlyOneComment = true; break; default: onlyOneComment = false; } } if (!onlyOneComment) { throw new IllegalArgumentException(); } } catch (InvalidInputException e) { throw new IllegalArgumentException(); } } // we do not consider the obsolete comment as a structureal property // but we protect them nevertheless checkModifiable(); this.optionalLeadingComment = comment; }
// in dom/org/eclipse/jdt/core/dom/FieldAccess.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/FieldAccess.java
public void setName(SimpleName fieldName) { if (fieldName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.fieldName; preReplaceChild(oldChild, fieldName, NAME_PROPERTY); this.fieldName = fieldName; postReplaceChild(oldChild, fieldName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ParenthesizedExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeDeclarationStatement.java
public void setDeclaration(AbstractTypeDeclaration decl) { if (decl == null) { throw new IllegalArgumentException(); } // a TypeDeclarationStatement may occur inside an // TypeDeclaration - must check cycles ASTNode oldChild = this.typeDecl; ChildPropertyDescriptor typeDeclProperty = typeDeclProperty(); preReplaceChild(oldChild, decl, typeDeclProperty); this.typeDecl= decl; postReplaceChild(oldChild, decl, typeDeclProperty); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static Class nodeClassForType(int nodeType) { switch (nodeType) { case ANNOTATION_TYPE_DECLARATION : return AnnotationTypeDeclaration.class; case ANNOTATION_TYPE_MEMBER_DECLARATION : return AnnotationTypeMemberDeclaration.class; case ANONYMOUS_CLASS_DECLARATION : return AnonymousClassDeclaration.class; case ARRAY_ACCESS : return ArrayAccess.class; case ARRAY_CREATION : return ArrayCreation.class; case ARRAY_INITIALIZER : return ArrayInitializer.class; case ARRAY_TYPE : return ArrayType.class; case ASSERT_STATEMENT : return AssertStatement.class; case ASSIGNMENT : return Assignment.class; case BLOCK : return Block.class; case BLOCK_COMMENT : return BlockComment.class; case BOOLEAN_LITERAL : return BooleanLiteral.class; case BREAK_STATEMENT : return BreakStatement.class; case CAST_EXPRESSION : return CastExpression.class; case CATCH_CLAUSE : return CatchClause.class; case CHARACTER_LITERAL : return CharacterLiteral.class; case CLASS_INSTANCE_CREATION : return ClassInstanceCreation.class; case COMPILATION_UNIT : return CompilationUnit.class; case CONDITIONAL_EXPRESSION : return ConditionalExpression.class; case CONSTRUCTOR_INVOCATION : return ConstructorInvocation.class; case CONTINUE_STATEMENT : return ContinueStatement.class; case UNION_TYPE : return UnionType.class; case DO_STATEMENT : return DoStatement.class; case EMPTY_STATEMENT : return EmptyStatement.class; case ENHANCED_FOR_STATEMENT : return EnhancedForStatement.class; case ENUM_CONSTANT_DECLARATION : return EnumConstantDeclaration.class; case ENUM_DECLARATION : return EnumDeclaration.class; case EXPRESSION_STATEMENT : return ExpressionStatement.class; case FIELD_ACCESS : return FieldAccess.class; case FIELD_DECLARATION : return FieldDeclaration.class; case FOR_STATEMENT : return ForStatement.class; case IF_STATEMENT : return IfStatement.class; case IMPORT_DECLARATION : return ImportDeclaration.class; case INFIX_EXPRESSION : return InfixExpression.class; case INITIALIZER : return Initializer.class; case INSTANCEOF_EXPRESSION : return InstanceofExpression.class; case JAVADOC : return Javadoc.class; case LABELED_STATEMENT : return LabeledStatement.class; case LINE_COMMENT : return LineComment.class; case MARKER_ANNOTATION : return MarkerAnnotation.class; case MEMBER_REF : return MemberRef.class; case MEMBER_VALUE_PAIR : return MemberValuePair.class; case METHOD_DECLARATION : return MethodDeclaration.class; case METHOD_INVOCATION : return MethodInvocation.class; case METHOD_REF : return MethodRef.class; case METHOD_REF_PARAMETER : return MethodRefParameter.class; case MODIFIER : return Modifier.class; case NORMAL_ANNOTATION : return NormalAnnotation.class; case NULL_LITERAL : return NullLiteral.class; case NUMBER_LITERAL : return NumberLiteral.class; case PACKAGE_DECLARATION : return PackageDeclaration.class; case PARAMETERIZED_TYPE : return ParameterizedType.class; case PARENTHESIZED_EXPRESSION : return ParenthesizedExpression.class; case POSTFIX_EXPRESSION : return PostfixExpression.class; case PREFIX_EXPRESSION : return PrefixExpression.class; case PRIMITIVE_TYPE : return PrimitiveType.class; case QUALIFIED_NAME : return QualifiedName.class; case QUALIFIED_TYPE : return QualifiedType.class; case RETURN_STATEMENT : return ReturnStatement.class; case SIMPLE_NAME : return SimpleName.class; case SIMPLE_TYPE : return SimpleType.class; case SINGLE_MEMBER_ANNOTATION : return SingleMemberAnnotation.class; case SINGLE_VARIABLE_DECLARATION : return SingleVariableDeclaration.class; case STRING_LITERAL : return StringLiteral.class; case SUPER_CONSTRUCTOR_INVOCATION : return SuperConstructorInvocation.class; case SUPER_FIELD_ACCESS : return SuperFieldAccess.class; case SUPER_METHOD_INVOCATION : return SuperMethodInvocation.class; case SWITCH_CASE: return SwitchCase.class; case SWITCH_STATEMENT : return SwitchStatement.class; case SYNCHRONIZED_STATEMENT : return SynchronizedStatement.class; case TAG_ELEMENT : return TagElement.class; case TEXT_ELEMENT : return TextElement.class; case THIS_EXPRESSION : return ThisExpression.class; case THROW_STATEMENT : return ThrowStatement.class; case TRY_STATEMENT : return TryStatement.class; case TYPE_DECLARATION : return TypeDeclaration.class; case TYPE_DECLARATION_STATEMENT : return TypeDeclarationStatement.class; case TYPE_LITERAL : return TypeLiteral.class; case TYPE_PARAMETER : return TypeParameter.class; case VARIABLE_DECLARATION_EXPRESSION : return VariableDeclarationExpression.class; case VARIABLE_DECLARATION_FRAGMENT : return VariableDeclarationFragment.class; case VARIABLE_DECLARATION_STATEMENT : return VariableDeclarationStatement.class; case WHILE_STATEMENT : return WhileStatement.class; case WILDCARD_TYPE : return WildcardType.class; } throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public Object set(int index, Object element) { if (element == null) { throw new IllegalArgumentException(); } if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // delink old child from parent, and link new child to parent ASTNode newChild = (ASTNode) element; ASTNode oldChild = (ASTNode) this.store.get(index); if (oldChild == newChild) { return oldChild; } if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType); ASTNode.this.ast.preReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor); Object result = this.store.set(index, newChild); // n.b. setParent will call ast.modifying() oldChild.setParent(null, null); newChild.setParent(ASTNode.this, this.propertyDescriptor); ASTNode.this.ast.postReplaceChildEvent(ASTNode.this, oldChild, newChild, this.propertyDescriptor); return result; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public void add(int index, Object element) { if (element == null) { throw new IllegalArgumentException(); } if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // link new child to parent ASTNode newChild = (ASTNode) element; ASTNode.checkNewChild(ASTNode.this, newChild, this.propertyDescriptor.cycleRisk, this.propertyDescriptor.elementType); ASTNode.this.ast.preAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor); this.store.add(index, element); updateCursors(index, +1); // n.b. setParent will call ast.modifying() newChild.setParent(ASTNode.this, this.propertyDescriptor); ASTNode.this.ast.postAddChildEvent(ASTNode.this, newChild, this.propertyDescriptor); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public Object remove(int index) { if ((ASTNode.this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } // delink old child from parent ASTNode oldChild = (ASTNode) this.store.get(index); if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } ASTNode.this.ast.preRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor); // n.b. setParent will call ast.modifying() oldChild.setParent(null, null); Object result = this.store.remove(index); updateCursors(index, -1); ASTNode.this.ast.postRemoveChildEvent(ASTNode.this, oldChild, this.propertyDescriptor); return result; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final Object getStructuralProperty(StructuralPropertyDescriptor property) { if (property instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor p = (SimplePropertyDescriptor) property; if (p.getValueType() == int.class) { int result = internalGetSetIntProperty(p, true, 0); return new Integer(result); } else if (p.getValueType() == boolean.class) { boolean result = internalGetSetBooleanProperty(p, true, false); return Boolean.valueOf(result); } else { return internalGetSetObjectProperty(p, true, null); } } if (property instanceof ChildPropertyDescriptor) { return internalGetSetChildProperty((ChildPropertyDescriptor) property, true, null); } if (property instanceof ChildListPropertyDescriptor) { return internalGetChildListProperty((ChildListPropertyDescriptor) property); } throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setStructuralProperty(StructuralPropertyDescriptor property, Object value) { if (property instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor p = (SimplePropertyDescriptor) property; if (p.getValueType() == int.class) { int arg = ((Integer) value).intValue(); internalGetSetIntProperty(p, false, arg); return; } else if (p.getValueType() == boolean.class) { boolean arg = ((Boolean) value).booleanValue(); internalGetSetBooleanProperty(p, false, arg); return; } else { if (value == null && p.isMandatory()) { throw new IllegalArgumentException(); } internalGetSetObjectProperty(p, false, value); return; } } if (property instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor p = (ChildPropertyDescriptor) property; ASTNode child = (ASTNode) value; if (child == null && p.isMandatory()) { throw new IllegalArgumentException(); } internalGetSetChildProperty(p, false, child); return; } if (property instanceof ChildListPropertyDescriptor) { throw new IllegalArgumentException("Cannot set the list of child list property"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void checkNewChild(ASTNode node, ASTNode newChild, boolean cycleCheck, Class nodeType) { if (newChild.ast != node.ast) { // new child is from a different AST throw new IllegalArgumentException(); } if (newChild.getParent() != null) { // new child currently has a different parent throw new IllegalArgumentException(); } if (cycleCheck && newChild == node.getRoot()) { // inserting new child would create a cycle throw new IllegalArgumentException(); } Class childClass = newChild.getClass(); if (nodeType != null && !nodeType.isAssignableFrom(childClass)) { // new child is not of the right type throw new ClassCastException(); } if ((newChild.typeAndFlags & PROTECT) != 0) { // new child node is protected => cannot be parented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void preReplaceChild(ASTNode oldChild, ASTNode newChild, ChildPropertyDescriptor property) { if ((this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot gain or lose children throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } if (newChild != null) { checkNewChild(this, newChild, property.cycleRisk, null); } // delink old child from parent if (oldChild != null) { if ((oldChild.typeAndFlags & PROTECT) != 0) { // old child node is protected => cannot be unparented throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } if (newChild != null) { this.ast.preReplaceChildEvent(this, oldChild, newChild, property); } else { this.ast.preRemoveChildEvent(this, oldChild, property); } oldChild.setParent(null, null); } else { if(newChild != null) { this.ast.preAddChildEvent(this, newChild, property); } } // link new child to parent if (newChild != null) { newChild.setParent(this, property); // cannot notify postAddChildEvent until parent is linked to child too } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void preValueChange(SimplePropertyDescriptor property) { if ((this.typeAndFlags & PROTECT) != 0) { // this node is protected => cannot change valure of properties throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } this.ast.preValueChangeEvent(this, property); this.ast.modifying(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void checkModifiable() { if ((this.typeAndFlags & PROTECT) != 0) { throw new IllegalArgumentException("AST node cannot be modified"); //$NON-NLS-1$ } this.ast.modifying(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final Object getProperty(String propertyName) { if (propertyName == null) { throw new IllegalArgumentException(); } if (this.property1 == null) { // node has no properties at all return null; } if (this.property1 instanceof String) { // node has only a single property if (propertyName.equals(this.property1)) { return this.property2; } else { return null; } } // otherwise node has table of properties Map m = (Map) this.property1; return m.get(propertyName); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setProperty(String propertyName, Object data) { if (propertyName == null) { throw new IllegalArgumentException(); } // N.B. DO NOT CALL ast.modifying(); if (this.property1 == null) { // node has no properties at all if (data == null) { // we already know this return; } // node gets its fist property this.property1 = propertyName; this.property2 = data; return; } if (this.property1 instanceof String) { // node has only a single property if (propertyName.equals(this.property1)) { // we're in luck if (data == null) { // just deleted last property this.property1 = null; this.property2 = null; } else { this.property2 = data; } return; } if (data == null) { // we already know this return; } // node already has one property - getting its second // convert to more flexible representation Map m = new HashMap(3); m.put(this.property1, this.property2); m.put(propertyName, data); this.property1 = m; this.property2 = null; return; } // node has two or more properties Map m = (Map) this.property1; if (data == null) { m.remove(propertyName); // check for just one property left if (m.size() == 1) { // convert to more efficient representation Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]); this.property1 = entries[0].getKey(); this.property2 = entries[0].getValue(); } return; } else { m.put(propertyName, data); // still has two or more properties return; } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static ASTNode copySubtree(AST target, ASTNode node) { if (node == null) { return null; } if (target == null) { throw new IllegalArgumentException(); } if (target.apiLevel() != node.getAST().apiLevel()) { throw new UnsupportedOperationException(); } ASTNode newNode = node.clone(target); return newNode; }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void accept(ASTVisitor visitor) { if (visitor == null) { throw new IllegalArgumentException(); } // begin with the generic pre-visit if (visitor.preVisit2(this)) { // dynamic dispatch to internal method for type-specific visit/endVisit accept0(visitor); } // end with the generic post-visit visitor.postVisit(this); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public final void setSourceRange(int startPosition, int length) { if (startPosition >= 0 && length < 0) { throw new IllegalArgumentException(); } if (startPosition < 0 && length != 0) { throw new IllegalArgumentException(); } // source positions are not considered a structural property // but we protect them nevertheless checkModifiable(); this.startPosition = startPosition; this.length = length; }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
public void setIdentifier(String identifier) { // update internalSetIdentifier if this is changed if (identifier == null) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; long sourceLevel = scanner.sourceLevel; long complianceLevel = scanner.complianceLevel; try { scanner.sourceLevel = ClassFileConstants.JDK1_3; scanner.complianceLevel = ClassFileConstants.JDK1_5; char[] source = identifier.toCharArray(); scanner.setSource(source); final int length = source.length; scanner.resetTo(0, length - 1); try { int tokenType = scanner.scanIdentifier(); if (tokenType != TerminalTokens.TokenNameIdentifier) { throw new IllegalArgumentException(); } if (scanner.currentPosition != length) { // this is the case when there is only one identifier see 87849 throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } } finally { this.ast.scanner.sourceLevel = sourceLevel; this.ast.scanner.complianceLevel = complianceLevel; } preValueChange(IDENTIFIER_PROPERTY); this.identifier = identifier; postValueChange(IDENTIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static IBinding[] resolve( final IJavaElement[] elements, int apiLevel, Map compilerOptions, IJavaProject javaProject, WorkingCopyOwner owner, int flags, IProgressMonitor monitor) { final int length = elements.length; final HashMap sourceElementPositions = new HashMap(); // a map from ICompilationUnit to int[] (positions in elements) int cuNumber = 0; final HashtableOfObjectToInt binaryElementPositions = new HashtableOfObjectToInt(); // a map from String (binding key) to int (position in elements) for (int i = 0; i < length; i++) { IJavaElement element = elements[i]; if (!(element instanceof SourceRefElement)) throw new IllegalStateException(element + " is not part of a compilation unit or class file"); //$NON-NLS-1$ Object cu = element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { // source member IntArrayList intList = (IntArrayList) sourceElementPositions.get(cu); if (intList == null) { sourceElementPositions.put(cu, intList = new IntArrayList()); cuNumber++; } intList.add(i); } else { // binary member try { String key = ((BinaryMember) element).getKey(true/*open to get resolved info*/); binaryElementPositions.put(key, i); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } } } ICompilationUnit[] cus = new ICompilationUnit[cuNumber]; sourceElementPositions.keySet().toArray(cus); int bindingKeyNumber = binaryElementPositions.size(); String[] bindingKeys = new String[bindingKeyNumber]; binaryElementPositions.keysToArray(bindingKeys); class Requestor extends ASTRequestor { IBinding[] bindings = new IBinding[length]; public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } } public void acceptBinding(String bindingKey, IBinding binding) { int index = binaryElementPositions.get(bindingKey); this.bindings[index] = binding; } } Requestor requestor = new Requestor(); resolve(cus, bindingKeys, requestor, apiLevel, compilerOptions, javaProject, owner, flags, monitor); return requestor.bindings; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
public void setComment(String docComment) { supportedOnlyIn2(); if (docComment == null) { throw new IllegalArgumentException(); } char[] source = docComment.toCharArray(); Scanner scanner = this.ast.scanner; scanner.resetTo(0, source.length); scanner.setSource(source); try { int token; boolean onlyOneComment = false; while ((token = scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameCOMMENT_JAVADOC : if (onlyOneComment) { throw new IllegalArgumentException(); } onlyOneComment = true; break; default: onlyOneComment = false; } } if (!onlyOneComment) { throw new IllegalArgumentException(); } } catch (InvalidInputException e) { throw new IllegalArgumentException(); } preValueChange(COMMENT_PROPERTY); this.comment = docComment; postValueChange(COMMENT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ThrowStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CastExpression.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CastExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
public void setEscapedValue(String value) { // check setInternalEscapedValue(String) if this method is changed if (value == null) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = value.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameCharacterLiteral: break; default: throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } preValueChange(ESCAPED_VALUE_PROPERTY); this.escapedValue = value; postValueChange(ESCAPED_VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
public char charValue() { Scanner scanner = this.ast.scanner; char[] source = this.escapedValue.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); int firstChar = scanner.getNextChar(); int secondChar = scanner.getNextChar(); if (firstChar == -1 || firstChar != '\'') { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } char value = (char) secondChar; int nextChar = scanner.getNextChar(); if (secondChar == '\\') { if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } switch(nextChar) { case 'b' : value = '\b'; break; case 't' : value = '\t'; break; case 'n' : value = '\n'; break; case 'f' : value = '\f'; break; case 'r' : value = '\r'; break; case '\"': value = '\"'; break; case '\'': value = '\''; break; case '\\': value = '\\'; break; default : //octal (well-formed: ended by a ' ) try { if (ScannerHelper.isDigit((char) nextChar)) { int number = ScannerHelper.getNumericValue((char) nextChar); nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } if (nextChar != '\'') { if (!ScannerHelper.isDigit((char) nextChar)) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } number = (number * 8) + ScannerHelper.getNumericValue((char) nextChar); nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } if (nextChar != '\'') { if (!ScannerHelper.isDigit((char) nextChar)) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } number = (number * 8) + ScannerHelper.getNumericValue((char) nextChar); } } return (char) number; } else { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } nextChar = scanner.getNextChar(); if (nextChar == -1) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } } if (nextChar == -1 || nextChar != '\'') { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ } return value; }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
public ITypeBinding createArrayType(int dimension) { int realDimensions = dimension; realDimensions += getDimensions(); if (realDimensions < 1 || realDimensions > 255) { throw new IllegalArgumentException(); } return this.resolver.resolveArrayType(this, dimension); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int getExtendedLength(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { // fall back: use best info available return node.getLength(); } else { return this.commentMapper.getExtendedLength(node); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int getExtendedStartPosition(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { // fall back: use best info available return node.getStartPosition(); } else { return this.commentMapper.getExtendedStartPosition(node); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int firstLeadingCommentIndex(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { return -1; } return this.commentMapper.firstLeadingCommentIndex(node); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
public int lastTrailingCommentIndex(ASTNode node) { if (node == null) { throw new IllegalArgumentException(); } if (this.commentMapper == null || node.getAST() != getAST()) { return -1; } return this.commentMapper.lastTrailingCommentIndex(node); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setCommentTable(Comment[] commentTable) { // double check table to ensure that all comments have // source positions and are in strictly increasing order if (commentTable == null) { this.optionalCommentList = null; this.optionalCommentTable = null; } else { int nextAvailablePosition = 0; for (int i = 0; i < commentTable.length; i++) { Comment comment = commentTable[i]; if (comment == null) { throw new IllegalArgumentException(); } int start = comment.getStartPosition(); int length = comment.getLength(); if (start < 0 || length < 0 || start < nextAvailablePosition) { throw new IllegalArgumentException(); } nextAvailablePosition = comment.getStartPosition() + comment.getLength(); } this.optionalCommentTable = commentTable; List commentList = Arrays.asList(commentTable); // protect the list from further modification this.optionalCommentList = Collections.unmodifiableList(commentList); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setProblems(IProblem[] problems) { if (problems == null) { throw new IllegalArgumentException(); } this.problems = problems; }
// in dom/org/eclipse/jdt/core/dom/Annotation.java
public void setTypeName(Name typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ChildPropertyDescriptor p = internalTypeNameProperty(); ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, p); this.typeName = typeName; postReplaceChild(oldChild, typeName, p); }
// in dom/org/eclipse/jdt/core/dom/ArrayAccess.java
public void setArray(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an ArrayAccess may occur inside an Expression // must check cycles ASTNode oldChild = this.arrayExpression; preReplaceChild(oldChild, expression, ARRAY_PROPERTY); this.arrayExpression = expression; postReplaceChild(oldChild, expression, ARRAY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayAccess.java
public void setIndex(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an ArrayAccess may occur inside an Expression // must check cycles ASTNode oldChild = this.indexExpression; preReplaceChild(oldChild, expression, INDEX_PROPERTY); this.indexExpression = expression; postReplaceChild(oldChild, expression, INDEX_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SynchronizedStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SynchronizedStatement.java
public void setBody(Block block) { if (block == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, block, BODY_PROPERTY); this.body = block; postReplaceChild(oldChild, block, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayType.java
public void setComponentType(Type componentType) { if (componentType == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.componentType; preReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY); this.componentType = componentType; postReplaceChild(oldChild, componentType, COMPONENT_TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DefaultBindingResolver.java
ITypeBinding resolveArrayType(ITypeBinding typeBinding, int dimensions) { if (typeBinding instanceof RecoveredTypeBinding) throw new IllegalArgumentException("Cannot be called on a recovered type binding"); //$NON-NLS-1$ ITypeBinding leafComponentType = typeBinding; int actualDimensions = dimensions; if (typeBinding.isArray()) { leafComponentType = typeBinding.getElementType(); actualDimensions += typeBinding.getDimensions(); } org.eclipse.jdt.internal.compiler.lookup.TypeBinding leafTypeBinding = null; if (leafComponentType.isPrimitive()) { String name = leafComponentType.getBinaryName(); switch(name.charAt(0)) { case 'I' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.INT; break; case 'B' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.BYTE; break; case 'Z' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.BOOLEAN; break; case 'C' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.CHAR; break; case 'J' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.LONG; break; case 'S' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.SHORT; break; case 'D' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.DOUBLE; break; case 'F' : leafTypeBinding = org.eclipse.jdt.internal.compiler.lookup.TypeBinding.FLOAT; break; case 'V' : throw new IllegalArgumentException(); } } else { if (!(leafComponentType instanceof TypeBinding)) return null; leafTypeBinding = ((TypeBinding) leafComponentType).binding; } return this.getTypeBinding(lookupEnvironment().createArrayType(leafTypeBinding, actualDimensions)); }
// in dom/org/eclipse/jdt/core/dom/SwitchStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedType.java
public void setQualifier(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.qualifier; preReplaceChild(oldChild, type, QUALIFIER_PROPERTY); this.qualifier = type; postReplaceChild(oldChild, type, QUALIFIER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/QualifiedType.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ArrayCreation.java
public void setType(ArrayType type) { if (type == null) { throw new IllegalArgumentException(); } // an ArrayCreation cannot occur inside a ArrayType - cycles not possible ASTNode oldChild = this.arrayType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.arrayType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ClassInstanceCreation.java
void internalSetName(Name name) { supportedOnlyIn2(); if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.typeName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ClassInstanceCreation.java
public void setType(Type type) { unsupportedIn2(); if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AssertStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } // an AssertStatement may occur inside an Expression - must check cycles ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit(char[] source) { if (source == null) { throw new IllegalArgumentException(); } ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(source); ASTNode result = c.createAST(null); return (CompilationUnit) result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( char[] source, String unitName, IJavaProject project) { if (source == null) { throw new IllegalArgumentException(); } ASTParser astParser = ASTParser.newParser(AST.JLS2); astParser.setSource(source); astParser.setUnitName(unitName); astParser.setProject(project); astParser.setResolveBindings(project != null); ASTNode result = astParser.createAST(null); return (CompilationUnit) result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( IClassFile classFile, boolean resolveBindings) { if (classFile == null) { throw new IllegalArgumentException(); } try { ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(classFile); c.setResolveBindings(resolveBindings); ASTNode result = c.createAST(null); return (CompilationUnit) result; } catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
public static CompilationUnit parseCompilationUnit( ICompilationUnit unit, boolean resolveBindings) { try { ASTParser c = ASTParser.newParser(AST.JLS2); c.setSource(unit); c.setResolveBindings(resolveBindings); ASTNode result = c.createAST(null); return (CompilationUnit) result; } catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
public ASTNode createInstance(Class nodeClass) { if (nodeClass == null) { throw new IllegalArgumentException(); } try { // invoke constructor with signature Foo(AST) Constructor c = nodeClass.getDeclaredConstructor(AST_CLASS); Object result = c.newInstance(this.THIS_AST); return (ASTNode) result; } catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/AST.java
Name internalNewName(String[] identifiers) { int count = identifiers.length; if (count == 0) { throw new IllegalArgumentException(); } final SimpleName simpleName = new SimpleName(this); simpleName.internalSetIdentifier(identifiers[0]); Name result = simpleName; for (int i = 1; i < count; i++) { SimpleName name = new SimpleName(this); name.internalSetIdentifier(identifiers[i]); result = newQualifiedName(result, name); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public ArrayType newArrayType(Type elementType, int dimensions) { if (elementType == null) { throw new IllegalArgumentException(); } if (dimensions < 1 || dimensions > 1000) { // we would blow our stacks anyway with a 1000-D array throw new IllegalArgumentException(); } ArrayType result = new ArrayType(this); result.setComponentType(elementType); for (int i = 2; i <= dimensions; i++) { result = newArrayType(result); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public FieldDeclaration newFieldDeclaration(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } FieldDeclaration result = new FieldDeclaration(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public Name newName(String qualifiedName) { StringTokenizer t = new StringTokenizer(qualifiedName, ".", true); //$NON-NLS-1$ Name result = null; // balance is # of name tokens - # of period tokens seen so far // initially 0; finally 1; should never drop < 0 or > 1 int balance = 0; while(t.hasMoreTokens()) { String s = t.nextToken(); if (s.indexOf('.') >= 0) { // this is a delimiter if (s.length() > 1) { // too many dots in a row throw new IllegalArgumentException(); } balance--; if (balance < 0) { throw new IllegalArgumentException(); } } else { // this is an identifier segment balance++; SimpleName name = newSimpleName(s); if (result == null) { result = name; } else { result = newQualifiedName(result, name); } } } if (balance != 1) { throw new IllegalArgumentException(); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public Name newName(String[] identifiers) { // update internalSetName(String[] if changed int count = identifiers.length; if (count == 0) { throw new IllegalArgumentException(); } Name result = newSimpleName(identifiers[0]); for (int i = 1; i < count; i++) { SimpleName name = newSimpleName(identifiers[i]); result = newQualifiedName(result, name); } return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public NumberLiteral newNumberLiteral(String literal) { if (literal == null) { throw new IllegalArgumentException(); } NumberLiteral result = new NumberLiteral(this); result.setToken(literal); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public SimpleName newSimpleName(String identifier) { if (identifier == null) { throw new IllegalArgumentException(); } SimpleName result = new SimpleName(this); result.setIdentifier(identifier); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public VariableDeclarationExpression newVariableDeclarationExpression(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } VariableDeclarationExpression result = new VariableDeclarationExpression(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
public VariableDeclarationStatement newVariableDeclarationStatement(VariableDeclarationFragment fragment) { if (fragment == null) { throw new IllegalArgumentException(); } VariableDeclarationStatement result = new VariableDeclarationStatement(this); result.fragments().add(fragment); return result; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void recordModifications(CompilationUnit root) { if(this.modificationCount != this.originalModificationCount) { throw new IllegalArgumentException("AST is already modified"); //$NON-NLS-1$ } else if(this.rewriter != null) { throw new IllegalArgumentException("AST modifications are already recorded"); //$NON-NLS-1$ } else if((root.getFlags() & ASTNode.PROTECT) != 0) { throw new IllegalArgumentException("Root node is unmodifiable"); //$NON-NLS-1$ } else if(root.getAST() != this) { throw new IllegalArgumentException("Root node is not owned by this ast"); //$NON-NLS-1$ } this.rewriter = new InternalASTRewrite(root); setEventHandler(this.rewriter); }
// in dom/org/eclipse/jdt/core/dom/AST.java
TextEdit rewrite(IDocument document, Map options) { if (document == null) { throw new IllegalArgumentException(); } if (this.rewriter == null) { throw new IllegalStateException("Modifications record is not enabled"); //$NON-NLS-1$ } return this.rewriter.rewriteAST(document, options); }
// in dom/org/eclipse/jdt/core/dom/AST.java
void setBindingResolver(BindingResolver resolver) { if (resolver == null) { throw new IllegalArgumentException(); } this.resolver = resolver; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void setEventHandler(NodeEventHandler eventHandler) { if (this.eventHandler == null) { throw new IllegalArgumentException(); } this.eventHandler = eventHandler; }
// in dom/org/eclipse/jdt/core/dom/AnnotationTypeMemberDeclaration.java
public void setName(SimpleName memberName) { if (memberName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberName; preReplaceChild(oldChild, memberName, NAME_PROPERTY); this.memberName = memberName; postReplaceChild(oldChild, memberName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AnnotationTypeMemberDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.memberType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TryStatement.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
public void setToken(String token) { // update internalSetToken(String) if this is changed if (token == null || token.length() == 0) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = token.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); scanner.tokenizeComments = false; scanner.tokenizeWhiteSpace = false; try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameDoubleLiteral: case TerminalTokens.TokenNameIntegerLiteral: case TerminalTokens.TokenNameFloatingPointLiteral: case TerminalTokens.TokenNameLongLiteral: break; case TerminalTokens.TokenNameMINUS : tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameDoubleLiteral: case TerminalTokens.TokenNameIntegerLiteral: case TerminalTokens.TokenNameFloatingPointLiteral: case TerminalTokens.TokenNameLongLiteral: break; default: throw new IllegalArgumentException("Invalid number literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$ } break; default: throw new IllegalArgumentException("Invalid number literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } finally { scanner.tokenizeComments = true; scanner.tokenizeWhiteSpace = true; } preValueChange(TOKEN_PROPERTY); this.tokenValue = token; postValueChange(TOKEN_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/AbstractTypeDeclaration.java
public void setName(SimpleName typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ChildPropertyDescriptor p = internalNameProperty(); ASTNode oldChild = this.typeName; preReplaceChild(oldChild, typeName, p); this.typeName = typeName; postReplaceChild(oldChild, typeName, p); }
// in dom/org/eclipse/jdt/core/dom/PrefixExpression.java
public void setOperator(PrefixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PrefixExpression.java
public void setOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.operand; preReplaceChild(oldChild, expression, OPERAND_PROPERTY); this.operand = expression; postReplaceChild(oldChild, expression, OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberRef.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.memberName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.memberName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InstanceofExpression.java
public void setLeftOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.leftOperand; preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); this.leftOperand = expression; postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InstanceofExpression.java
public void setRightOperand(Type referenceType) { if (referenceType == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.rightOperand; preReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY); this.rightOperand = referenceType; postReplaceChild(oldChild, referenceType, RIGHT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SingleMemberAnnotation.java
public void setValue(Expression value) { if (value == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.value; preReplaceChild(oldChild, value, VALUE_PROPERTY); this.value = value; postReplaceChild(oldChild, value, VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/IfStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/IfStatement.java
public void setThenStatement(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.thenStatement; preReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY); this.thenStatement = statement; postReplaceChild(oldChild, statement, THEN_STATEMENT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/LabeledStatement.java
public void setLabel(SimpleName label) { if (label == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.labelName; preReplaceChild(oldChild, label, LABEL_PROPERTY); this.labelName = label; postReplaceChild(oldChild, label, LABEL_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/LabeledStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ExpressionStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodRef.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeLiteral.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SuperFieldAccess.java
public void setName(SimpleName fieldName) { if (fieldName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.fieldName; preReplaceChild(oldChild, fieldName, NAME_PROPERTY); this.fieldName = fieldName; postReplaceChild(oldChild, fieldName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setEnvironment(String[] classpathEntries, String[] sourcepathEntries, String[] encodings, boolean includeRunningVMBootclasspath) { this.classpaths = classpathEntries; this.sourcepaths = sourcepathEntries; this.sourcepathsEncodings = encodings; if (encodings != null) { if (sourcepathEntries == null || sourcepathEntries.length != encodings.length) { throw new IllegalArgumentException(); } } if (includeRunningVMBootclasspath) { this.bits |= CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH; } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setKind(int kind) { if ((kind != K_COMPILATION_UNIT) && (kind != K_CLASS_BODY_DECLARATIONS) && (kind != K_EXPRESSION) && (kind != K_STATEMENTS)) { throw new IllegalArgumentException(); } this.astKind = kind; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void setSourceRange(int offset, int length) { if (offset < 0 || length < -1) { throw new IllegalArgumentException(); } this.sourceOffset = offset; this.sourceLength = length; }
// in dom/org/eclipse/jdt/core/dom/PackageDeclaration.java
public void setName(Name name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.packageName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.packageName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CatchClause.java
public void setException(SingleVariableDeclaration exception) { if (exception == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.exceptionDecl; preReplaceChild(oldChild, exception, EXCEPTION_PROPERTY); this.exceptionDecl= exception; postReplaceChild(oldChild, exception, EXCEPTION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/CatchClause.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ForStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DoStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/DoStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PrimitiveType.java
public void setPrimitiveTypeCode(PrimitiveType.Code typeCode) { if (typeCode == null) { throw new IllegalArgumentException(); } preValueChange(PRIMITIVE_TYPE_CODE_PROPERTY); this.typeCode = typeCode; postValueChange(PRIMITIVE_TYPE_CODE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodInvocation.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setOperator(InfixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setLeftOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.leftOperand; preReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); this.leftOperand = expression; postReplaceChild(oldChild, expression, LEFT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/InfixExpression.java
public void setRightOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.rightOperand; preReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY); this.rightOperand = expression; postReplaceChild(oldChild, expression, RIGHT_OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberValuePair.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.name; preReplaceChild(oldChild, name, NAME_PROPERTY); this.name = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MemberValuePair.java
public void setValue(Expression value) { if (value == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.value; preReplaceChild(oldChild, value, VALUE_PROPERTY); this.value = value; postReplaceChild(oldChild, value, VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ParameterizedType.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/WhileStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/WhileStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TextElement.java
public void setText(String text) { if (text == null) { throw new IllegalArgumentException(); } if (text.indexOf("*/") > 0) { //$NON-NLS-1$ throw new IllegalArgumentException(); } preValueChange(TEXT_PROPERTY); this.text = text; postValueChange(TEXT_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/FieldDeclaration.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.conditionExpression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.conditionExpression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setThenExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.thenExpression; preReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY); this.thenExpression = expression; postReplaceChild(oldChild, expression, THEN_EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ConditionalExpression.java
public void setElseExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.elseExpression; preReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY); this.elseExpression = expression; postReplaceChild(oldChild, expression, ELSE_EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationFragment.java
public void setName(SimpleName variableName) { if (variableName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.variableName; preReplaceChild(oldChild, variableName, NAME_PROPERTY); this.variableName = variableName; postReplaceChild(oldChild, variableName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationFragment.java
public void setExtraDimensions(int dimensions) { if (dimensions < 0) { throw new IllegalArgumentException(); } preValueChange(EXTRA_DIMENSIONS_PROPERTY); this.extraArrayDimensions = dimensions; postValueChange(EXTRA_DIMENSIONS_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/SuperMethodInvocation.java
public void setName(SimpleName name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.methodName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.methodName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationStatement.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public void setEscapedValue(String token) { // update internalSetEscapedValue(String) if this is changed if (token == null) { throw new IllegalArgumentException("Token cannot be null"); //$NON-NLS-1$ } Scanner scanner = this.ast.scanner; char[] source = token.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameStringLiteral: break; default: throw new IllegalArgumentException("Invalid string literal : >" + token + "<"); //$NON-NLS-1$//$NON-NLS-2$ } } catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ } preValueChange(ESCAPED_VALUE_PROPERTY); this.escapedValue = token; postValueChange(ESCAPED_VALUE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public String getLiteralValue() { String s = getEscapedValue(); int len = s.length(); if (len < 2 || s.charAt(0) != '\"' || s.charAt(len-1) != '\"' ) { throw new IllegalArgumentException(); } Scanner scanner = this.ast.scanner; char[] source = s.toCharArray(); scanner.setSource(source); scanner.resetTo(0, source.length); try { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameStringLiteral: return scanner.getCurrentStringLiteral(); default: throw new IllegalArgumentException(); } } catch(InvalidInputException e) { throw new IllegalArgumentException(); } }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
public void setLiteralValue(String value) { if (value == null) { throw new IllegalArgumentException(); } int len = value.length(); StringBuffer b = new StringBuffer(len + 2); b.append("\""); // opening delimiter //$NON-NLS-1$ for (int i = 0; i < len; i++) { char c = value.charAt(i); switch(c) { case '\b' : b.append("\\b"); //$NON-NLS-1$ break; case '\t' : b.append("\\t"); //$NON-NLS-1$ break; case '\n' : b.append("\\n"); //$NON-NLS-1$ break; case '\f' : b.append("\\f"); //$NON-NLS-1$ break; case '\r' : b.append("\\r"); //$NON-NLS-1$ break; case '\"': b.append("\\\""); //$NON-NLS-1$ break; case '\\': b.append("\\\\"); //$NON-NLS-1$ break; case '\0' : b.append("\\0"); //$NON-NLS-1$ break; case '\1' : b.append("\\1"); //$NON-NLS-1$ break; case '\2' : b.append("\\2"); //$NON-NLS-1$ break; case '\3' : b.append("\\3"); //$NON-NLS-1$ break; case '\4' : b.append("\\4"); //$NON-NLS-1$ break; case '\5' : b.append("\\5"); //$NON-NLS-1$ break; case '\6' : b.append("\\6"); //$NON-NLS-1$ break; case '\7' : b.append("\\7"); //$NON-NLS-1$ break; default: b.append(c); } } b.append("\""); // closing delimiter //$NON-NLS-1$ setEscapedValue(b.toString()); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setParameter(SingleVariableDeclaration parameter) { if (parameter == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.parameter; preReplaceChild(oldChild, parameter, PARAMETER_PROPERTY); this.parameter = parameter; postReplaceChild(oldChild, parameter, PARAMETER_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setExpression(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.expression; preReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); this.expression = expression; postReplaceChild(oldChild, expression, EXPRESSION_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnhancedForStatement.java
public void setBody(Statement statement) { if (statement == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, statement, BODY_PROPERTY); this.body = statement; postReplaceChild(oldChild, statement, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/TypeParameter.java
public void setName(SimpleName typeName) { if (typeName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.typeVariableName; preReplaceChild(oldChild, typeName, NAME_PROPERTY); this.typeVariableName = typeName; postReplaceChild(oldChild, typeName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PostfixExpression.java
public void setOperator(PostfixExpression.Operator operator) { if (operator == null) { throw new IllegalArgumentException(); } preValueChange(OPERATOR_PROPERTY); this.operator = operator; postValueChange(OPERATOR_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/PostfixExpression.java
public void setOperand(Expression expression) { if (expression == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.operand; preReplaceChild(oldChild, expression, OPERAND_PROPERTY); this.operand = expression; postReplaceChild(oldChild, expression, OPERAND_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Modifier.java
public void setKeyword(ModifierKeyword modifierKeyord) { if (modifierKeyord == null) { throw new IllegalArgumentException(); } preValueChange(KEYWORD_PROPERTY); this.modifierKeyword = modifierKeyord; postValueChange(KEYWORD_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/EnumConstantDeclaration.java
public void setName(SimpleName constantName) { if (constantName == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.constantName; preReplaceChild(oldChild, constantName, NAME_PROPERTY); this.constantName = constantName; postReplaceChild(oldChild, constantName, NAME_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/VariableDeclarationExpression.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.baseType; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.baseType = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/MethodRefParameter.java
public void setType(Type type) { if (type == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.type; preReplaceChild(oldChild, type, TYPE_PROPERTY); this.type = type; postReplaceChild(oldChild, type, TYPE_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/Initializer.java
public void setBody(Block body) { if (body == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.body; preReplaceChild(oldChild, body, BODY_PROPERTY); this.body = body; postReplaceChild(oldChild, body, BODY_PROPERTY); }
// in dom/org/eclipse/jdt/core/dom/ImportDeclaration.java
public void setName(Name name) { if (name == null) { throw new IllegalArgumentException(); } ASTNode oldChild = this.importName; preReplaceChild(oldChild, name, NAME_PROPERTY); this.importName = name; postReplaceChild(oldChild, name, NAME_PROPERTY); }
30
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (FileNotFoundException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLog", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { throw new IllegalArgumentException( this.bind("configure.invalidexpansionargumentname", arg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IOException e) { e.printStackTrace(); throw new IllegalArgumentException(this.bind("configure.ioexceptionwarningspropertiesfile", propertiesFile)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalAccessException e) { // all AST node classes have an accessible Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
52
            
// in model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java
public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException { if(newLoadFactor <= 1.0 && newLoadFactor > 0.0) this.loadFactor = newLoadFactor; else throw new IllegalArgumentException(Messages.cache_invalidLoadFactor); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getImport(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) { return ((ICompilationUnit)parent).getPackageDeclaration(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { return ((IType)parent).getField(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { if (isVariableDeclarator()) { expand(); } super.insertSibling(sibling); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } else { super.setName(name); setTypeAltered(true); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMField.java
public void setType(String typeName) throws IllegalArgumentException { if (typeName == null) { throw new IllegalArgumentException(Messages.element_nullType); } becomeDetailed(); expand(); fragment(); setTypeAltered(true); setNameAltered(true); this.fType= typeName; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void addSuperInterface(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_addNullInterface); } if (this.fSuperInterfaces == null) { this.fSuperInterfaces= new String[1]; this.fSuperInterfaces[0]= name; } else { this.fSuperInterfaces= appendString(this.fSuperInterfaces, name); } setSuperInterfaces(this.fSuperInterfaces); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { switch (parent.getElementType()) { case IJavaElement.COMPILATION_UNIT: return ((ICompilationUnit)parent).getType(getName()); case IJavaElement.TYPE: return ((IType)parent).getType(getName()); // Note: creating local/anonymous type is not supported default: throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
public void setName(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.element_nullName); } super.setName(name); Enumeration children= getChildren(); while (children.hasMoreElements()) { IDOMNode child= (IDOMNode)children.nextElement(); if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { return ((IPackageFragment)parent).getCompilationUnit(getName()); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException { basicAddChild(child); // if the node is a constructor, it must also be fragmented to update the constructor's name if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) { ((DOMNode)child).fragment(); } else { fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException { // verify child may be added if (!canHaveChildren()) { throw new DOMException(Messages.dom_unableAddChild); } if (child == null) { throw new IllegalArgumentException(Messages.dom_addNullChild); } if (!isAllowableChild(child)) { throw new DOMException(Messages.dom_addIncompatibleChild); } if (child.getParent() != null) { throw new DOMException(Messages.dom_addChildWithParent); } /* NOTE: To test if the child is an ancestor of this node, we * need only test if the root of this node is the child (the child * is already a root since we have just guarenteed it has no parent). */ if (child == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsChild); } DOMNode node= (DOMNode)child; // if the child is not already part of this document, localize its contents // before adding it to the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // add the child last if (this.fFirstChild == null) { // this is the first and only child this.fFirstChild= node; } else { this.fLastChild.fNextNode= node; node.fPreviousNode= this.fLastChild; } this.fLastChild= node; node.fParent= this; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException { // verify sibling may be added if (sibling == null) { throw new IllegalArgumentException(Messages.dom_addNullSibling); } if (this.fParent == null) { throw new DOMException(Messages.dom_addSiblingBeforeRoot); } if (!this.fParent.isAllowableChild(sibling)) { throw new DOMException(Messages.dom_addIncompatibleSibling); } if (sibling.getParent() != null) { throw new DOMException(Messages.dom_addSiblingWithParent); } /* NOTE: To test if the sibling is an ancestor of this node, we * need only test if the root of this node is the child (the sibling * is already a root since we have just guaranteed it has no parent). */ if (sibling == getRoot()) { throw new DOMException(Messages.dom_addAncestorAsSibling); } DOMNode node= (DOMNode)sibling; // if the sibling is not already part of this document, localize its contents // before inserting it into the tree if (node.getDocument() != getDocument()) { node.localizeContents(); } // insert the node if (this.fPreviousNode == null) { this.fParent.fFirstChild= node; } else { this.fPreviousNode.fNextNode= node; } node.fParent= this.fParent; node.fPreviousNode= this.fPreviousNode; node.fNextNode= this; this.fPreviousNode= node; // if the node is a constructor, it must also be fragmented to update the constructor's name if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) { node.fragment(); } else { this.fParent.fragment(); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { int count = 1; IDOMNode previousNode = getPreviousNode(); while (previousNode != null) { if (previousNode instanceof DOMInitializer) { count++; } previousNode = previousNode.getPreviousNode(); } return ((IType) parent).getInitializer(count); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addException(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullExceptionType); } if (this.fExceptions == null) { this.fExceptions= new String[1]; this.fExceptions[0]= name; } else { this.fExceptions= appendString(this.fExceptions, name); } setExceptions(this.fExceptions); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void addParameter(String type, String name) throws IllegalArgumentException { if (type == null) { throw new IllegalArgumentException(Messages.dom_nullTypeParameter); } if (name == null) { throw new IllegalArgumentException(Messages.dom_nullNameParameter); } if (this.fParameterNames == null) { this.fParameterNames= new String[1]; this.fParameterNames[0]= name; } else { this.fParameterNames= appendString(this.fParameterNames, name); } if (this.fParameterTypes == null) { this.fParameterTypes= new String[1]; this.fParameterTypes[0]= type; } else { this.fParameterTypes= appendString(this.fParameterTypes, type); } setParameters(this.fParameterTypes, this.fParameterNames); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException { if (parent.getElementType() == IJavaElement.TYPE) { // translate parameter types to signatures String[] sigs= null; if (this.fParameterTypes != null) { sigs= new String[this.fParameterTypes.length]; int i; for (i= 0; i < this.fParameterTypes.length; i++) { sigs[i]= Signature.createTypeSignature(this.fParameterTypes[i].toCharArray(), false); } } String name= null; if (isConstructor()) { name= getConstructorName(); } else { name= getName(); } return ((IType)parent).getMethod(name, sigs); } else { throw new IllegalArgumentException(Messages.element_illegalParent); } }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setParameters(String[] types, String[] names) throws IllegalArgumentException { becomeDetailed(); if (types== null || names == null) { if (types == null && names == null) { this.fParameterTypes= null; this.fParameterNames= null; this.fParameterList= new char[] {'(',')'}; } else { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } } else if (names.length != types.length) { throw new IllegalArgumentException(Messages.dom_mismatchArgNamesAndTypes); } else if (names.length == 0) { setParameters(null, null); } else { this.fParameterNames= names; this.fParameterTypes= types; CharArrayBuffer parametersBuffer = new CharArrayBuffer(); parametersBuffer.append("("); //$NON-NLS-1$ char[] comma = new char[] {',', ' '}; for (int i = 0; i < names.length; i++) { if (i > 0) { parametersBuffer.append(comma); } parametersBuffer .append(types[i]) .append(' ') .append(names[i]); } parametersBuffer.append(')'); this.fParameterList= parametersBuffer.getContents(); } fragment(); }
// in model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
public void setReturnType(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(Messages.dom_nullReturnType); } becomeDetailed(); fragment(); setReturnTypeAltered(true); this.fReturnType= name; }
// in model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
protected void setRelativePosition(IJavaElement sibling, int policy) throws IllegalArgumentException { if (sibling == null) { this.anchorElement = null; this.insertionPolicy = INSERT_LAST; } else { this.anchorElement = sibling; this.insertionPolicy = policy; } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { try { int count = 0; while (typeSignature[count] == C_ARRAY) { ++count; } return count; } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getArrayCount(String typeSignature) throws IllegalArgumentException { return getArrayCount(typeSignature.toCharArray()); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException { int count = getArrayCount(typeSignature); if (count == 0) return typeSignature; int length = typeSignature.length; char[] result = new char[length-count]; System.arraycopy(typeSignature, count, result, 0, length-count); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String getElementType(String typeSignature) throws IllegalArgumentException { char[] signature = typeSignature.toCharArray(); char[] elementType = getElementType(signature); return signature == elementType ? typeSignature : new String(elementType); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getIntersectionTypeBounds(char[] intersectionTypeSignature) throws IllegalArgumentException { if (getTypeSignatureKind(intersectionTypeSignature) != INTERSECTION_TYPE_SIGNATURE) { return CharOperation.NO_CHAR_CHAR; } ArrayList args = new ArrayList(); int i = 1; // skip the '|' int length = intersectionTypeSignature.length; for (;;) { int e = Util.scanClassTypeSignature(intersectionTypeSignature, i); if (e < 0) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } args.add(CharOperation.subarray(intersectionTypeSignature, i, e + 1)); if (e == length - 1) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } else if (intersectionTypeSignature[e + 1] != C_COLON) { throw new IllegalArgumentException("Invalid format"); //$NON-NLS-1$ } i = e + 2; // add one to skip C_COLON } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getIntersectionTypeBounds(String intersectionTypeSignature) throws IllegalArgumentException { char[][] args = getIntersectionTypeBounds(intersectionTypeSignature.toCharArray()); return CharOperation.toStrings(args); }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { try { int count = 0; int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } for (;;) { if (methodSignature[i] == C_PARAM_END) { return count; } int e= Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } else { i = e + 1; } count++; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static int getParameterCount(String methodSignature) throws IllegalArgumentException { return getParameterCount(methodSignature.toCharArray()); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { try { int count = getParameterCount(methodSignature); char[][] result = new char[count][]; if (count == 0) { return result; } int i = CharOperation.indexOf(C_PARAM_START, methodSignature); if (i < 0) { throw new IllegalArgumentException(); } else { i++; } int t = 0; for (;;) { if (methodSignature[i] == C_PARAM_END) { return result; } int e = Util.scanTypeSignature(methodSignature, i); if (e < 0) { throw new IllegalArgumentException(); } result[t] = CharOperation.subarray(methodSignature, i, e + 1); t++; i = e + 1; } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException(); } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException { char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray()); return CharOperation.toStrings(parameterTypes); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // there could be thrown exceptions behind, thus scan one type exactly int last = Util.scanTypeSignature(methodSignature, paren+1); return CharOperation.subarray(methodSignature, paren + 1, last+1); }
// in model/org/eclipse/jdt/core/Signature.java
public static String getReturnType(String methodSignature) throws IllegalArgumentException { return new String(getReturnType(methodSignature.toCharArray())); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getThrownExceptionTypes(char[] methodSignature) throws IllegalArgumentException { // skip type parameters int exceptionStart = CharOperation.indexOf(C_EXCEPTION_START, methodSignature); if (exceptionStart == -1) { int paren = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); if (paren == -1) { throw new IllegalArgumentException(); } // ignore return type exceptionStart = Util.scanTypeSignature(methodSignature, paren+1) + 1; int length = methodSignature.length; if (exceptionStart == length) return CharOperation.NO_CHAR_CHAR; throw new IllegalArgumentException(); } int length = methodSignature.length; int i = exceptionStart; ArrayList exceptionList = new ArrayList(1); while (i < length) { if (methodSignature[i] == C_EXCEPTION_START) { exceptionStart++; i++; } else { throw new IllegalArgumentException(); } i = Util.scanTypeSignature(methodSignature, i) + 1; exceptionList.add(CharOperation.subarray(methodSignature, exceptionStart,i)); exceptionStart = i; } char[][] result; exceptionList.toArray(result = new char[exceptionList.size()][]); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getThrownExceptionTypes(String methodSignature) throws IllegalArgumentException { char[][] parameterTypes = getThrownExceptionTypes(methodSignature.toCharArray()); return CharOperation.toStrings(parameterTypes); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeArguments(char[] parameterizedTypeSignature) throws IllegalArgumentException { int length = parameterizedTypeSignature.length; if (length < 2 || parameterizedTypeSignature[length-2] != C_GENERIC_END) // cannot have type arguments otherwise signature would end by ">;" return CharOperation.NO_CHAR_CHAR; int count = 1; // start to count generic end/start peers int start = length - 2; while (start >= 0 && count > 0) { switch (parameterizedTypeSignature[--start]) { case C_GENERIC_START: count--; break; case C_GENERIC_END: count++; break; } } if (start < 0) // invalid number of generic start/end throw new IllegalArgumentException(); ArrayList args = new ArrayList(); int p = start + 1; while (true) { if (p >= parameterizedTypeSignature.length) { throw new IllegalArgumentException(); } char c = parameterizedTypeSignature[p]; if (c == C_GENERIC_END) { int size = args.size(); char[][] result = new char[size][]; args.toArray(result); return result; } int e = Util.scanTypeArgumentSignature(parameterizedTypeSignature, p); args.add(CharOperation.subarray(parameterizedTypeSignature, p, e+1)); p = e + 1; } }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeArguments(String parameterizedTypeSignature) throws IllegalArgumentException { char[][] args = getTypeArguments(parameterizedTypeSignature.toCharArray()); return CharOperation.toStrings(args); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeErasure(char[] parameterizedTypeSignature) throws IllegalArgumentException { int end = CharOperation.indexOf(C_GENERIC_START, parameterizedTypeSignature); if (end == -1) return parameterizedTypeSignature; int length = parameterizedTypeSignature.length; char[] result = new char[length]; int pos = 0; int start = 0; int deep= 0; for (int idx=end; idx<length; idx++) { switch (parameterizedTypeSignature[idx]) { case C_GENERIC_START: if (deep == 0) { int size = idx-start; System.arraycopy(parameterizedTypeSignature, start, result, pos, size); end = idx; pos += size; } deep++; break; case C_GENERIC_END: deep--; if (deep < 0) throw new IllegalArgumentException(); if (deep == 0) start = idx+1; break; } } if (deep > 0) throw new IllegalArgumentException(); int size = pos+length-start; char[] resized = new char[size]; System.arraycopy(result, 0, resized, 0, pos); System.arraycopy(parameterizedTypeSignature, start, resized, pos, length-start); return resized; }
// in model/org/eclipse/jdt/core/Signature.java
public static String getTypeErasure(String parameterizedTypeSignature) throws IllegalArgumentException { char[] signature = parameterizedTypeSignature.toCharArray(); char[] erasure = getTypeErasure(signature); return signature == erasure ? parameterizedTypeSignature : new String(erasure); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameterBounds(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p1 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p1 < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } if (p1 == formalTypeParameterSignature.length - 1) { // no class or interface bounds return CharOperation.NO_CHAR_CHAR; } int p2 = CharOperation.indexOf(C_COLON, formalTypeParameterSignature, p1 + 1); char[] classBound; if (p2 < 0) { // no interface bounds classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, formalTypeParameterSignature.length); return new char[][] {classBound}; } if (p2 == p1 + 1) { // no class bound, but 1 or more interface bounds classBound = null; } else { classBound = CharOperation.subarray(formalTypeParameterSignature, p1 + 1, p2); } char[][] interfaceBounds = CharOperation.splitOn(C_COLON, formalTypeParameterSignature, p2 + 1, formalTypeParameterSignature.length); if (classBound == null) { return interfaceBounds; } int resultLength = interfaceBounds.length + 1; char[][] result = new char[resultLength][]; result[0] = classBound; System.arraycopy(interfaceBounds, 0, result, 1, interfaceBounds.length); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeParameterBounds(String formalTypeParameterSignature) throws IllegalArgumentException { char[][] bounds = getTypeParameterBounds(formalTypeParameterSignature.toCharArray()); return CharOperation.toStrings(bounds); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[][] getTypeParameters(char[] methodOrTypeSignature) throws IllegalArgumentException { try { int length = methodOrTypeSignature.length; if (length == 0) return CharOperation.NO_CHAR_CHAR; if (methodOrTypeSignature[0] != C_GENERIC_START) return CharOperation.NO_CHAR_CHAR; ArrayList paramList = new ArrayList(1); int paramStart = 1, i = 1; // start after leading '<' while (i < length) { if (methodOrTypeSignature[i] == C_GENERIC_END) { int size = paramList.size(); if (size == 0) throw new IllegalArgumentException(); char[][] result; paramList.toArray(result = new char[size][]); return result; } i = CharOperation.indexOf(C_COLON, methodOrTypeSignature, i); if (i < 0 || i >= length) throw new IllegalArgumentException(); // iterate over bounds while (methodOrTypeSignature[i] == ':') { i++; // skip colon switch (methodOrTypeSignature[i]) { case ':': // no class bound break; case C_GENERIC_END: break; case C_RESOLVED: try { i = Util.scanClassTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter } break; case C_ARRAY: try { i = Util.scanArrayTypeSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter } break; case C_TYPE_VARIABLE: try { i = Util.scanTypeVariableSignature(methodOrTypeSignature, i); i++; // position at start of next param if any } catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter } break; // default: another type parameter is starting } } paramList.add(CharOperation.subarray(methodOrTypeSignature, paramStart, i)); paramStart = i; // next param start from here } } catch (ArrayIndexOutOfBoundsException e) { // invalid signature, fall through } throw new IllegalArgumentException(); }
// in model/org/eclipse/jdt/core/Signature.java
public static String[] getTypeParameters(String methodOrTypeSignature) throws IllegalArgumentException { char[][] params = getTypeParameters(methodOrTypeSignature.toCharArray()); return CharOperation.toStrings(params); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] getTypeVariable(char[] formalTypeParameterSignature) throws IllegalArgumentException { int p = CharOperation.indexOf(C_COLON, formalTypeParameterSignature); if (p < 0) { // no ":" means can't be a formal type parameter signature throw new IllegalArgumentException(); } return CharOperation.subarray(formalTypeParameterSignature, 0, p); }
// in model/org/eclipse/jdt/core/Signature.java
public static String getTypeVariable(String formalTypeParameterSignature) throws IllegalArgumentException { return new String(getTypeVariable(formalTypeParameterSignature.toCharArray())); }
// in model/org/eclipse/jdt/core/Signature.java
public static char[] toCharArray(char[] signature) throws IllegalArgumentException { int sigLength = signature.length; if (sigLength == 0) { throw new IllegalArgumentException(); } if (signature[0] == C_PARAM_START || signature[0] == C_GENERIC_START) { return toCharArray(signature, CharOperation.NO_CHAR, null, true, true); } StringBuffer buffer = new StringBuffer(signature.length + 10); appendTypeSignature(signature, 0, true, buffer); char[] result = new char[buffer.length()]; buffer.getChars(0, buffer.length(), result, 0); return result; }
// in model/org/eclipse/jdt/core/Signature.java
public static String toString(String signature) throws IllegalArgumentException { return new String(toCharArray(signature.toCharArray())); }
// in formatter/org/eclipse/jdt/internal/formatter/comment/CommentFormatterUtil.java
private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException { Document doc= new Document(content); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { if (this.fOffset < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < this.fOffset + this.fLength)) { this.fPosition.offset= this.fOffset + this.fLength; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ASTRewriteFormatter.java
private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { Document doc= new Document(string); try { if (positions != null) { final String POS_CATEGORY= "myCategory"; //$NON-NLS-1$ doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { int start= this.fOffset; int end= start + this.fLength; if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) { this.fPosition.offset= end; // deleted positions: set to end of remove return false; } return true; } }); for (int i= 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } } } }
// in dom/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException { if (document == null) { throw new IllegalArgumentException(); } ASTNode rootNode= getRootNode(); if (rootNode == null) { return new MultiTextEdit(); // no changes } char[] content= document.get().toCharArray(); LineInformation lineInfo= LineInformation.create(document); String lineDelim= TextUtilities.getDefaultLineDelimiter(document); ASTNode astRoot= rootNode.getRoot(); List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null; Map currentOptions = options == null ? JavaCore.getOptions() : options; return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData()); }
// 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()); }
28
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { e.printStackTrace(); }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (IllegalArgumentException e) { this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // declaring type is invalid return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // string is not a valid type syntax return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // declaring type is invalid return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (IllegalArgumentException iae) { // string is not a valid type syntax return null; }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalArgumentException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (IllegalArgumentException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316 return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch(IllegalArgumentException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
catch (IllegalArgumentException e) { // parameter signature is malformed buffer.append("*** invalid signature: "); //$NON-NLS-1$ buffer.append(parameters[i]); }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not a class type signature -> it is a new type parameter }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not an array type signature -> it is a new type parameter }
// in model/org/eclipse/jdt/core/Signature.java
catch (IllegalArgumentException e) { // not a type variable signature -> it is a new type parameter }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(IllegalArgumentException e) { // protection for invalid signature if(this.parameterTypeNames != null) { this.parameterNames = CompletionEngine.createDefaultParameterNames(this.parameterTypeNames.length); } else { this.parameterNames = null; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch(IllegalArgumentException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch(IllegalArgumentException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (IllegalArgumentException e) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (IllegalArgumentException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/NodeInfoStore.java
catch (IllegalArgumentException e) { return null; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
3
            
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(IllegalArgumentException e) { StringBuffer message = new StringBuffer("Exception occurred during compilation unit conversion:"); //$NON-NLS-1$ String lineDelimiter = Util.findLineSeparator(source); if (lineDelimiter == null) lineDelimiter = System.getProperty("line.separator");//$NON-NLS-1$ message.append(lineDelimiter); message.append("----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$ message.append(lineDelimiter); message.append(source); message.append(lineDelimiter); message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$ Util.log(e, message.toString()); throw e; }
1
runtime (Lib) IllegalStateException 25
            
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
public boolean visit(BinaryExpression binaryExpression, BlockScope scope) { switch((binaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) { case OperatorIds.AND : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameAND, scope); case OperatorIds.DIVIDE : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameDIVIDE, scope); case OperatorIds.GREATER : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER, scope); case OperatorIds.GREATER_EQUAL : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameGREATER_EQUAL, scope); case OperatorIds.LEFT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLEFT_SHIFT, scope); case OperatorIds.LESS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS, scope); case OperatorIds.LESS_EQUAL : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameLESS_EQUAL, scope); case OperatorIds.MINUS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMINUS, scope); case OperatorIds.MULTIPLY : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameMULTIPLY, scope); case OperatorIds.OR : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameOR, scope); case OperatorIds.PLUS : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNamePLUS, scope); case OperatorIds.REMAINDER : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameREMAINDER, scope); case OperatorIds.RIGHT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameRIGHT_SHIFT, scope); case OperatorIds.UNSIGNED_RIGHT_SHIFT : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT, scope); case OperatorIds.XOR : return dumpBinaryExpression(binaryExpression, TerminalTokens.TokenNameXOR, scope); default: throw new IllegalStateException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
Object decodeDefaultValue() { Object value = null; // u1 tag; int tag = u1At(this.readOffset); this.readOffset++; int constValueOffset = -1; switch (tag) { case 'Z': // boolean constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = BooleanConstant.fromValue(i4At(constValueOffset + 1) == 1); this.readOffset += 2; break; case 'I': // integer constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = IntConstant.fromValue(i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'C': // char constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = CharConstant.fromValue((char) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'B': // byte constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = ByteConstant.fromValue((byte) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'S': // short constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = ShortConstant.fromValue((short) i4At(constValueOffset + 1)); this.readOffset += 2; break; case 'D': // double constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = DoubleConstant.fromValue(doubleAt(constValueOffset + 1)); this.readOffset += 2; break; case 'F': // float constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = FloatConstant.fromValue(floatAt(constValueOffset + 1)); this.readOffset += 2; break; case 'J': // long constant constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = LongConstant.fromValue(i8At(constValueOffset + 1)); this.readOffset += 2; break; case 's': // String constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; value = StringConstant.fromValue(String.valueOf(utf8At(constValueOffset + 3, u2At(constValueOffset + 1)))); this.readOffset += 2; break; case 'e': constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] typeName = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); this.readOffset += 2; constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] constName = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); this.readOffset += 2; value = new EnumConstantSignature(typeName, constName); break; case 'c': constValueOffset = this.constantPoolOffsets[u2At(this.readOffset)] - this.structOffset; char[] className = utf8At(constValueOffset + 3, u2At(constValueOffset + 1)); value = new ClassSignature(className); this.readOffset += 2; break; case '@': value = new AnnotationInfo(this.reference, this.constantPoolOffsets, this.readOffset + this.structOffset, false, true); this.readOffset += ((AnnotationInfo) value).readOffset; break; case '[': int numberOfValues = u2At(this.readOffset); this.readOffset += 2; if (numberOfValues == 0) { value = EmptyValueArray; } else { Object[] arrayElements = new Object[numberOfValues]; value = arrayElements; for (int i = 0; i < numberOfValues; i++) arrayElements[i] = decodeDefaultValue(); } break; default: throw new IllegalStateException("Unrecognized tag " + (char) tag); //$NON-NLS-1$ } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int readRetentionPolicy(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'e': int utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] typeName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); currentOffset += 2; if (typeName.length == 38 && CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_RETENTIONPOLICY)) { utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] constName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); this.standardAnnotationTagBits |= Annotation.getRetentionPolicy(constName); } currentOffset += 2; break; case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; for (int i = 0; i < numberOfValues; i++) currentOffset = scanElementValue(currentOffset); break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int readTargetValue(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'e': int utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] typeName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); currentOffset += 2; if (typeName.length == 34 && CharOperation.equals(typeName, ConstantPool.JAVA_LANG_ANNOTATION_ELEMENTTYPE)) { utf8Offset = this.constantPoolOffsets[u2At(currentOffset)] - this.structOffset; char[] constName = utf8At(utf8Offset + 3, u2At(utf8Offset + 1)); this.standardAnnotationTagBits |= Annotation.getTargetElementType(constName); } currentOffset += 2; break; case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; if (numberOfValues == 0) { this.standardAnnotationTagBits |= TagBits.AnnotationTarget; } else { for (int i = 0; i < numberOfValues; i++) currentOffset = readTargetValue(currentOffset); } break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/AnnotationInfo.java
private int scanElementValue(int offset) { int currentOffset = offset; int tag = u1At(currentOffset); currentOffset++; switch (tag) { case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case 'Z': case 's': case 'c': currentOffset += 2; break; case 'e': currentOffset += 4; break; case '@': // none of the supported standard annotation are in the nested // level. currentOffset = scanAnnotation(currentOffset, false, false); break; case '[': int numberOfValues = u2At(currentOffset); currentOffset += 2; for (int i = 0; i < numberOfValues; i++) currentOffset = scanElementValue(currentOffset); break; default: throw new IllegalStateException(); } return currentOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
public static void collectRunningVMBootclasspath(List bootclasspaths) { /* no bootclasspath specified * we can try to retrieve the default librairies of the VM used to run * the batch compiler */ String javaversion = System.getProperty("java.version");//$NON-NLS-1$ if (javaversion != null && javaversion.equalsIgnoreCase("1.1.8")) { //$NON-NLS-1$ throw new IllegalStateException(); } /* * Handle >= JDK 1.2.2 settings: retrieve the bootclasspath */ // check bootclasspath properties for Sun, JRockit and Harmony VMs String bootclasspathProperty = System.getProperty("sun.boot.class.path"); //$NON-NLS-1$ if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) { // IBM J9 VMs bootclasspathProperty = System.getProperty("vm.boot.class.path"); //$NON-NLS-1$ if ((bootclasspathProperty == null) || (bootclasspathProperty.length() == 0)) { // Harmony using IBM VME bootclasspathProperty = System.getProperty("org.apache.harmony.boot.class.path"); //$NON-NLS-1$ } } if ((bootclasspathProperty != null) && (bootclasspathProperty.length() != 0)) { StringTokenizer tokenizer = new StringTokenizer(bootclasspathProperty, File.pathSeparator); String token; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); FileSystem.Classpath currentClasspath = FileSystem.getClasspath(token, null, null); if (currentClasspath != null) { bootclasspaths.add(currentClasspath); } } } else { // try to get all jars inside the lib folder of the java home final File javaHome = getJavaHome(); if (javaHome != null) { File[] directoriesToCheck = null; if (System.getProperty("os.name").startsWith("Mac")) {//$NON-NLS-1$//$NON-NLS-2$ directoriesToCheck = new File[] { new File(javaHome, "../Classes"), //$NON-NLS-1$ }; } else { // fall back to try to retrieve them out of the lib directory directoriesToCheck = new File[] { new File(javaHome, "lib") //$NON-NLS-1$ }; } File[][] systemLibrariesJars = Main.getLibrariesFiles(directoriesToCheck); if (systemLibrariesJars != null) { for (int i = 0, max = systemLibrariesJars.length; i < max; i++) { File[] current = systemLibrariesJars[i]; if (current != null) { for (int j = 0, max2 = current.length; j < max2; j++) { FileSystem.Classpath classpath = FileSystem.getClasspath(current[j].getAbsolutePath(), null, false, null, null); if (classpath != null) { bootclasspaths.add(classpath); } } } } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/BinaryTypeBinding.java
static Object convertMemberValue(Object binaryValue, LookupEnvironment env, char[][][] missingTypeNames) { if (binaryValue == null) return null; if (binaryValue instanceof Constant) return binaryValue; if (binaryValue instanceof ClassSignature) return env.getTypeFromSignature(((ClassSignature) binaryValue).getTypeName(), 0, -1, false, null, missingTypeNames); if (binaryValue instanceof IBinaryAnnotation) return createAnnotation((IBinaryAnnotation) binaryValue, env, missingTypeNames); if (binaryValue instanceof EnumConstantSignature) { EnumConstantSignature ref = (EnumConstantSignature) binaryValue; ReferenceBinding enumType = (ReferenceBinding) env.getTypeFromSignature(ref.getTypeName(), 0, -1, false, null, missingTypeNames); enumType = (ReferenceBinding) resolveType(enumType, env, false /* no raw conversion */); return enumType.getField(ref.getEnumConstantName(), false); } if (binaryValue instanceof Object[]) { Object[] objects = (Object[]) binaryValue; int length = objects.length; if (length == 0) return objects; Object[] values = new Object[length]; for (int i = 0; i < length; i++) values[i] = convertMemberValue(objects[i], env, missingTypeNames); return values; } // should never reach here. throw new IllegalStateException(); }
// in compiler/org/eclipse/jdt/internal/compiler/lookup/AnnotationHolder.java
Object getDefaultValue() { if (this.defaultValue instanceof UnresolvedReferenceBinding) { if (this.env == null) throw new IllegalStateException(); this.defaultValue = ((UnresolvedReferenceBinding) this.defaultValue).resolve(this.env, false); } return this.defaultValue; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static CompilationUnitDeclaration parse( org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit, NodeSearcher nodeSearcher, Map settings, int flags) { if (sourceUnit == null) { throw new IllegalStateException(); } CompilerOptions compilerOptions = new CompilerOptions(settings); boolean statementsRecovery = (flags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0; compilerOptions.performMethodsFullRecovery = statementsRecovery; compilerOptions.performStatementsRecovery = statementsRecovery; compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0; Parser parser = new CommentRecorderParser( new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, new DefaultProblemFactory()), false); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult); if (compilationUnitDeclaration.ignoreMethodBodies) { compilationUnitDeclaration.ignoreFurtherInvestigation = true; // if initial diet parse did not work, no need to dig into method bodies. return compilationUnitDeclaration; } if (nodeSearcher != null) { char[] source = parser.scanner.getSource(); int searchPosition = nodeSearcher.position; if (searchPosition < 0 || searchPosition > source.length) { // the position is out of range. There is no need to search for a node. return compilationUnitDeclaration; } compilationUnitDeclaration.traverse(nodeSearcher, compilationUnitDeclaration.scope); org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodeSearcher.found; if (node == null) { return compilationUnitDeclaration; } org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType; if (node instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration)node).parseStatements(parser, compilationUnitDeclaration); } else if (enclosingTypeDeclaration != null) { if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) { ((org.eclipse.jdt.internal.compiler.ast.Initializer) node).parseStatements(parser, enclosingTypeDeclaration, compilationUnitDeclaration); } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) { ((org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)node).parseMethods(parser, compilationUnitDeclaration); } } } else { //fill the methods bodies in order for the code to be generated //real parse of the method.... org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types; if (types != null) { for (int j = 0, typeLength = types.length; j < typeLength; j++) { types[j].parseMethods(parser, compilationUnitDeclaration); } } } return compilationUnitDeclaration; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
public static IBinding[] resolve( final IJavaElement[] elements, int apiLevel, Map compilerOptions, IJavaProject javaProject, WorkingCopyOwner owner, int flags, IProgressMonitor monitor) { final int length = elements.length; final HashMap sourceElementPositions = new HashMap(); // a map from ICompilationUnit to int[] (positions in elements) int cuNumber = 0; final HashtableOfObjectToInt binaryElementPositions = new HashtableOfObjectToInt(); // a map from String (binding key) to int (position in elements) for (int i = 0; i < length; i++) { IJavaElement element = elements[i]; if (!(element instanceof SourceRefElement)) throw new IllegalStateException(element + " is not part of a compilation unit or class file"); //$NON-NLS-1$ Object cu = element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { // source member IntArrayList intList = (IntArrayList) sourceElementPositions.get(cu); if (intList == null) { sourceElementPositions.put(cu, intList = new IntArrayList()); cuNumber++; } intList.add(i); } else { // binary member try { String key = ((BinaryMember) element).getKey(true/*open to get resolved info*/); binaryElementPositions.put(key, i); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } } } ICompilationUnit[] cus = new ICompilationUnit[cuNumber]; sourceElementPositions.keySet().toArray(cus); int bindingKeyNumber = binaryElementPositions.size(); String[] bindingKeys = new String[bindingKeyNumber]; binaryElementPositions.keysToArray(bindingKeys); class Requestor extends ASTRequestor { IBinding[] bindings = new IBinding[length]; public void acceptAST(ICompilationUnit source, CompilationUnit ast) { // TODO (jerome) optimize to visit the AST only once IntArrayList intList = (IntArrayList) sourceElementPositions.get(source); for (int i = 0; i < intList.length; i++) { final int index = intList.list[i]; SourceRefElement element = (SourceRefElement) elements[index]; DOMFinder finder = new DOMFinder(ast, element, true/*resolve binding*/); try { finder.search(); } catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ } this.bindings[index] = finder.foundBinding; } } public void acceptBinding(String bindingKey, IBinding binding) { int index = binaryElementPositions.get(bindingKey); this.bindings[index] = binding; } } Requestor requestor = new Requestor(); resolve(cus, bindingKeys, requestor, apiLevel, compilerOptions, javaProject, owner, flags, monitor); return requestor.bindings; }
// in dom/org/eclipse/jdt/core/dom/AST.java
TextEdit rewrite(IDocument document, Map options) { if (document == null) { throw new IllegalArgumentException(); } if (this.rewriter == null) { throw new IllegalStateException("Modifications record is not enabled"); //$NON-NLS-1$ } return this.rewriter.rewriteAST(document, options); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private List getClasspath() throws IllegalStateException { Main main = new Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*systemExit*/, null/*options*/, null/*progress*/); ArrayList allClasspaths = new ArrayList(); try { if ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0) { org.eclipse.jdt.internal.compiler.util.Util.collectRunningVMBootclasspath(allClasspaths); } if (this.sourcepaths != null) { for (int i = 0, max = this.sourcepaths.length; i < max; i++) { String encoding = this.sourcepathsEncodings == null ? null : this.sourcepathsEncodings[i]; main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.sourcepaths[i], encoding, true, false); } } if (this.classpaths != null) { for (int i = 0, max = this.classpaths.length; i < max; i++) { main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.classpaths[i], null, false, false); } } ArrayList pendingErrors = main.pendingErrors; if (pendingErrors != null && pendingErrors.size() != 0) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } } catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } return allClasspaths; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public ASTNode createAST(IProgressMonitor monitor) { ASTNode result = null; if (monitor != null) monitor.beginTask("", 1); //$NON-NLS-1$ try { if (this.rawSource == null && this.typeRoot == null) { throw new IllegalStateException("source not specified"); //$NON-NLS-1$ } result = internalCreateAST(monitor); } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); if (monitor != null) monitor.done(); } return result; }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void createASTs(ICompilationUnit[] compilationUnits, String[] bindingKeys, ASTRequestor requestor, IProgressMonitor monitor) { try { int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) { if (this.project == null) throw new IllegalStateException("project not specified"); //$NON-NLS-1$ if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } CompilationUnitResolver.resolve(compilationUnits, bindingKeys, requestor, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner, flags, monitor); } else { CompilationUnitResolver.parse(compilationUnits, requestor, this.apiLevel, this.compilerOptions, flags, monitor); } } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public void createASTs(String[] sourceFilePaths, String[] encodings, String[] bindingKeys, FileASTRequestor requestor, IProgressMonitor monitor) { try { int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) { if (this.classpaths == null && this.sourcepaths == null && ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) == 0)) { throw new IllegalStateException("no environment is specified"); //$NON-NLS-1$ } if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } CompilationUnitResolver.resolve(sourceFilePaths, encodings, bindingKeys, requestor, this.apiLevel, this.compilerOptions, getClasspath(), flags, monitor); } else { CompilationUnitResolver.parse(sourceFilePaths, encodings, requestor, this.apiLevel, this.compilerOptions, flags, monitor); } } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
public IBinding[] createBindings(IJavaElement[] elements, IProgressMonitor monitor) { try { if (this.project == null) throw new IllegalStateException("project or classpath not specified"); //$NON-NLS-1$ int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } if ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } return CompilationUnitResolver.resolve(elements, this.apiLevel, this.compilerOptions, this.project, this.workingCopyOwner, flags, monitor); } finally { // reset to defaults to allow reuse (and avoid leaking) initializeDefaults(); } }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private ASTNode internalCreateAST(IProgressMonitor monitor) { boolean needToResolveBindings = (this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0; switch(this.astKind) { case K_CLASS_BODY_DECLARATIONS : case K_EXPRESSION : case K_STATEMENTS : if (this.rawSource == null) { if (this.typeRoot != null) { // get the source from the type root if (this.typeRoot instanceof ICompilationUnit) { org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.typeRoot; this.rawSource = sourceUnit.getContents(); } else if (this.typeRoot instanceof IClassFile) { try { String sourceString = this.typeRoot.getSource(); if (sourceString != null) { this.rawSource = sourceString.toCharArray(); } } catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); } } } } if (this.rawSource != null) { if (this.sourceOffset + this.sourceLength > this.rawSource.length) { throw new IllegalStateException(); } return internalCreateASTForKind(); } break; case K_COMPILATION_UNIT : CompilationUnitDeclaration compilationUnitDeclaration = null; try { NodeSearcher searcher = null; org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = null; WorkingCopyOwner wcOwner = this.workingCopyOwner; if (this.typeRoot instanceof ICompilationUnit) { /* * this.compilationUnitSource is an instance of org.eclipse.jdt.internal.core.CompilationUnit that implements * both org.eclipse.jdt.core.ICompilationUnit and org.eclipse.jdt.internal.compiler.env.ICompilationUnit */ sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) this.typeRoot; /* * use a BasicCompilation that caches the source instead of using the compilationUnitSource directly * (if it is a working copy, the source can change between the parse and the AST convertion) * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75632) */ sourceUnit = new BasicCompilationUnit(sourceUnit.getContents(), sourceUnit.getPackageName(), new String(sourceUnit.getFileName()), this.project); wcOwner = ((ICompilationUnit) this.typeRoot).getOwner(); } else if (this.typeRoot instanceof IClassFile) { try { String sourceString = this.typeRoot.getSource(); if (sourceString == null) { throw new IllegalStateException(); } PackageFragment packageFragment = (PackageFragment) this.typeRoot.getParent(); BinaryType type = (BinaryType) this.typeRoot.findPrimaryType(); IBinaryType binaryType = (IBinaryType) type.getElementInfo(); // file name is used to recreate the Java element, so it has to be the toplevel .class file name char[] fileName = binaryType.getFileName(); int firstDollar = CharOperation.indexOf('$', fileName); if (firstDollar != -1) { char[] suffix = SuffixConstants.SUFFIX_class; int suffixLength = suffix.length; char[] newFileName = new char[firstDollar + suffixLength]; System.arraycopy(fileName, 0, newFileName, 0, firstDollar); System.arraycopy(suffix, 0, newFileName, firstDollar, suffixLength); fileName = newFileName; } sourceUnit = new BasicCompilationUnit(sourceString.toCharArray(), Util.toCharArrays(packageFragment.names), new String(fileName), this.project); } catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); } } else if (this.rawSource != null) { needToResolveBindings = ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0) && this.unitName != null && (this.project != null || this.classpaths != null || this.sourcepaths != null || ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0)) && this.compilerOptions != null; sourceUnit = new BasicCompilationUnit(this.rawSource, null, this.unitName == null ? "" : this.unitName, this.project); //$NON-NLS-1$ } else { throw new IllegalStateException(); } if ((this.bits & CompilationUnitResolver.PARTIAL) != 0) { searcher = new NodeSearcher(this.focalPointPosition); } int flags = 0; if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY; } if (searcher == null && ((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0)) { flags |= ICompilationUnit.IGNORE_METHOD_BODIES; } if (needToResolveBindings) { if ((this.bits & CompilationUnitResolver.BINDING_RECOVERY) != 0) { flags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY; } try { // parse and resolve compilationUnitDeclaration = CompilationUnitResolver.resolve( sourceUnit, this.project, getClasspath(), searcher, this.compilerOptions, this.workingCopyOwner, flags, monitor); } catch (JavaModelException e) { flags &= ~ICompilationUnit.ENABLE_BINDINGS_RECOVERY; compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; } } else { compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; } CompilationUnit result = CompilationUnitResolver.convert( compilationUnitDeclaration, sourceUnit.getContents(), this.apiLevel, this.compilerOptions, needToResolveBindings, wcOwner, needToResolveBindings ? new DefaultBindingResolver.BindingTables() : null, flags, monitor, this.project != null); result.setTypeRoot(this.typeRoot); return result; } finally { if (compilationUnitDeclaration != null && ((this.bits & CompilationUnitResolver.RESOLVE_BINDING) != 0)) { compilationUnitDeclaration.cleanUp(); } } } throw new IllegalStateException(); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private ASTNode internalCreateASTForKind() { final ASTConverter converter = new ASTConverter(this.compilerOptions, false, null); converter.compilationUnitSource = this.rawSource; converter.compilationUnitSourceLength = this.rawSource.length; converter.scanner.setSource(this.rawSource); AST ast = AST.newAST(this.apiLevel); ast.setDefaultNodeFlag(ASTNode.ORIGINAL); ast.setBindingResolver(new BindingResolver()); if ((this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0) { ast.setFlag(ICompilationUnit.ENABLE_STATEMENTS_RECOVERY); } converter.setAST(ast); CodeSnippetParsingUtil codeSnippetParsingUtil = new CodeSnippetParsingUtil((this.bits & CompilationUnitResolver.IGNORE_METHOD_BODIES) != 0); CompilationUnit compilationUnit = ast.newCompilationUnit(); if (this.sourceLength == -1) { this.sourceLength = this.rawSource.length; } switch(this.astKind) { case K_STATEMENTS : ConstructorDeclaration constructorDeclaration = codeSnippetParsingUtil.parseStatements( this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0); RecoveryScannerData data = constructorDeclaration.compilationResult.recoveryScannerData; if(data != null) { Scanner scanner = converter.scanner; converter.scanner = new RecoveryScanner(scanner, data.removeUnused()); converter.docParser.scanner = converter.scanner; converter.scanner.setSource(scanner.source); compilationUnit.setStatementsRecoveryData(data); } RecordedParsingInformation recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; int[][] comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); Block block = ast.newBlock(); block.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength); org.eclipse.jdt.internal.compiler.ast.Statement[] statements = constructorDeclaration.statements; if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) { if (statements[i] instanceof org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) { converter.checkAndAddMultipleLocalDeclaration(statements, i, block.statements()); } else { Statement statement = converter.convert(statements[i]); if (statement != null) { block.statements().add(statement); } } } } rootNodeToCompilationUnit(ast, compilationUnit, block, recordedParsingInformation, data); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return block; case K_EXPRESSION : org.eclipse.jdt.internal.compiler.ast.Expression expression = codeSnippetParsingUtil.parseExpression(this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true); recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); if (expression != null) { Expression expression2 = converter.convert(expression); rootNodeToCompilationUnit(expression2.getAST(), compilationUnit, expression2, codeSnippetParsingUtil.recordedParsingInformation, null); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return expression2; } else { CategorizedProblem[] problems = recordedParsingInformation.problems; if (problems != null) { compilationUnit.setProblems(problems); } ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return compilationUnit; } case K_CLASS_BODY_DECLARATIONS : final org.eclipse.jdt.internal.compiler.ast.ASTNode[] nodes = codeSnippetParsingUtil.parseClassBodyDeclarations( this.rawSource, this.sourceOffset, this.sourceLength, this.compilerOptions, true, (this.bits & CompilationUnitResolver.STATEMENT_RECOVERY) != 0); recordedParsingInformation = codeSnippetParsingUtil.recordedParsingInformation; comments = recordedParsingInformation.commentPositions; if (comments != null) { converter.buildCommentsTable(compilationUnit, comments); } compilationUnit.setLineEndTable(recordedParsingInformation.lineEnds); if (nodes != null) { // source has no syntax error or the statement recovery is enabled TypeDeclaration typeDeclaration = converter.convert(nodes); typeDeclaration.setSourceRange(this.sourceOffset, this.sourceOffset + this.sourceLength); rootNodeToCompilationUnit(typeDeclaration.getAST(), compilationUnit, typeDeclaration, codeSnippetParsingUtil.recordedParsingInformation, null); ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return typeDeclaration; } else { // source has syntax error and the statement recovery is disabled CategorizedProblem[] problems = recordedParsingInformation.problems; if (problems != null) { compilationUnit.setProblems(problems); } ast.setDefaultNodeFlag(0); ast.setOriginalModificationCount(ast.modificationCount()); return compilationUnit; } } throw new IllegalStateException(); }
3
            
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
1
            
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
private List getClasspath() throws IllegalStateException { Main main = new Main(new PrintWriter(System.out), new PrintWriter(System.err), false/*systemExit*/, null/*options*/, null/*progress*/); ArrayList allClasspaths = new ArrayList(); try { if ((this.bits & CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH) != 0) { org.eclipse.jdt.internal.compiler.util.Util.collectRunningVMBootclasspath(allClasspaths); } if (this.sourcepaths != null) { for (int i = 0, max = this.sourcepaths.length; i < max; i++) { String encoding = this.sourcepathsEncodings == null ? null : this.sourcepathsEncodings[i]; main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.sourcepaths[i], encoding, true, false); } } if (this.classpaths != null) { for (int i = 0, max = this.classpaths.length; i < max; i++) { main.processPathEntries( Main.DEFAULT_SIZE_CLASSPATH, allClasspaths, this.classpaths[i], null, false, false); } } ArrayList pendingErrors = main.pendingErrors; if (pendingErrors != null && pendingErrors.size() != 0) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } } catch (IllegalArgumentException e) { throw new IllegalStateException("invalid environment settings"); //$NON-NLS-1$ } return allClasspaths; }
5
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(IllegalStateException e) { this.logger.logWrongJDK(); this.proceed = false; return null; }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
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 */ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (IllegalStateException ise) { // happen when there's no workspace (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=216817) // or when it is shutting down (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=60687) return System.getProperty("file.encoding"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
2
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (IllegalStateException e) { // convert ASTParser's complaints into old form throw new IllegalArgumentException(); }
2
runtime (Domain) ImageBuilderInternalException
public class ImageBuilderInternalException extends RuntimeException {

private static final long serialVersionUID = 28252254530437336L; // backward compatible
protected CoreException coreException;

public ImageBuilderInternalException(CoreException e) {
	this.coreException = e;
}

public CoreException getThrowable() {
	return this.coreException;
}

public void printStackTrace() {
	if (this.coreException != null) {
		System.err.println(this);
		System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$
		this.coreException.printStackTrace();
	} else {
		super.printStackTrace();
	}
}
}
0 0 0 1
            
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (ImageBuilderInternalException e) { Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException while building: " + this.currentProject.getName()); //$NON-NLS-1$ createInconsistentBuildMarker(e.coreException); }
0 0
unknown (Lib) IndexOutOfBoundsException 4
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
0 0 45
            
// in model/org/eclipse/jdt/internal/core/Member.java
catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.wasAcr = true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D (added with fix of 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D if(DEBUG) { System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.wasAcr = true; }
// in dom/org/eclipse/jdt/core/dom/NodeFinder.java
catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 return null; }
9
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
0
checked (Domain) InstallException
public class InstallException extends Exception {

	private static final long serialVersionUID = -5870897747810654203L;	// backward compatible
/**
 * Constructs a <code>InstallException</code> with no detail  message.
 */
public InstallException() {
	super();
}
/**
 * Constructs a <code>InstallException</code> with the specified
 * detail message.
 *
 * @param   s   the detail message.
 */
public InstallException(String s) {
	super(s);
}
}
2
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate( char[] codeSnippet, char[][] contextLocalVariableTypeNames, char[][] contextLocalVariableNames, int[] contextLocalVariableModifiers, char[] contextDeclaringTypeName, boolean contextIsStatic, boolean contextIsConstructorCall, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { // Initialialize context this.localVariableTypeNames = contextLocalVariableTypeNames; this.localVariableNames = contextLocalVariableNames; this.localVariableModifiers = contextLocalVariableModifiers; this.declaringTypeName = contextDeclaringTypeName; this.isStatic = contextIsStatic; this.isConstructorCall = contextIsConstructorCall; deployCodeSnippetClassIfNeeded(requestor); try { // Install new variables if needed class ForwardingRequestor implements IRequestor { boolean hasErrors = false; public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) { return requestor.acceptClassFiles(classFiles, codeSnippetClassName); } public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) { requestor.acceptProblem(problem, fragmentSource, fragmentKind); if (problem.isError()) { this.hasErrors = true; } } } ForwardingRequestor forwardingRequestor = new ForwardingRequestor(); if (this.varsChanged) { evaluateVariables(environment, options, forwardingRequestor, problemFactory); } // Compile code snippet if there was no errors while evaluating the variables if (!forwardingRequestor.hasErrors) { Evaluator evaluator = new CodeSnippetEvaluator( codeSnippet, this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); // Send code snippet on target if (classes != null && classes.length > 0) { char[] simpleClassName = evaluator.getClassName(); char[] pkgName = getPackageName(); char[] qualifiedClassName = pkgName.length == 0 ? simpleClassName : CharOperation.concat(pkgName, simpleClassName, '.'); CODE_SNIPPET_COUNTER++; if (!requestor.acceptClassFiles(classes, qualifiedClassName)) throw new InstallException(); } } } finally { // Reinitialize context to default values this.localVariableTypeNames = null; this.localVariableNames = null; this.localVariableModifiers = null; this.declaringTypeName = null; this.isStatic = true; this.isConstructorCall = false; } }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariables(INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { deployCodeSnippetClassIfNeeded(requestor); VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); if (classes != null) { if (classes.length > 0) { // Sort classes so that enclosing types are cached before nested types // otherwise an AbortCompilation is thrown in 1.5 mode since the enclosing type // is needed to resolve a nested type Util.sort(classes, new Util.Comparer() { public int compare(Object a, Object b) { if (a == b) return 0; ClassFile enclosing = ((ClassFile) a).enclosingClassFile; while (enclosing != null) { if (enclosing == b) return 1; enclosing = enclosing.enclosingClassFile; } return -1; } }); // Send classes if (!requestor.acceptClassFiles(classes, null)) { throw new InstallException(); } // Remember that the variables have been installed int count = this.variableCount; GlobalVariable[] variablesCopy = new GlobalVariable[count]; System.arraycopy(this.variables, 0, variablesCopy, 0, count); this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, count); VAR_CLASS_COUNTER++; } this.varsChanged = false; }
0 5
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
private void deployCodeSnippetClassIfNeeded(IRequestor requestor) throws InstallException { if (this.codeSnippetBinary == null) { // Deploy CodeSnippet class (only once) if (!requestor.acceptClassFiles( new ClassFile[] { new ClassFile() { public byte[] getBytes() { return getCodeSnippetBytes(); } public char[][] getCompoundName() { return EvaluationConstants.ROOT_COMPOUND_NAME; } } }, null)) throw new InstallException();
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate( char[] codeSnippet, char[][] contextLocalVariableTypeNames, char[][] contextLocalVariableNames, int[] contextLocalVariableModifiers, char[] contextDeclaringTypeName, boolean contextIsStatic, boolean contextIsConstructorCall, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { // Initialialize context this.localVariableTypeNames = contextLocalVariableTypeNames; this.localVariableNames = contextLocalVariableNames; this.localVariableModifiers = contextLocalVariableModifiers; this.declaringTypeName = contextDeclaringTypeName; this.isStatic = contextIsStatic; this.isConstructorCall = contextIsConstructorCall; deployCodeSnippetClassIfNeeded(requestor); try { // Install new variables if needed class ForwardingRequestor implements IRequestor { boolean hasErrors = false; public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) { return requestor.acceptClassFiles(classFiles, codeSnippetClassName); } public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) { requestor.acceptProblem(problem, fragmentSource, fragmentKind); if (problem.isError()) { this.hasErrors = true; } } } ForwardingRequestor forwardingRequestor = new ForwardingRequestor(); if (this.varsChanged) { evaluateVariables(environment, options, forwardingRequestor, problemFactory); } // Compile code snippet if there was no errors while evaluating the variables if (!forwardingRequestor.hasErrors) { Evaluator evaluator = new CodeSnippetEvaluator( codeSnippet, this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); // Send code snippet on target if (classes != null && classes.length > 0) { char[] simpleClassName = evaluator.getClassName(); char[] pkgName = getPackageName(); char[] qualifiedClassName = pkgName.length == 0 ? simpleClassName : CharOperation.concat(pkgName, simpleClassName, '.'); CODE_SNIPPET_COUNTER++; if (!requestor.acceptClassFiles(classes, qualifiedClassName)) throw new InstallException(); } } } finally { // Reinitialize context to default values this.localVariableTypeNames = null; this.localVariableNames = null; this.localVariableModifiers = null; this.declaringTypeName = null; this.isStatic = true; this.isConstructorCall = false; } }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluate(char[] codeSnippet, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException { this.evaluate( codeSnippet, null, null, null, null, true, false, environment, options, requestor, problemFactory); }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariable(GlobalVariable variable, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { this.evaluate(variable.getName(), environment, options, requestor, problemFactory); }
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
public void evaluateVariables(INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException { deployCodeSnippetClassIfNeeded(requestor); VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory); ClassFile[] classes = evaluator.getClasses(); if (classes != null) { if (classes.length > 0) { // Sort classes so that enclosing types are cached before nested types // otherwise an AbortCompilation is thrown in 1.5 mode since the enclosing type // is needed to resolve a nested type Util.sort(classes, new Util.Comparer() { public int compare(Object a, Object b) { if (a == b) return 0; ClassFile enclosing = ((ClassFile) a).enclosingClassFile; while (enclosing != null) { if (enclosing == b) return 1; enclosing = enclosing.enclosingClassFile; } return -1; } }); // Send classes if (!requestor.acceptClassFiles(classes, null)) { throw new InstallException(); } // Remember that the variables have been installed int count = this.variableCount; GlobalVariable[] variablesCopy = new GlobalVariable[count]; System.arraycopy(this.variables, 0, variablesCopy, 0, count); this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, count); VAR_CLASS_COUNTER++; } this.varsChanged = false; }
4
            
// in eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
catch (InstallException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
// in model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
catch (InstallException e) { handleInstallException(e); }
0 0
unknown (Lib) InstantiationException 0 0 0 2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
2
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (InstantiationException e) { // should not happen throw new org.eclipse.jdt.internal.compiler.problem.AbortCompilation(); }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InstantiationException e) { // all concrete AST node classes can be instantiated // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
unknown (Lib) InterruptedException 0 0 0 18
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch(InterruptedException e){ // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // background indexing was interrupted }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
catch(InterruptedException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
catch(InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (InterruptedException e) { return projectInfo.secondaryTypes; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (InterruptedException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (InterruptedException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (InterruptedException e) { // Do nothing }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (InterruptedException e) { // continue }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (InterruptedException ignored) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InterruptedException ignore) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InterruptedException e) { // ignore }
0 0
runtime (Domain) InvalidCursorLocation
public class InvalidCursorLocation extends RuntimeException {

	public String irritant;

	/* Possible irritants */
	public static final String NO_COMPLETION_INSIDE_UNICODE = "No Completion Inside Unicode"; //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_COMMENT = "No Completion Inside Comment";      //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_STRING = "No Completion Inside String";        //$NON-NLS-1$
	public static final String NO_COMPLETION_INSIDE_NUMBER = "No Completion Inside Number";        //$NON-NLS-1$

	private static final long serialVersionUID = -3443160725735779590L; // backward compatible

public InvalidCursorLocation(String irritant){
	this.irritant = irritant;
}
}
4
            
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public final void getNextUnicodeChar() throws InvalidInputException { int temp = this.currentPosition; // the \ is already read super.getNextUnicodeChar(); if(this.cursorLocation > temp) { this.unicodeCharSize += (this.currentPosition - temp); } if (temp < this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { int token = super.scanNumber(dotPrefix); // consider completion just before a number to be ok, will insert before it if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER); } return token; }
0 0 2
            
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (InvalidCursorLocation e) { // may eventually report a usefull error (added to fix 99629) if(DEBUG) { System.out.println("Exception caught by CompletionEngine:"); //$NON-NLS-1$ e.printStackTrace(System.out); } }
0 0
checked (Domain) InvalidInputException
public class InvalidInputException extends Exception {

	private static final long serialVersionUID = 2909732853499731592L; // backward compatible

/**
 * Creates a new exception with no detail message.
 */
public InvalidInputException() {
	super();
}

/**
 * Creates a new exception with the given detail message.
 * @param message the detail message
 */
public InvalidInputException(String message) {
	super(message);
}
}
149
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { if (this.tagSourceStart>this.cursorLocation) { return super.parseArguments(receiver); } // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && getCurrentTokenType() == TerminalTokens.TokenNameRPAREN) { this.lineStarted = true; return createMethodReference(receiver, null); } Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } if (this.index >= this.scanner.eofPosition) { int argumentStart = ((ASTNode)typeRef).sourceStart; Object argument = createArgumentReference(this.scanner.getCurrentIdentifierSource(), 0, false, typeRef, null, (((long)argumentStart)<<32)+this.tokenPreviousPosition-1); return syntaxRecoverArgumentType(receiver, arguments, argument); } if (this.index >= this.cursorLocation) { if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token == null || singleTypeReference.token.length == 0) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens == null || qualifiedTypeReference.tokens.length < qualifiedTypeReference.sourcePositions.length) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); return syntaxRecoverArgumentType(receiver, arguments, argument); } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
public static boolean isDigit(char c) throws InvalidInputException { if(c < ScannerHelper.MAX_OBVIOUS) { return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0; } if (Character.isDigit(c)) { throw new InvalidInputException(Scanner.INVALID_DIGIT); } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { TypeReference argTypeRef = (TypeReference) typeRef; if (dim > 0) { long pos = (((long) argTypeRef.sourceStart) << 32) + argTypeRef.sourceEnd; if (typeRef instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef; argTypeRef = new JavadocArraySingleTypeReference(singleRef.token, dim, pos); } else { JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) typeRef; argTypeRef = new JavadocArrayQualifiedTypeReference(qualifRef, dim); } } int argEnd = argTypeRef.sourceEnd; if (dim > 0) { argEnd = (int) dimPositions[dim-1]; if (isVarargs) { argTypeRef.bits |= ASTNode.IsVarArgs; // set isVarArgs } } if (argNamePos >= 0) argEnd = (int) argNamePos; return new JavadocArgumentExpression(name, argTypeRef.sourceStart, argEnd, argTypeRef); } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } // Create field JavadocFieldReference field = new JavadocFieldReference(this.identifierStack[0], this.identifierPositionStack[0]); field.receiver = typeRef; field.tagSourceStart = this.tagSourceStart; field.tagSourceEnd = this.tagSourceEnd; field.tagValue = this.tagValue; return field; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; // Decide whether we have a constructor or not boolean isConstructor = false; int length = this.identifierLengthStack[0]; // may be > 1 for member class constructor reference if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } isConstructor = CharOperation.equals(this.identifierStack[length-1], name); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } else { if (typeRef instanceof JavadocSingleTypeReference) { char[] name = ((JavadocSingleTypeReference)typeRef).token; isConstructor = CharOperation.equals(this.identifierStack[length-1], name); } else if (typeRef instanceof JavadocQualifiedTypeReference) { char[][] tokens = ((JavadocQualifiedTypeReference)typeRef).tokens; int last = tokens.length-1; isConstructor = CharOperation.equals(this.identifierStack[length-1], tokens[last]); if (isConstructor) { boolean valid = true; if (valid) { for (int i=0; i<length-1 && valid; i++) { valid = CharOperation.equals(this.identifierStack[i], tokens[i]); } } if (!valid) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidMemberTypeQualification((int)(this.identifierPositionStack[0]>>>32), (int)this.identifierPositionStack[length-1], -1); } return null; } } } else { throw new InvalidInputException(); } } // Create node if (arguments == null) { if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1]); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } else { JavadocArgumentExpression[] expressions = new JavadocArgumentExpression[arguments.size()]; arguments.toArray(expressions); if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.arguments = expressions; allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1], expressions); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final void jumpOverMethodBody() { this.wasAcr = false; int found = 1; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; // ---------Consume white space and handles startPosition--------- boolean isWhiteSpace; do { this.startPosition = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); } else { if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { pushLineSeparator(); } isWhiteSpace = CharOperation.isWhitespace(this.currentCharacter); } } while (isWhiteSpace); // -------consume token until } is found--------- NextToken: switch (this.currentCharacter) { case '{' : found++; break NextToken; case '}' : found--; if (found == 0) return; break NextToken; case '\'' : { boolean test; test = getNextChar('\\'); if (test) { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } else { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } getNextChar('\''); break NextToken; } case '"' : try { try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { return; } if (this.currentCharacter == '\r'){ if (this.source[this.currentPosition] == '\n') this.currentPosition++; break NextToken; // the string cannot go further that the line } if (this.currentCharacter == '\n'){ break; // the string cannot go further that the line } if (this.currentCharacter == '\\') { try { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } catch (InvalidInputException ex) { // ignore } } try { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } catch (InvalidInputException ex) { // ignore } } } catch (IndexOutOfBoundsException e) { return; } break NextToken; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment try { this.lastCommentLinePosition = this.currentPosition; //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code inside the catch(IndexOutOfBoundsException e) below throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; getNextUnicodeChar(); } } recordComment(TokenNameCOMMENT_LINE); if (this.recordLineSeparator && ((this.currentCharacter == '\r') || (this.currentCharacter == '\n'))) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } } catch (IndexOutOfBoundsException e) { //an eof will then be generated this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (!this.tokenizeComments) { this.currentPosition++; } } break NextToken; } if (test > 0) { //traditional and javadoc comment boolean isJavadoc = false; try { //get the next char boolean star = false; int previous; boolean isUnicode = false; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { return; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } recordComment(isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK); this.commentTagStarts[this.commentPtr] = firstTag; } catch (IndexOutOfBoundsException e) { return; } break NextToken; } break NextToken; } default : try { char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { scanIdentifierOrKeyword(); break NextToken; } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { scanNumber(false); break NextToken; } else { break NextToken; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate break NextToken; } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { break NextToken; } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) { scanIdentifierOrKeyword(); break NextToken; } // if (ScannerHelper.isDigit(this.currentCharacter)) { // scanNumber(false); // break NextToken; // } } catch (InvalidInputException ex) { // ignore } } } //-----------------end switch while try-------------------- } catch (IndexOutOfBoundsException e) { // ignore } catch (InvalidInputException e) { // ignore } return; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); int start = this.scanner.getCurrentTokenStartPosition(); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && this.currentTokenType == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } this.lineStarted = true; return createMethodReference(receiver, null); } break nextArg; } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { break nextArg; } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseQualifiedName(boolean reset) throws InvalidInputException { // Reset identifier stack if requested if (reset) { this.identifierPtr = -1; this.identifierLengthPtr = -1; } // Scan tokens int primitiveToken = -1; int parserKind = this.kind & PARSER_KIND; nextToken : for (int iToken = 0; ; iToken++) { int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameIdentifier : if (((iToken & 1) != 0)) { // identifiers must be odd tokens break nextToken; } pushIdentifier(iToken == 0, false); consumeToken(); break; case TerminalTokens.TokenNameDOT : if ((iToken & 1) == 0) { // dots must be even tokens throw new InvalidInputException(); } consumeToken(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: if (iToken == 0) { pushIdentifier(true, true); primitiveToken = token; consumeToken(); break nextToken; } // Fall through default case to verify that we do not leave on a dot //$FALL-THROUGH$ default : if (iToken == 0) { if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return null; } if ((iToken & 1) == 0) { // cannot leave on a dot switch (parserKind) { case COMPLETION_PARSER: if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return syntaxRecoverQualifiedName(primitiveToken); case DOM_PARSER: if (this.currentTokenType != -1) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } // $FALL-THROUGH$ - fall through default case to raise exception default: throw new InvalidInputException(); } } break nextToken; } } // Reset position: we want to rescan last token if (parserKind != COMPLETION_PARSER && this.currentTokenType != -1) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return createTypeReference(primitiveToken); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { MethodRefParameter argument = this.ast.newMethodRefParameter(); ASTNode node = (ASTNode) typeRef; int argStart = node.getStartPosition(); int argEnd = node.getStartPosition()+node.getLength()-1; if (dim > 0) argEnd = (int) dimPositions[dim-1]; if (argNamePos >= 0) argEnd = (int) argNamePos; if (name.length != 0) { final SimpleName argName = new SimpleName(this.ast); argName.internalSetIdentifier(new String(name)); argument.setName(argName); int argNameStart = (int) (argNamePos >>> 32); argName.setSourceRange(argNameStart, argEnd-argNameStart+1); } Type argType = null; if (node.getNodeType() == ASTNode.PRIMITIVE_TYPE) { argType = (PrimitiveType) node; // if (dim > 0) { // argType = this.ast.newArrayType(argType, dim); // argType.setSourceRange(argStart, ((int) dimPositions[dim-1])-argStart+1); // } } else { Name argTypeName = (Name) node; argType = this.ast.newSimpleType(argTypeName); argType.setSourceRange(argStart, node.getLength()); } if (dim > 0 && !isVarargs) { for (int i=0; i<dim; i++) { argType = this.ast.newArrayType(argType); argType.setSourceRange(argStart, ((int) dimPositions[i])-argStart+1); } } argument.setType(argType); argument.setSourceRange(argStart, argEnd - argStart + 1); return argument; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { MemberRef fieldRef = this.ast.newMemberRef(); SimpleName fieldName = new SimpleName(this.ast); fieldName.internalSetIdentifier(new String(this.identifierStack[0])); fieldRef.setName(fieldName); int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; fieldName.setSourceRange(start, end - start + 1); if (receiver == null) { start = this.memberStart; fieldRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; fieldRef.setQualifier(typeRef); start = typeRef.getStartPosition(); end = fieldName.getStartPosition()+fieldName.getLength()-1; fieldRef.setSourceRange(start, end-start+1); } return fieldRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Create method ref MethodRef methodRef = this.ast.newMethodRef(); SimpleName methodName = new SimpleName(this.ast); int length = this.identifierLengthStack[0] - 1; // may be > 0 for member class constructor reference methodName.internalSetIdentifier(new String(this.identifierStack[length])); methodRef.setName(methodName); int start = (int) (this.identifierPositionStack[length] >>> 32); int end = (int) this.identifierPositionStack[length]; methodName.setSourceRange(start, end - start + 1); // Set qualifier if (receiver == null) { start = this.memberStart; methodRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; methodRef.setQualifier(typeRef); start = typeRef.getStartPosition(); } // Add arguments if (arguments != null) { Iterator parameters = arguments.listIterator(); while (parameters.hasNext()) { MethodRefParameter param = (MethodRefParameter) parameters.next(); methodRef.parameters().add(param); } } methodRef.setSourceRange(start, this.scanner.getCurrentTokenEndPosition()-start+1); return methodRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
15
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
catch (ClassCastException ex) { throw new InvalidInputException(); }
67
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException { char[] src = this.source; // only look for newer task: tags if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { return; } int foundTaskIndex = this.foundTaskCount; char previous = src[commentStart+1]; // should be '*' or '/' for ( int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) { char[] tag = null; char[] priority = null; // check for tag occurrence only if not ambiguous with javadoc tag if (previous != '@') { nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) { tag = this.taskTags[itag]; int tagLength = tag.length; if (tagLength == 0) continue nextTag; // ensure tag is not leaded with letter if tag starts with a letter if (ScannerHelper.isJavaIdentifierStart(this.complianceLevel, tag[0])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, previous)) { continue nextTag; } } for (int t = 0; t < tagLength; t++) { char sc, tc; int x = i+t; if (x >= this.eofPosition || x >= commentEnd) continue nextTag; // case sensitive check if ((sc = src[i + t]) != (tc = tag[t])) { // case insensitive check if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { continue nextTag; } } } // ensure tag is not followed with letter if tag finishes with a letter if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i+tagLength-1])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i + tagLength])) continue nextTag; } if (this.foundTaskTags == null) { this.foundTaskTags = new char[5][]; this.foundTaskMessages = new char[5][]; this.foundTaskPriorities = new char[5][]; this.foundTaskPositions = new int[5][]; } else if (this.foundTaskCount == this.foundTaskTags.length) { System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount); } priority = this.taskPriorities != null && itag < this.taskPriorities.length ? this.taskPriorities[itag] : null; this.foundTaskTags[this.foundTaskCount] = tag; this.foundTaskPriorities[this.foundTaskCount] = priority; this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 }; this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; this.foundTaskCount++; i += tagLength - 1; // will be incremented when looping break nextTag; } } previous = src[i]; } boolean containsEmptyTask = false; for (int i = foundTaskIndex; i < this.foundTaskCount; i++) { // retrieve message start and end positions int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length; int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 : commentEnd - 1; // at most beginning of next task if (max_value < msgStart) { max_value = msgStart; // would only occur if tag is before EOF. } int end = -1; char c; for (int j = msgStart; j < max_value; j++) { if ((c = src[j]) == '\n' || c == '\r') { end = j - 1; break; } } if (end == -1) { for (int j = max_value; j > msgStart; j--) { if ((c = src[j]) == '*') { end = j - 1; break; } } if (end == -1) end = max_value; } if (msgStart == end) { // if the description is empty, we might want to see if two tags are not sharing the same message // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797 containsEmptyTask = true; continue; } // trim the message // we don't trim the beginning of the message to be able to show it after the task tag while (CharOperation.isWhitespace(src[end]) && msgStart <= end) end--; // update the end position of the task this.foundTaskPositions[i][1] = end; // get the message source final int messageLength = end - msgStart + 1; char[] message = new char[messageLength]; System.arraycopy(src, msgStart, message, 0, messageLength); this.foundTaskMessages[i] = message; } if (containsEmptyTask) { for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) { if (this.foundTaskMessages[i].length == 0) { loop: for (int j = i + 1; j < max; j++) { if (this.foundTaskMessages[j].length != 0) { this.foundTaskMessages[i] = this.foundTaskMessages[j]; this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1]; break loop; } } } } } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix) throws InvalidInputException { consumeDigits(radix, false); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private final int consumeDigits0(int radix, int usingUnderscore, int invalidPosition, boolean expectingDigitFirst) throws InvalidInputException { int kind = 0; if (getNextChar('_')) { if (expectingDigitFirst) { return invalidPosition; } kind = usingUnderscore; while (getNextChar('_')) {/*empty */} } if (getNextCharAsDigit(radix)) { // continue to read digits or underscore while (getNextCharAsDigit(radix)) {/*empty */} int kind2 = consumeDigits0(radix, usingUnderscore, invalidPosition, false); if (kind2 == 0) { return kind; } return kind2; } if (kind == usingUnderscore) return invalidPosition; return kind; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final boolean getNextCharAsDigit() throws InvalidInputException { //BOOLEAN //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //Both previous lines are true if the currentCharacter is a digit //On false, no side effect has occured. //ALL getNextChar.... ARE OPTIMIZED COPIES if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront return false; int temp = this.currentPosition; try { if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; this.withoutUnicodePtr--; return false; } return true; } else { if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; return false; } if (this.withoutUnicodePtr != 0) unicodeStore(); return true; } } catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; } catch(InvalidInputException e) { this.currentPosition = temp; return false; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException { //BOOLEAN //handle the case of unicode. Jump over the next whiteSpace //making startPosition pointing on the next available char //On false, the currentCharacter is filled up with a potential //correct char this.wasAcr = false; getNextUnicodeChar(); return CharOperation.isWhitespace(this.currentCharacter); }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object ref, long[] dimPositions, long argNamePos) throws InvalidInputException { FormatJavadocReference typeRef = (FormatJavadocReference) ref; if (dim > 0) { typeRef.sourceEnd = (int) dimPositions[dim-1]; } if (argNamePos >= 0) typeRef.sourceEnd = (int) argNamePos; return ref; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int start = receiver == null ? this.memberStart : ((FormatJavadocReference)receiver).sourceStart; int lineStart = this.scanner.getLineNumber(start); return new FormatJavadocReference(start, (int) this.identifierPositionStack[0], lineStart); }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int start = receiver == null ? this.memberStart : ((FormatJavadocReference) receiver).sourceStart; int lineStart = this.scanner.getLineNumber(start); return new FormatJavadocReference(start, this.scanner.getCurrentTokenEndPosition(), lineStart); }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseHtmlTag(int previousPosition, int endTextPosition) throws InvalidInputException { if (!this.parseHtmlTags) return false; boolean closing = false; boolean valid = false; boolean incremented = false; int start = this.scanner.currentPosition; int currentPosition = start; int htmlPtr = this.htmlTagsPtr; char firstChar = peekChar(); boolean hasWhitespaces = firstChar == ' ' || ScannerHelper.isWhitespace(firstChar); try { int token = readTokenAndConsume(); char[] htmlTag; int htmlIndex; switch (token) { case TerminalTokens.TokenNameIdentifier: // HTML tag opening htmlTag = this.scanner.getCurrentIdentifierSource(); htmlIndex = getHtmlTagIndex(htmlTag); if (htmlIndex == JAVADOC_TAGS_ID_MASK) return false; if (htmlPtr >= 0) { int lastHtmlTagIndex = getHtmlTagIndex(this.htmlTags[htmlPtr]); if ((lastHtmlTagIndex & JAVADOC_TAGS_ID_MASK) == JAVADOC_IMMUTABLE_TAGS_ID) { // Do not accept tags inside immutable tags except the <pre> tag if ((htmlIndex & JAVADOC_TAGS_ID_MASK) == JAVADOC_CODE_TAGS_ID) { FormatJavadocBlock previousBlock = (FormatJavadocBlock) this.astStack[this.astPtr]; FormatJavadocNode parentNode = previousBlock; FormatJavadocNode lastNode = parentNode; while (lastNode.getLastNode() != null) { parentNode = lastNode; lastNode = lastNode.getLastNode(); } if (lastNode.isText()) { FormatJavadocText text = (FormatJavadocText) lastNode; if (text.separatorsPtr == -1) { break; } } } return false; } } if ((htmlIndex & JAVADOC_TAGS_ID_MASK) > JAVADOC_SINGLE_TAGS_ID) { if (this.htmlTagsPtr == -1 || !CharOperation.equals(this.htmlTags[this.htmlTagsPtr], htmlTag, false)) { if (++this.htmlTagsPtr == 0) { // lazy initialization this.htmlTags = new char[AST_STACK_INCREMENT][]; } else { // resize if needed if (this.htmlTagsPtr == this.htmlTags.length) { System.arraycopy(this.htmlTags, 0, (this.htmlTags = new char[this.htmlTags.length + AST_STACK_INCREMENT][]), 0, this.htmlTagsPtr); } } this.htmlTags[this.htmlTagsPtr] = htmlTag; incremented = true; } } // Accept xhtml syntax currentPosition = this.scanner.currentPosition; if (readToken() == TerminalTokens.TokenNameDIVIDE) { consumeToken(); } break; case TerminalTokens.TokenNameDIVIDE: // HTML tag closing if (this.htmlTagsPtr == -1) return false; htmlTag = this.htmlTags[this.htmlTagsPtr]; if ((token = readTokenAndConsume()) != TerminalTokens.TokenNameIdentifier) { // not a closing html tag return false; } char[] identifier = this.scanner.getCurrentIdentifierSource(); htmlIndex = getHtmlTagIndex(identifier); if (htmlIndex == JAVADOC_TAGS_ID_MASK) return false; int ptr = this.htmlTagsPtr; while (!CharOperation.equals(htmlTag, identifier, false)) { if (this.htmlTagsPtr <= 0) { // consider the closing tag as invalid this.htmlTagsPtr = ptr; return false; } this.htmlTagsPtr--; htmlTag = this.htmlTags[this.htmlTagsPtr]; } // set closing flag htmlIndex |= JAVADOC_CLOSED_TAG; closing = true; currentPosition = this.scanner.currentPosition; break; default: return false; } // Looking for tag closing switch (readTokenAndConsume()) { case TerminalTokens.TokenNameLESS: case TerminalTokens.TokenNameLESS_EQUAL: // consider that the closing '>' is missing return false; case TerminalTokens.TokenNameGREATER: // simple tag without attributes break; case TerminalTokens.TokenNameGREATER_EQUAL: case TerminalTokens.TokenNameRIGHT_SHIFT: case TerminalTokens.TokenNameRIGHT_SHIFT_EQUAL: // simple tag without attributes, but the closing '>' is followed by an '=' or '>' break; default: this.index = currentPosition; loop: while (true) { // currentPosition = this.index; switch (readChar()) { case '<': if (hasWhitespaces) { // not 100% sure this is a tag definition => give up return false; } // opening tag => consider the current one as closed this.index = currentPosition; this.scanner.startPosition = currentPosition; this.scanner.currentPosition = currentPosition; this.scanner.currentCharacter = '<'; break loop; case '>': // simple tag without attributes this.scanner.startPosition = this.index; this.scanner.currentPosition = this.index; this.scanner.currentCharacter = peekChar(); break loop; default: break; } if (this.index >= this.javadocTextEnd) { // the end of the comment is reached => consider current tag as closed this.index = currentPosition; this.scanner.startPosition = currentPosition; this.scanner.currentPosition = currentPosition; break; } } } // Push texts if (this.lineStarted && this.textStart != -1 && this.textStart < endTextPosition) { pushText(this.textStart, endTextPosition, -1, htmlPtr); } pushText(previousPosition, this.index, htmlIndex, this.htmlTagsPtr); this.textStart = -1; valid = true; } finally { if (valid) { if (closing) { this.htmlTagsPtr--; } } else if (!this.abort) { if (incremented) { this.htmlTagsPtr--; if (this.htmlTagsPtr == -1) this.htmlTags = null; } this.scanner.resetTo(start, this.scanner.eofPosition-1); this.index = start; } } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseParam() throws InvalidInputException { boolean valid = super.parseParam(); if (!valid) { this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); this.index = this.tagSourceEnd+1; char ch = peekChar(); // Try to push an identifier in the stack, otherwise restart from the end tag position if (ch == ' ' || ScannerHelper.isWhitespace(ch)) { int token = this.scanner.getNextToken(); if (token == TerminalTokens.TokenNameIdentifier) { ch = peekChar(); if (ch == ' ' || ScannerHelper.isWhitespace(ch)) { pushIdentifier(true, false); pushParamName(false); this.index = this.scanner.currentPosition; valid = true; } } this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); } this.tagValue = TAG_OTHERS_VALUE; // tag is invalid, do not keep the parsed tag value } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseReference() throws InvalidInputException { boolean valid = super.parseReference(); if (!valid) { this.scanner.resetTo(this.tagSourceEnd+1, this.javadocEnd); this.index = this.tagSourceEnd+1; this.tagValue = TAG_OTHERS_VALUE; // tag is invalid, do not keep the parsed tag value } return valid; }
// in formatter/org/eclipse/jdt/internal/formatter/FormatterCommentParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Do not parse javadoc tag inside <pre>...</pre> tags if (this.htmlTagsPtr >= 0) { int ptr = this.htmlTagsPtr; while (ptr >= 0) { if (getHtmlTagIndex(this.htmlTags[ptr--]) == JAVADOC_CODE_TAGS_ID) { if (this.textStart == -1) this.textStart = this.inlineTagStarted ? this.inlineTagStart : previousPosition; this.inlineTagStarted = false; return true; } } } // Read tag name int ptr = this.astPtr; this.tagSourceStart = previousPosition; this.scanner.startPosition = this.index; this.scanner.currentCharacter = readChar(); switch (this.scanner.currentCharacter) { case ' ': case '*': case '}': // tag name is empty this.tagSourceEnd = previousPosition; if (this.textStart == -1) this.textStart = previousPosition; return true; default: if (ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { // tag name is empty this.tagSourceEnd = previousPosition; if (this.textStart == -1) this.textStart = previousPosition; return true; } break; } int currentPosition = this.index; char currentChar = this.scanner.currentCharacter; while (currentChar != ' ' && currentChar != '*' && currentChar != '}' && !ScannerHelper.isWhitespace(currentChar)) { currentPosition = this.index; currentChar = readChar(); } this.tagSourceEnd = currentPosition - 1; this.scanner.currentCharacter = currentChar; this.scanner.currentPosition = currentPosition; char[] tagName = this.scanner.getCurrentIdentifierSource(); int length = tagName.length; this.index = this.tagSourceEnd+1; // Decide which parse to perform depending on tag name this.tagValue = TAG_OTHERS_VALUE; boolean valid = false; switch (tagName[0]) { case 'a': if (length == TAG_AUTHOR_LENGTH && CharOperation.equals(TAG_AUTHOR, tagName)) { this.tagValue = TAG_AUTHOR_VALUE; } break; case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName)) { this.tagValue = TAG_CATEGORY_VALUE; valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } else if (length == TAG_CODE_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_CODE, tagName)) { this.tagValue = TAG_CODE_VALUE; } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) { this.deprecated = true; valid = true; this.tagValue = TAG_DEPRECATED_VALUE; } else if (length == TAG_DOC_ROOT_LENGTH && CharOperation.equals(TAG_DOC_ROOT, tagName)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=227730 // identify @docRoot tag as a base tag that does not expect any argument valid = true; this.tagValue = TAG_DOC_ROOT_VALUE; } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) { this.tagValue = TAG_EXCEPTION_VALUE; valid = parseThrows(); } break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName)) { if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } valid = true; this.tagValue = TAG_INHERITDOC_VALUE; } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) { this.tagValue = TAG_LINK_VALUE; if (this.inlineTagStarted || (this.kind & COMPLETION_PARSER) != 0) { valid = parseReference(); } else { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @link outside inline comment valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName)) { this.tagValue = TAG_LINKPLAIN_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_LITERAL_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_LITERAL, tagName)) { this.tagValue = TAG_LITERAL_VALUE; } break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) { this.tagValue = TAG_PARAM_VALUE; valid = parseParam(); } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) { if (this.inlineTagStarted) { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @see inside inline comment valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } else { this.tagValue = TAG_SEE_VALUE; valid = parseReference(); } } else if (length == TAG_SERIAL_LENGTH && CharOperation.equals(TAG_SERIAL, tagName)) { this.tagValue = TAG_SERIAL_VALUE; } else if (length == TAG_SERIAL_DATA_LENGTH && CharOperation.equals(TAG_SERIAL_DATA, tagName)) { this.tagValue = TAG_SERIAL_DATA_VALUE; } else if (length == TAG_SERIAL_FIELD_LENGTH && CharOperation.equals(TAG_SERIAL_FIELD, tagName)) { this.tagValue = TAG_SERIAL_FIELD_VALUE; } else if (length == TAG_SINCE_LENGTH && CharOperation.equals(TAG_SINCE, tagName)) { this.tagValue = TAG_SINCE_VALUE; } break; case 'v': if (length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName)) { this.tagValue = TAG_VALUE_VALUE; if (this.sourceLevel >= ClassFileConstants.JDK1_5) { if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_VERSION_LENGTH && CharOperation.equals(TAG_VERSION, tagName)) { this.tagValue = TAG_VERSION_VALUE; } else { createTag(); } break; case 'r': if (length == TAG_RETURN_LENGTH && CharOperation.equals(TAG_RETURN, tagName)) { this.tagValue = TAG_RETURN_VALUE; valid = parseReturn(); } break; case 't': if (length == TAG_THROWS_LENGTH && CharOperation.equals(TAG_THROWS, tagName)) { this.tagValue = TAG_THROWS_VALUE; valid = parseThrows(); } break; default: createTag(); break; } consumeToken(); this.textStart = -1; // the javadoc parser may not create tag for some valid tags: force tag creation for such tag. if (valid) { switch (this.tagValue) { case TAG_INHERITDOC_VALUE: case TAG_DEPRECATED_VALUE: createTag(); break; } } else if (this.invalidTagName) { this.textStart = previousPosition; } else if (this.astPtr == ptr) { createTag(); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { // Create argument as we may need it after char[] argName = name==null ? CharOperation.NO_CHAR : name; Expression expression = (Expression) super.createArgumentReference(argName, dim, isVarargs, typeRef, dimPositions, argNamePos); // See if completion location is in argument int refStart = ((TypeReference)typeRef).sourceStart; int refEnd = ((TypeReference)typeRef).sourceEnd; boolean inCompletion = (refStart <= this.cursorLocation && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)); // or it's a completion on empty token if (this.completionNode == null && inCompletion) { JavadocArgumentExpression javadocArgument = (JavadocArgumentExpression) expression; TypeReference expressionType = javadocArgument.argument.type; if (expressionType instanceof JavadocSingleTypeReference) { this.completionNode = new CompletionOnJavadocSingleTypeReference((JavadocSingleTypeReference) expressionType); } else if (expressionType instanceof JavadocQualifiedTypeReference) { this.completionNode = new CompletionOnJavadocQualifiedTypeReference((JavadocQualifiedTypeReference) expressionType); } if (CompletionEngine.DEBUG) { System.out.println(" completion argument="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return expression; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int refStart = (int) (this.identifierPositionStack[0] >>> 32); int refEnd = (int) this.identifierPositionStack[0]; boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor if (inCompletion) { JavadocFieldReference fieldRef = (JavadocFieldReference) super.createFieldReference(receiver); char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } this.completionNode = new CompletionOnJavadocFieldReference(fieldRef, this.memberStart, name); if (CompletionEngine.DEBUG) { System.out.println(" completion field="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return super.createFieldReference(receiver); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference int refStart = (int) (this.identifierPositionStack[memberPtr] >>> 32); int refEnd = (int) this.identifierPositionStack[memberPtr]; boolean inCompletion = (refStart <= (this.cursorLocation+1) && this.cursorLocation <= refEnd) // completion cursor is between first and last stacked identifiers || ((refStart == (refEnd+1) && refEnd == this.cursorLocation)) // or it's a completion on empty token || (this.memberStart == this.cursorLocation); // or it's a completion just after the member separator with an identifier after the cursor if (inCompletion) { ASTNode node = (ASTNode) super.createMethodReference(receiver, arguments); if (node instanceof JavadocMessageSend) { JavadocMessageSend messageSend = (JavadocMessageSend) node; int nameStart = (int) (messageSend.nameSourcePosition >>> 32); int nameEnd = (int) messageSend.nameSourcePosition; if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) { this.completionNode = new CompletionOnJavadocFieldReference(messageSend, this.memberStart); } else { this.completionNode = new CompletionOnJavadocMessageSend(messageSend, this.memberStart); } } else if (node instanceof JavadocAllocationExpression) { this.completionNode = new CompletionOnJavadocAllocationExpression((JavadocAllocationExpression)node, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; } return super.createMethodReference(receiver, arguments); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { if (this.tagSourceStart>this.cursorLocation) { return super.parseArguments(receiver); } // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && getCurrentTokenType() == TerminalTokens.TokenNameRPAREN) { this.lineStarted = true; return createMethodReference(receiver, null); } Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } if (this.index >= this.scanner.eofPosition) { int argumentStart = ((ASTNode)typeRef).sourceStart; Object argument = createArgumentReference(this.scanner.getCurrentIdentifierSource(), 0, false, typeRef, null, (((long)argumentStart)<<32)+this.tokenPreviousPosition-1); return syntaxRecoverArgumentType(receiver, arguments, argument); } if (this.index >= this.cursorLocation) { if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token == null || singleTypeReference.token.length == 0) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens == null || qualifiedTypeReference.tokens.length < qualifiedTypeReference.sourcePositions.length) { Object methodRef = createMethodReference(receiver, arguments); return syntaxRecoverEmptyArgumentType(methodRef); } } } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); return syntaxRecoverArgumentType(receiver, arguments, argument); } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseParam() throws InvalidInputException { int startPosition = this.index; int endPosition = this.index; long namePosition = (((long)startPosition)<<32) + endPosition; this.identifierPtr = -1; boolean valid = super.parseParam(); if (this.identifierPtr > 2) return valid; // See if expression is concerned by completion char[] name = null; CompletionScanner completionScanner = (CompletionScanner) this.scanner; boolean isTypeParam = false; if (this.identifierPtr >= 0) { char[] identifier = null; switch (this.identifierPtr) { case 2: if (!valid && completionScanner.completionIdentifier != null && completionScanner.completionIdentifier.length == 0) { valid = pushParamName(true); } // $FALL-THROUGH$ - fall through next case to verify and get identifiers stack contents case 1: isTypeParam = this.identifierStack[0][0] == '<'; identifier = this.identifierStack[1]; namePosition = this.identifierPositionStack[1]; break; case 0: identifier = this.identifierStack[0]; namePosition = this.identifierPositionStack[0]; isTypeParam = identifier.length > 0 && identifier[0] == '<'; break; } if (identifier != null && identifier.length > 0 && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, identifier[0])) { name = identifier; } startPosition = (int)(this.identifierPositionStack[0]>>32); endPosition = (int)this.identifierPositionStack[this.identifierPtr]; } boolean inCompletion = (startPosition <= (this.cursorLocation+1) && this.cursorLocation <= endPosition) // completion cursor is between first and last stacked identifiers || ((startPosition == (endPosition+1) && endPosition == this.cursorLocation)); // or it's a completion on empty token if (inCompletion) { if (this.completionNode == null) { if (isTypeParam) { this.completionNode = new CompletionOnJavadocTypeParamReference(name, namePosition, startPosition, endPosition); } else { this.completionNode = new CompletionOnJavadocParamNameReference(name, namePosition, startPosition, endPosition); } if (CompletionEngine.DEBUG) { System.out.println(" completion param="+this.completionNode); //$NON-NLS-1$ } } else if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { CompletionOnJavadocParamNameReference paramNameRef = (CompletionOnJavadocParamNameReference)this.completionNode; int nameStart = (int) (namePosition>>32); paramNameRef.sourceStart = nameStart; int nameEnd = (int) namePosition; if (nameStart<this.cursorLocation && this.cursorLocation<nameEnd) { paramNameRef.sourceEnd = this.cursorLocation + 1; } else { paramNameRef.sourceEnd = nameEnd; } paramNameRef.tagSourceStart = startPosition; paramNameRef.tagSourceEnd = endPosition; } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { CompletionOnJavadocTypeParamReference typeParamRef = (CompletionOnJavadocTypeParamReference)this.completionNode; int nameStart = (int) (namePosition>>32); typeParamRef.sourceStart = nameStart; int nameEnd = (int) namePosition; if (nameStart<this.cursorLocation && this.cursorLocation<nameEnd) { typeParamRef.sourceEnd = this.cursorLocation + 1; } else { typeParamRef.sourceEnd = nameEnd; } typeParamRef.tagSourceStart = startPosition; typeParamRef.tagSourceEnd = endPosition; } } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseReference() throws InvalidInputException { boolean completed = this.completionNode != null; boolean valid = super.parseReference(); if (!completed && this.completionNode != null) { this.completionNode.addCompletionFlags(CompletionOnJavadoc.FORMAL_REFERENCE); } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { int startPosition = this.inlineTagStarted ? this.inlineTagStart : previousPosition; boolean newLine = !this.lineStarted; boolean valid = super.parseTag(previousPosition); boolean inCompletion = (this.tagSourceStart <= (this.cursorLocation+1) && this.cursorLocation <= this.tagSourceEnd) // completion cursor is between first and last stacked identifiers || ((this.tagSourceStart == (this.tagSourceEnd+1) && this.tagSourceEnd == this.cursorLocation)); // or it's a completion on empty token if (inCompletion) { int end = this.tagSourceEnd; if (this.inlineTagStarted && this.scanner.currentCharacter == '}') { end = this.scanner.currentPosition; } long position = (((long)startPosition)<<32) + end; int length = this.cursorLocation+1-this.tagSourceStart; char[] tag = new char[length]; System.arraycopy(this.source, this.tagSourceStart, tag, 0, length); char[][][] tags = possibleTags(tag, newLine); if (tags != null) { this.completionNode = new CompletionOnJavadocTag(tag, position, startPosition, end, tags, this.allPossibleTags); } } return valid; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected int readToken() throws InvalidInputException { int token = super.readToken(); if (token == TerminalTokens.TokenNameIdentifier && this.scanner.currentPosition == this.scanner.startPosition) { // Scanner is looping on empty token => read it... this.scanner.getCurrentIdentifierSource(); } return token; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException { if (this.cursorLocation == ((int)this.identifierPositionStack[this.identifierPtr])) { // special case of completion just before the dot. return createTypeReference(primitiveToken); } int idLength = this.identifierLengthStack[this.identifierLengthPtr]; char[][] tokens = new char[idLength][]; int startPtr = this.identifierPtr-idLength+1; System.arraycopy(this.identifierStack, startPtr, tokens, 0, idLength); long[] positions = new long[idLength+1]; System.arraycopy(this.identifierPositionStack, startPtr, positions, 0, idLength); positions[idLength] = (((long)this.tokenPreviousPosition)<<32) + this.tokenPreviousPosition; this.completionNode = new CompletionOnJavadocQualifiedTypeReference(tokens, CharOperation.NO_CHAR, positions, this.tagSourceStart, this.tagSourceEnd); if (CompletionEngine.DEBUG) { System.out.println(" completion partial qualified type="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverArgumentType(Object receiver, List arguments, Object argument) throws InvalidInputException { if (this.completionNode != null && !this.pushText) { this.completionNode.addCompletionFlags(CompletionOnJavadoc.BASE_TYPES); if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { char[] token = ((CompletionOnJavadocSingleTypeReference)this.completionNode).token; if (token != null && token.length > 0) { return this.completionNode; } } else { return this.completionNode; } } // Filter empty token if (this.completionNode instanceof CompletionOnJavadocSingleTypeReference) { CompletionOnJavadocSingleTypeReference singleTypeReference = (CompletionOnJavadocSingleTypeReference) this.completionNode; if (singleTypeReference.token != null && singleTypeReference.token.length > 0) { arguments.add(argument); } } else if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference qualifiedTypeReference = (CompletionOnJavadocQualifiedTypeReference) this.completionNode; if (qualifiedTypeReference.tokens != null && qualifiedTypeReference.tokens.length == qualifiedTypeReference.sourcePositions.length) { arguments.add(argument); } } else { arguments.add(argument); } Object methodRef = super.createMethodReference(receiver, arguments); if (methodRef instanceof JavadocMessageSend) { JavadocMessageSend msgSend = (JavadocMessageSend) methodRef; if (this.index > this.cursorLocation) { msgSend.sourceEnd = this.tokenPreviousPosition-1; } int nameStart = (int) (msgSend.nameSourcePosition >>> 32); int nameEnd = (int) msgSend.nameSourcePosition; if ((nameStart <= (this.cursorLocation+1) && this.cursorLocation <= nameEnd)) { this.completionNode = new CompletionOnJavadocFieldReference(msgSend, this.memberStart); } else { this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart); } } else if (methodRef instanceof JavadocAllocationExpression) { JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef; if (this.index > this.cursorLocation) { allocExp.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
protected Object syntaxRecoverEmptyArgumentType(Object methodRef) throws InvalidInputException { if (methodRef instanceof JavadocMessageSend) { JavadocMessageSend msgSend = (JavadocMessageSend) methodRef; if (this.index > this.cursorLocation) { msgSend.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocMessageSend(msgSend, this.memberStart); } else if (methodRef instanceof JavadocAllocationExpression) { JavadocAllocationExpression allocExp = (JavadocAllocationExpression) methodRef; if (this.index > this.cursorLocation) { allocExp.sourceEnd = this.tokenPreviousPosition-1; } this.completionNode = new CompletionOnJavadocAllocationExpression(allocExp, this.memberStart); } if (CompletionEngine.DEBUG) { System.out.println(" completion method="+this.completionNode); //$NON-NLS-1$ } return this.completionNode; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; this.unicodeCharSize = 0; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles start position--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset = 0; do { this.startPosition = this.currentPosition; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) { /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = 6; } else { offset = 1; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { pushLineSeparator(); } } isWhiteSpace = (this.currentCharacter == ' ') || CharOperation.isWhitespace(this.currentCharacter); } if (isWhiteSpace) { hasWhiteSpaces = true; } /* completion requesting strictly inside blanks */ if ((whiteStart != this.currentPosition) //&& (previousToken == TokenNameDOT) && (this.completionIdentifier == null) && (whiteStart <= this.cursorLocation+1) && (this.cursorLocation < this.startPosition) && !ScannerHelper.isJavaIdentifierStart(this.complianceLevel, this.currentCharacter)){ this.currentPosition = this.startPosition; // for next token read return TokenNameIdentifier; } } while (isWhiteSpace); if (this.tokenizeWhiteSpace && hasWhiteSpaces) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; return TokenNameWHITESPACE; } //little trick to get out in the middle of a source computation if (this.currentPosition > this.eofPosition){ /* might be completing at eof (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ // compute end of empty identifier. // if the empty identifier is at the start of a next token the end of // empty identifier is the end of the next token (e.g. "<empty token>next"). int temp = this.eofPosition; this.eofPosition = this.source.length; while(getNextCharAsJavaIdentifierPart()){/*empty*/} this.eofPosition = temp; this.endOfEmptyToken = this.currentPosition - 1; this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ return TokenNameDOT; // completion inside .<|>12 } if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; boolean checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { if (isUnicode) { int start = this.currentPosition - 5; while(this.source[start] != '\\') { start--; } if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { this.currentPosition = start; // complete inside a string literal return TokenNameStringLiteral; } start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character if(this.startPosition <= this.cursorLocation && this.cursorLocation <= this.currentPosition-1) { // complete inside a string literal return TokenNameStringLiteral; } } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; if(this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition) { // complete inside a string literal return TokenNameStringLiteral; } throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : { int test; if ((test = getNextChar('/', '*')) == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; this.currentPosition++; while (this.source[this.currentPosition] == 'u') { this.currentPosition++; } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { isUnicode = true; char unicodeChar; int index = this.currentPosition + 1; index++; while (this.source[index] == 'u') { index++; } //-------------unicode traitement ------------ int c1 = 0, c2 = 0, c3 = 0, c4 = 0; if ((c1 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[index++])) > 15 || c4 < 0) { this.currentPosition = index; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } else { unicodeChar = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); } if (unicodeChar == '\n') { this.currentPosition = index; this.currentCharacter = '\n'; } } } recordComment(TokenNameCOMMENT_LINE); if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { //checkNonExternalizedString(); if (this.recordLineSeparator) { if (!isUnicode) { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (!isJavadoc && this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); } if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; } case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <this.currentPosition == this.source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = Character.isJavaIdentifierStart(c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } /* might be completing at very end of file (e.g. behind a dot) */ if (this.completionIdentifier == null && this.startPosition == this.cursorLocation + 1){ this.currentPosition = this.startPosition; // for being detected as empty free identifier return TokenNameIdentifier; } return TokenNameEOF; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public final void getNextUnicodeChar() throws InvalidInputException { int temp = this.currentPosition; // the \ is already read super.getNextUnicodeChar(); if(this.cursorLocation > temp) { this.unicodeCharSize += (this.currentPosition - temp); } if (temp < this.cursorLocation && this.cursorLocation < this.currentPosition-1){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { int token = super.scanNumber(dotPrefix); // consider completion just before a number to be ok, will insert before it if (this.startPosition <= this.cursorLocation && this.cursorLocation < this.currentPosition){ throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER); } return token; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { // Create argument as we may need it after Expression expression = (Expression) super.createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); // See if selection is in argument int start = ((TypeReference)typeRef).sourceStart; int end = ((TypeReference)typeRef).sourceEnd; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = expression; this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected argument="+this.selectedNode); //$NON-NLS-1$ } } return expression; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = (ASTNode) super.createFieldReference(receiver); this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected field="+this.selectedNode); //$NON-NLS-1$ } } return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { int memberPtr = this.identifierLengthStack[0] - 1; // may be > 0 for inner class constructor reference int start = (int) (this.identifierPositionStack[memberPtr] >>> 32); int end = (int) this.identifierPositionStack[memberPtr]; if (start <= this.selectionStart && this.selectionEnd <= end) { this.selectedNode = (ASTNode) super.createMethodReference(receiver, arguments); this.abort = true; if (SelectionEngine.DEBUG) { System.out.println(" selected method="+this.selectedNode); //$NON-NLS-1$ } } return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
public static boolean isDigit(char c) throws InvalidInputException { if(c < ScannerHelper.MAX_OBVIOUS) { return (ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0; } if (Character.isDigit(c)) { throw new InvalidInputException(Scanner.INVALID_DIGIT); } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { TypeReference argTypeRef = (TypeReference) typeRef; if (dim > 0) { long pos = (((long) argTypeRef.sourceStart) << 32) + argTypeRef.sourceEnd; if (typeRef instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference singleRef = (JavadocSingleTypeReference) typeRef; argTypeRef = new JavadocArraySingleTypeReference(singleRef.token, dim, pos); } else { JavadocQualifiedTypeReference qualifRef = (JavadocQualifiedTypeReference) typeRef; argTypeRef = new JavadocArrayQualifiedTypeReference(qualifRef, dim); } } int argEnd = argTypeRef.sourceEnd; if (dim > 0) { argEnd = (int) dimPositions[dim-1]; if (isVarargs) { argTypeRef.bits |= ASTNode.IsVarArgs; // set isVarArgs } } if (argNamePos >= 0) argEnd = (int) argNamePos; return new JavadocArgumentExpression(name, argTypeRef.sourceStart, argEnd, argTypeRef); } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } // Create field JavadocFieldReference field = new JavadocFieldReference(this.identifierStack[0], this.identifierPositionStack[0]); field.receiver = typeRef; field.tagSourceStart = this.tagSourceStart; field.tagSourceEnd = this.tagSourceEnd; field.tagValue = this.tagValue; return field; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Get receiver type TypeReference typeRef = (TypeReference) receiver; // Decide whether we have a constructor or not boolean isConstructor = false; int length = this.identifierLengthStack[0]; // may be > 1 for member class constructor reference if (typeRef == null) { char[] name = this.sourceParser.compilationUnit.getMainTypeName(); TypeDeclaration typeDecl = getParsedTypeDeclaration(); if (typeDecl != null) { name = typeDecl.name; } isConstructor = CharOperation.equals(this.identifierStack[length-1], name); typeRef = new JavadocImplicitTypeReference(name, this.memberStart); } else { if (typeRef instanceof JavadocSingleTypeReference) { char[] name = ((JavadocSingleTypeReference)typeRef).token; isConstructor = CharOperation.equals(this.identifierStack[length-1], name); } else if (typeRef instanceof JavadocQualifiedTypeReference) { char[][] tokens = ((JavadocQualifiedTypeReference)typeRef).tokens; int last = tokens.length-1; isConstructor = CharOperation.equals(this.identifierStack[length-1], tokens[last]); if (isConstructor) { boolean valid = true; if (valid) { for (int i=0; i<length-1 && valid; i++) { valid = CharOperation.equals(this.identifierStack[i], tokens[i]); } } if (!valid) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidMemberTypeQualification((int)(this.identifierPositionStack[0]>>>32), (int)this.identifierPositionStack[length-1], -1); } return null; } } } else { throw new InvalidInputException(); } } // Create node if (arguments == null) { if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1]); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } else { JavadocArgumentExpression[] expressions = new JavadocArgumentExpression[arguments.size()]; arguments.toArray(expressions); if (isConstructor) { JavadocAllocationExpression allocation = new JavadocAllocationExpression(this.identifierPositionStack[length-1]); allocation.arguments = expressions; allocation.type = typeRef; allocation.tagValue = this.tagValue; allocation.sourceEnd = this.scanner.getCurrentTokenEndPosition(); if (length == 1) { allocation.qualification = new char[][] { this.identifierStack[0] }; } else { System.arraycopy(this.identifierStack, 0, allocation.qualification = new char[length][], 0, length); allocation.sourceStart = (int) (this.identifierPositionStack[0] >>> 32); } allocation.memberStart = this.memberStart; return allocation; } else { JavadocMessageSend msg = new JavadocMessageSend(this.identifierStack[length-1], this.identifierPositionStack[length-1], expressions); msg.receiver = typeRef; msg.tagValue = this.tagValue; msg.sourceEnd = this.scanner.getCurrentTokenEndPosition(); return msg; } } } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Complain when tag is missing a description // Note that if the parse of an inline tag has already started, consider it // as the expected description, hence do not report any warning switch (this.tagWaitingForDescription) { case TAG_PARAM_VALUE: case TAG_THROWS_VALUE: if (!this.inlineTagStarted) { int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[this.identifierPtr]; this.sourceParser.problemReporter().javadocMissingTagDescriptionAfterReference(start, end, this.sourceParser.modifiers); } break; case NO_TAG_VALUE: break; default: if (!this.inlineTagStarted) { this.sourceParser.problemReporter().javadocMissingTagDescription(TAG_NAMES[this.tagWaitingForDescription], this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers); } break; } this.tagWaitingForDescription = NO_TAG_VALUE; // Verify first character this.tagSourceStart = this.index; this.tagSourceEnd = previousPosition; this.scanner.startPosition = this.index; int currentPosition = this.index; char firstChar = readChar(); switch (firstChar) { case ' ': case '*': case '}': case '#': // the first character is not valid, hence report invalid empty tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(previousPosition, currentPosition); if (this.textStart == -1) this.textStart = currentPosition; this.scanner.currentCharacter = firstChar; return false; default: if (ScannerHelper.isWhitespace(firstChar)) { // the first character is not valid, hence report invalid empty tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(previousPosition, currentPosition); if (this.textStart == -1) this.textStart = currentPosition; this.scanner.currentCharacter = firstChar; return false; } break; } // Read tag name char[] tagName = new char[32]; int length = 0; char currentChar = firstChar; int tagNameLength = tagName.length; boolean validTag = true; tagLoop: while (true) { if (length == tagNameLength) { System.arraycopy(tagName, 0, tagName = new char[tagNameLength+32], 0, tagNameLength); tagNameLength = tagName.length; } tagName[length++] = currentChar; currentPosition = this.index; currentChar = readChar(); switch (currentChar) { case ' ': case '*': case '}': // these characters mark the end of the tag reading break tagLoop; case '#': // invalid tag character, mark the tag as invalid but continue until the end of the tag validTag = false; break; default: if (ScannerHelper.isWhitespace(currentChar)) { // whitespace characters mark the end of the tag reading break tagLoop; } break; } } // Init positions this.tagSourceEnd = currentPosition - 1; this.scanner.currentCharacter = currentChar; this.scanner.currentPosition = currentPosition; this.index = this.tagSourceEnd+1; // Return if the tag is not valid if (!validTag) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(this.tagSourceStart, this.tagSourceEnd); if (this.textStart == -1) this.textStart = this.index; this.scanner.currentCharacter = currentChar; return false; } // Decide which parse to perform depending on tag name this.tagValue = TAG_OTHERS_VALUE; boolean valid = false; switch (firstChar) { case 'a': if (length == TAG_AUTHOR_LENGTH && CharOperation.equals(TAG_AUTHOR, tagName, 0, length)) { this.tagValue = TAG_AUTHOR_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName, 0, length)) { this.tagValue = TAG_CATEGORY_VALUE; if (!this.inlineTagStarted) { valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } } else if (length == TAG_CODE_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_CODE, tagName, 0, length)) { this.tagValue = TAG_CODE_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName, 0, length)) { this.deprecated = true; valid = true; this.tagValue = TAG_DEPRECATED_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_DOC_ROOT_LENGTH && CharOperation.equals(TAG_DOC_ROOT, tagName, 0, length)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=227730 // identify @docRoot tag as a base tag that does not expect any argument valid = true; this.tagValue = TAG_DOC_ROOT_VALUE; } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName, 0, length)) { this.tagValue = TAG_EXCEPTION_VALUE; if (!this.inlineTagStarted) { valid = parseThrows(); } } break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName, 0, length)) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=247037, @inheritDoc usage is illegal // outside of few block tags and the main description. switch (this.lastBlockTagValue) { case TAG_RETURN_VALUE: case TAG_THROWS_VALUE: case TAG_EXCEPTION_VALUE: case TAG_PARAM_VALUE: case NO_TAG_VALUE: // Still in main description valid = true; if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } if (this.inlineTagStarted) { // parse a 'valid' inheritDoc tag parseInheritDocTag(); } break; default: valid = false; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } this.tagValue = TAG_INHERITDOC_VALUE; } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName, 0, length)) { this.tagValue = TAG_LINK_VALUE; if (this.inlineTagStarted || (this.kind & COMPLETION_PARSER) != 0) { valid= parseReference(); } } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName, 0, length)) { this.tagValue = TAG_LINKPLAIN_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } } else if (length == TAG_LITERAL_LENGTH && this.inlineTagStarted && CharOperation.equals(TAG_LITERAL, tagName, 0, length)) { this.tagValue = TAG_LITERAL_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName, 0, length)) { this.tagValue = TAG_PARAM_VALUE; if (!this.inlineTagStarted) { valid = parseParam(); } } break; case 'r': if (length == TAG_RETURN_LENGTH && CharOperation.equals(TAG_RETURN, tagName, 0, length)) { this.tagValue = TAG_RETURN_VALUE; if (!this.inlineTagStarted) { valid = parseReturn(); } } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName, 0, length)) { this.tagValue = TAG_SEE_VALUE; if (!this.inlineTagStarted) { valid = parseReference(); } } else if (length == TAG_SERIAL_LENGTH && CharOperation.equals(TAG_SERIAL, tagName, 0, length)) { this.tagValue = TAG_SERIAL_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SERIAL_DATA_LENGTH && CharOperation.equals(TAG_SERIAL_DATA, tagName, 0, length)) { this.tagValue = TAG_SERIAL_DATA_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SERIAL_FIELD_LENGTH && CharOperation.equals(TAG_SERIAL_FIELD, tagName, 0, length)) { this.tagValue = TAG_SERIAL_FIELD_VALUE; this.tagWaitingForDescription = this.tagValue; } else if (length == TAG_SINCE_LENGTH && CharOperation.equals(TAG_SINCE, tagName, 0, length)) { this.tagValue = TAG_SINCE_VALUE; this.tagWaitingForDescription = this.tagValue; } break; case 't': if (length == TAG_THROWS_LENGTH && CharOperation.equals(TAG_THROWS, tagName, 0, length)) { this.tagValue = TAG_THROWS_VALUE; if (!this.inlineTagStarted) { valid = parseThrows(); } } break; case 'v': if (length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName, 0, length)) { this.tagValue = TAG_VALUE_VALUE; if (this.sourceLevel >= ClassFileConstants.JDK1_5) { if (this.inlineTagStarted) { valid = parseReference(); } } else { if (this.validValuePositions == -1) { if (this.invalidValuePositions != -1) { if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag((int) (this.invalidValuePositions>>>32), (int) this.invalidValuePositions); } if (valid) { this.validValuePositions = (((long) this.tagSourceStart) << 32) + this.tagSourceEnd; this.invalidValuePositions = -1; } else { this.invalidValuePositions = (((long) this.tagSourceStart) << 32) + this.tagSourceEnd; } } else { if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } else if (length == TAG_VERSION_LENGTH && CharOperation.equals(TAG_VERSION, tagName, 0, length)) { this.tagValue = TAG_VERSION_VALUE; this.tagWaitingForDescription = this.tagValue; } else { createTag(); } break; default: createTag(); break; } this.textStart = this.index; if (this.tagValue != TAG_OTHERS_VALUE) { if (!this.inlineTagStarted) { this.lastBlockTagValue = this.tagValue; } // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=267833 // Report a problem if a block tag is being used in the context of an inline tag and vice versa. if ((this.inlineTagStarted && JAVADOC_TAG_TYPE[this.tagValue] == TAG_TYPE_BLOCK) || (!this.inlineTagStarted && JAVADOC_TAG_TYPE[this.tagValue] == TAG_TYPE_INLINE)) { valid = false; this.tagValue = TAG_OTHERS_VALUE; this.tagWaitingForDescription = NO_TAG_VALUE; if (this.reportProblems) { this.sourceParser.problemReporter().javadocUnexpectedTag(this.tagSourceStart, this.tagSourceEnd); } } } return valid; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/JavadocParser.java
protected boolean parseParam() throws InvalidInputException { boolean valid = super.parseParam(); this.tagWaitingForDescription = valid && this.reportProblems ? TAG_PARAM_VALUE : NO_TAG_VALUE; return valid; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void checkTaskTag(int commentStart, int commentEnd) throws InvalidInputException { char[] src = this.source; // only look for newer task: tags if (this.foundTaskCount > 0 && this.foundTaskPositions[this.foundTaskCount - 1][0] >= commentStart) { return; } int foundTaskIndex = this.foundTaskCount; char previous = src[commentStart+1]; // should be '*' or '/' for ( int i = commentStart + 2; i < commentEnd && i < this.eofPosition; i++) { char[] tag = null; char[] priority = null; // check for tag occurrence only if not ambiguous with javadoc tag if (previous != '@') { nextTag : for (int itag = 0; itag < this.taskTags.length; itag++) { tag = this.taskTags[itag]; int tagLength = tag.length; if (tagLength == 0) continue nextTag; // ensure tag is not leaded with letter if tag starts with a letter if (ScannerHelper.isJavaIdentifierStart(this.complianceLevel, tag[0])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, previous)) { continue nextTag; } } for (int t = 0; t < tagLength; t++) { char sc, tc; int x = i+t; if (x >= this.eofPosition || x >= commentEnd) continue nextTag; // case sensitive check if ((sc = src[i + t]) != (tc = tag[t])) { // case insensitive check if (this.isTaskCaseSensitive || (ScannerHelper.toLowerCase(sc) != ScannerHelper.toLowerCase(tc))) { continue nextTag; } } } // ensure tag is not followed with letter if tag finishes with a letter if (i+tagLength < commentEnd && ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i+tagLength-1])) { if (ScannerHelper.isJavaIdentifierPart(this.complianceLevel, src[i + tagLength])) continue nextTag; } if (this.foundTaskTags == null) { this.foundTaskTags = new char[5][]; this.foundTaskMessages = new char[5][]; this.foundTaskPriorities = new char[5][]; this.foundTaskPositions = new int[5][]; } else if (this.foundTaskCount == this.foundTaskTags.length) { System.arraycopy(this.foundTaskTags, 0, this.foundTaskTags = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskMessages, 0, this.foundTaskMessages = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPriorities, 0, this.foundTaskPriorities = new char[this.foundTaskCount * 2][], 0, this.foundTaskCount); System.arraycopy(this.foundTaskPositions, 0, this.foundTaskPositions = new int[this.foundTaskCount * 2][], 0, this.foundTaskCount); } priority = this.taskPriorities != null && itag < this.taskPriorities.length ? this.taskPriorities[itag] : null; this.foundTaskTags[this.foundTaskCount] = tag; this.foundTaskPriorities[this.foundTaskCount] = priority; this.foundTaskPositions[this.foundTaskCount] = new int[] { i, i + tagLength - 1 }; this.foundTaskMessages[this.foundTaskCount] = CharOperation.NO_CHAR; this.foundTaskCount++; i += tagLength - 1; // will be incremented when looping break nextTag; } } previous = src[i]; } boolean containsEmptyTask = false; for (int i = foundTaskIndex; i < this.foundTaskCount; i++) { // retrieve message start and end positions int msgStart = this.foundTaskPositions[i][0] + this.foundTaskTags[i].length; int max_value = i + 1 < this.foundTaskCount ? this.foundTaskPositions[i + 1][0] - 1 : commentEnd - 1; // at most beginning of next task if (max_value < msgStart) { max_value = msgStart; // would only occur if tag is before EOF. } int end = -1; char c; for (int j = msgStart; j < max_value; j++) { if ((c = src[j]) == '\n' || c == '\r') { end = j - 1; break; } } if (end == -1) { for (int j = max_value; j > msgStart; j--) { if ((c = src[j]) == '*') { end = j - 1; break; } } if (end == -1) end = max_value; } if (msgStart == end) { // if the description is empty, we might want to see if two tags are not sharing the same message // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=110797 containsEmptyTask = true; continue; } // trim the message // we don't trim the beginning of the message to be able to show it after the task tag while (CharOperation.isWhitespace(src[end]) && msgStart <= end) end--; // update the end position of the task this.foundTaskPositions[i][1] = end; // get the message source final int messageLength = end - msgStart + 1; char[] message = new char[messageLength]; System.arraycopy(src, msgStart, message, 0, messageLength); this.foundTaskMessages[i] = message; } if (containsEmptyTask) { for (int i = foundTaskIndex, max = this.foundTaskCount; i < max; i++) { if (this.foundTaskMessages[i].length == 0) { loop: for (int j = i + 1; j < max; j++) { if (this.foundTaskMessages[j].length != 0) { this.foundTaskMessages[i] = this.foundTaskMessages[j]; this.foundTaskPositions[i][1] = this.foundTaskPositions[j][1]; break loop; } } } } } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix) throws InvalidInputException { consumeDigits(radix, false); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final void consumeDigits(int radix, boolean expectingDigitFirst) throws InvalidInputException { final int USING_UNDERSCORE = 1; final int INVALID_POSITION = 2; switch(consumeDigits0(radix, USING_UNDERSCORE, INVALID_POSITION, expectingDigitFirst)) { case USING_UNDERSCORE : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } break; case INVALID_POSITION : if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(UNDERSCORES_IN_LITERALS_NOT_BELOW_17); } throw new InvalidInputException(INVALID_UNDERSCORE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private final int consumeDigits0(int radix, int usingUnderscore, int invalidPosition, boolean expectingDigitFirst) throws InvalidInputException { int kind = 0; if (getNextChar('_')) { if (expectingDigitFirst) { return invalidPosition; } kind = usingUnderscore; while (getNextChar('_')) {/*empty */} } if (getNextCharAsDigit(radix)) { // continue to read digits or underscore while (getNextCharAsDigit(radix)) {/*empty */} int kind2 = consumeDigits0(radix, usingUnderscore, invalidPosition, false); if (kind2 == 0) { return kind; } return kind2; } if (kind == usingUnderscore) return invalidPosition; return kind; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final boolean getNextCharAsDigit() throws InvalidInputException { //BOOLEAN //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //Both previous lines are true if the currentCharacter is a digit //On false, no side effect has occured. //ALL getNextChar.... ARE OPTIMIZED COPIES if (this.currentPosition >= this.eofPosition) // handle the obvious case upfront return false; int temp = this.currentPosition; try { if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; this.withoutUnicodePtr--; return false; } return true; } else { if (!ScannerHelper.isDigit(this.currentCharacter)) { this.currentPosition = temp; return false; } if (this.withoutUnicodePtr != 0) unicodeStore(); return true; } } catch (IndexOutOfBoundsException e) { this.currentPosition = temp; return false; } catch(InvalidInputException e) { this.currentPosition = temp; return false; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanIdentifier() throws InvalidInputException { int whiteStart = 0; while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; if (this.currentPosition < this.eofPosition) { this.currentCharacter = this.source[this.currentPosition++]; checkIfUnicode = this.currentPosition < this.eofPosition && this.currentCharacter == '\\' && this.source[this.currentPosition] == 'u'; } else if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } else { return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeywordWithBoundCheck(); } return TokenNameERROR; } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextCharWithBoundChecks(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeywordWithBoundCheck(); return TokenNameERROR; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int getNextToken() throws InvalidInputException { this.wasAcr = false; if (this.diet) { jumpOverMethodBody(); this.diet = false; return this.currentPosition > this.eofPosition ? TokenNameEOF : TokenNameRBRACE; } int whiteStart = 0; try { while (true) { //loop for jumping over comments this.withoutUnicodePtr = 0; //start with a new token (even comment written with unicode ) // ---------Consume white space and handles startPosition--------- whiteStart = this.currentPosition; boolean isWhiteSpace, hasWhiteSpaces = false; int offset; int unicodePtr; boolean checkIfUnicode = false; do { unicodePtr = this.withoutUnicodePtr; offset = this.currentPosition; this.startPosition = this.currentPosition; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } if (this.currentPosition > this.eofPosition) return TokenNameEOF; } if (this.currentPosition > this.eofPosition) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { this.currentPosition--; // reposition scanner in case we are interested by spaces as tokens this.startPosition = whiteStart; return TokenNameWHITESPACE; } return TokenNameEOF; } if (checkIfUnicode) { isWhiteSpace = jumpOverUnicodeWhiteSpace(); offset = this.currentPosition - offset; } else { offset = this.currentPosition - offset; if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { pushLineSeparator(); } } // inline version of: //isWhiteSpace = // (this.currentCharacter == ' ') || ScannerHelper.isWhitespace(this.currentCharacter); switch (this.currentCharacter) { case 10 : /* \ u000a: LINE FEED */ case 12 : /* \ u000c: FORM FEED */ case 13 : /* \ u000d: CARRIAGE RETURN */ case 32 : /* \ u0020: SPACE */ case 9 : /* \ u0009: HORIZONTAL TABULATION */ isWhiteSpace = true; break; default : isWhiteSpace = false; } } if (isWhiteSpace) { hasWhiteSpaces = true; } } while (isWhiteSpace); if (hasWhiteSpaces) { if (this.tokenizeWhiteSpace) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition-=offset; this.startPosition = whiteStart; if (checkIfUnicode) { this.withoutUnicodePtr = unicodePtr; } return TokenNameWHITESPACE; } else if (checkIfUnicode) { this.withoutUnicodePtr = 0; unicodeStore(); } else { this.withoutUnicodePtr = 0; } } // ---------Identify the next token------------- switch (this.currentCharacter) { case '@' : /* if (this.sourceLevel >= ClassFileConstants.JDK1_5) { return TokenNameAT; } else { return TokenNameERROR; }*/ return TokenNameAT; case '(' : return TokenNameLPAREN; case ')' : return TokenNameRPAREN; case '{' : return TokenNameLBRACE; case '}' : return TokenNameRBRACE; case '[' : return TokenNameLBRACKET; case ']' : return TokenNameRBRACKET; case ';' : return TokenNameSEMICOLON; case ',' : return TokenNameCOMMA; case '.' : if (getNextCharAsDigit()) { return scanNumber(true); } int temp = this.currentPosition; if (getNextChar('.')) { if (getNextChar('.')) { return TokenNameELLIPSIS; } else { this.currentPosition = temp; return TokenNameDOT; } } else { this.currentPosition = temp; return TokenNameDOT; } case '+' : { int test; if ((test = getNextChar('+', '=')) == 0) return TokenNamePLUS_PLUS; if (test > 0) return TokenNamePLUS_EQUAL; return TokenNamePLUS; } case '-' : { int test; if ((test = getNextChar('-', '=')) == 0) return TokenNameMINUS_MINUS; if (test > 0) return TokenNameMINUS_EQUAL; return TokenNameMINUS; } case '~' : return TokenNameTWIDDLE; case '!' : if (getNextChar('=')) return TokenNameNOT_EQUAL; return TokenNameNOT; case '*' : if (getNextChar('=')) return TokenNameMULTIPLY_EQUAL; return TokenNameMULTIPLY; case '%' : if (getNextChar('=')) return TokenNameREMAINDER_EQUAL; return TokenNameREMAINDER; case '<' : { int test; if ((test = getNextChar('=', '<')) == 0) return TokenNameLESS_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameLEFT_SHIFT_EQUAL; return TokenNameLEFT_SHIFT; } return TokenNameLESS; } case '>' : { int test; if (this.returnOnlyGreater) { return TokenNameGREATER; } if ((test = getNextChar('=', '>')) == 0) return TokenNameGREATER_EQUAL; if (test > 0) { if ((test = getNextChar('=', '>')) == 0) return TokenNameRIGHT_SHIFT_EQUAL; if (test > 0) { if (getNextChar('=')) return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; return TokenNameUNSIGNED_RIGHT_SHIFT; } return TokenNameRIGHT_SHIFT; } return TokenNameGREATER; } case '=' : if (getNextChar('=')) return TokenNameEQUAL_EQUAL; return TokenNameEQUAL; case '&' : { int test; if ((test = getNextChar('&', '=')) == 0) return TokenNameAND_AND; if (test > 0) return TokenNameAND_EQUAL; return TokenNameAND; } case '|' : { int test; if ((test = getNextChar('|', '=')) == 0) return TokenNameOR_OR; if (test > 0) return TokenNameOR_EQUAL; return TokenNameOR; } case '^' : if (getNextChar('=')) return TokenNameXOR_EQUAL; return TokenNameXOR; case '?' : return TokenNameQUESTION; case ':' : return TokenNameCOLON; case '\'' : { int test; if ((test = getNextChar('\n', '\r')) == 0) { throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (test > 0) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } } if (getNextChar('\'')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 3; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (getNextChar('\\')) { if (this.unicodeAsBackSlash) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } else { this.currentCharacter = this.source[this.currentPosition++]; } scanEscapeCharacter(); } else { // consume next character this.unicodeAsBackSlash = false; checkIfUnicode = false; try { checkIfUnicode = ((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u'); } catch(IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); } if (checkIfUnicode) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (getNextChar('\'')) return TokenNameCharacterLiteral; // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 20; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\'') { this.currentPosition += lookAhead + 1; break; } } throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); case '"' : try { // consume next character this.unicodeAsBackSlash = false; boolean isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } while (this.currentCharacter != '"') { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_STRING); } /**** \r and \n are not valid in string literals ****/ if ((this.currentCharacter == '\n') || (this.currentCharacter == '\r')) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed if (isUnicode) { int start = this.currentPosition; for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition >= this.eofPosition) { this.currentPosition = start; break; } if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { isUnicode = true; getNextUnicodeChar(); } else { isUnicode = false; } if (!isUnicode && this.currentCharacter == '\n') { this.currentPosition--; // set current position on new line character break; } if (this.currentCharacter == '\"') { throw new InvalidInputException(INVALID_CHAR_IN_STRING); } } } else { this.currentPosition--; // set current position on new line character } throw new InvalidInputException(INVALID_CHAR_IN_STRING); } if (this.currentCharacter == '\\') { if (this.unicodeAsBackSlash) { this.withoutUnicodePtr--; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; this.withoutUnicodePtr--; } else { isUnicode = false; } } else { if (this.withoutUnicodePtr == 0) { unicodeInitializeBuffer(this.currentPosition - this.startPosition); } this.withoutUnicodePtr --; this.currentCharacter = this.source[this.currentPosition++]; } // we need to compute the escape character in a separate buffer scanEscapeCharacter(); if (this.withoutUnicodePtr != 0) { unicodeStore(); } } // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_STRING); } catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow } return TokenNameStringLiteral; case '/' : if (!this.skipComments) { int test = getNextChar('/', '*'); if (test == 0) { //line comment this.lastCommentLinePosition = this.currentPosition; try { //get the next char if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ boolean isUnicode = false; while (this.currentCharacter != '\r' && this.currentCharacter != '\n') { if (this.currentPosition >= this.eofPosition) { this.lastCommentLinePosition = this.currentPosition; this.currentPosition ++; // this avoids duplicating the code in the catch(IndexOutOfBoundsException e) throw new IndexOutOfBoundsException(); } this.lastCommentLinePosition = this.currentPosition; //get the next char isUnicode = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } /* * We need to completely consume the line break */ if (this.currentCharacter == '\r' && this.eofPosition > this.currentPosition) { if (this.source[this.currentPosition] == '\n') { this.currentPosition++; this.currentCharacter = '\n'; } else if ((this.source[this.currentPosition] == '\\') && (this.source[this.currentPosition + 1] == 'u')) { getNextUnicodeChar(); isUnicode = true; } } recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; recordComment(TokenNameCOMMENT_LINE); if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.checkNonExternalizedStringLiterals && this.lastPosition < this.currentPosition) { parseTags(); } if (this.tokenizeComments) { return TokenNameCOMMENT_LINE; } else { this.currentPosition++; } } break; } if (test > 0) { //traditional and javadoc comment try { //get the next char boolean isJavadoc = false, star = false; boolean isUnicode = false; int previous; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if (this.currentCharacter == '*') { isJavadoc = true; star = true; } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } isUnicode = false; previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; //jump over the \\ } // empty comment is not a javadoc /**/ if (this.currentCharacter == '/') { isJavadoc = false; } //loop until end of comment */ int firstTag = 0; while ((this.currentCharacter != '/') || (!star)) { if (this.currentPosition >= this.eofPosition) { throw new InvalidInputException(UNTERMINATED_COMMENT); } if ((this.currentCharacter == '\r') || (this.currentCharacter == '\n')) { if (this.recordLineSeparator) { if (isUnicode) { pushUnicodeLineSeparator(); } else { pushLineSeparator(); } } } switch (this.currentCharacter) { case '*': star = true; break; case '@': if (firstTag == 0 && this.isFirstTag()) { firstTag = previous; } //$FALL-THROUGH$ default case to set star to false default: star = false; } //get next char previous = this.currentPosition; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { //-------------unicode traitement ------------ getNextUnicodeChar(); isUnicode = true; } else { isUnicode = false; } //handle the \\u case manually into comment if (this.currentCharacter == '\\') { if (this.source[this.currentPosition] == '\\') this.currentPosition++; } //jump over the \\ } int token = isJavadoc ? TokenNameCOMMENT_JAVADOC : TokenNameCOMMENT_BLOCK; recordComment(token); this.commentTagStarts[this.commentPtr] = firstTag; if (this.taskTags != null) checkTaskTag(this.startPosition, this.currentPosition); if (this.tokenizeComments) { /* if (isJavadoc) return TokenNameCOMMENT_JAVADOC; return TokenNameCOMMENT_BLOCK; */ return token; } } catch (IndexOutOfBoundsException e) { this.currentPosition--; throw new InvalidInputException(UNTERMINATED_COMMENT); } break; } } if (getNextChar('=')) return TokenNameDIVIDE_EQUAL; return TokenNameDIVIDE; case '\u001a' : if (atEnd()) return TokenNameEOF; //the atEnd may not be <currentPosition == source.length> if source is only some part of a real (external) stream throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ default : char c = this.currentCharacter; if (c < ScannerHelper.MAX_OBVIOUS) { if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_IDENT_START) != 0) { return scanIdentifierOrKeyword(); } else if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[c] & ScannerHelper.C_DIGIT) != 0) { return scanNumber(false); } else { return TokenNameERROR; } } boolean isJavaIdStart; if (c >= HIGH_SURROGATE_MIN_VALUE && c <= HIGH_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } // Unicode 4 detection char low = (char) getNextChar(); if (low < LOW_SURROGATE_MIN_VALUE || low > LOW_SURROGATE_MAX_VALUE) { // illegal low surrogate throw new InvalidInputException(INVALID_LOW_SURROGATE); } isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c, low); } else if (c >= LOW_SURROGATE_MIN_VALUE && c <= LOW_SURROGATE_MAX_VALUE) { if (this.complianceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } throw new InvalidInputException(INVALID_HIGH_SURROGATE); } else { // optimized case already checked isJavaIdStart = ScannerHelper.isJavaIdentifierStart(this.complianceLevel, c); } if (isJavaIdStart) return scanIdentifierOrKeyword(); if (ScannerHelper.isDigit(this.currentCharacter)) { return scanNumber(false); } return TokenNameERROR; } } } //-----------------end switch while try-------------------- catch (IndexOutOfBoundsException e) { if (this.tokenizeWhiteSpace && (whiteStart != this.currentPosition - 1)) { // reposition scanner in case we are interested by spaces as tokens this.currentPosition--; this.startPosition = whiteStart; return TokenNameWHITESPACE; } } return TokenNameEOF; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public void getNextUnicodeChar() throws InvalidInputException { //VOID //handle the case of unicode. //when a unicode appears then we must use a buffer that holds char internal values //At the end of this method currentCharacter holds the new visited char //and currentPosition points right next after it //ALL getNextChar.... ARE OPTIMIZED COPIES int c1 = 0, c2 = 0, c3 = 0, c4 = 0, unicodeSize = 6; this.currentPosition++; if (this.currentPosition < this.eofPosition) { while (this.source[this.currentPosition] == 'u') { this.currentPosition++; if (this.currentPosition >= this.eofPosition) { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } unicodeSize++; } } else { this.currentPosition--; throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((this.currentPosition + 4) > this.eofPosition) { this.currentPosition += (this.eofPosition - this.currentPosition); throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } if ((c1 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c1 < 0 || (c2 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c2 < 0 || (c3 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c3 < 0 || (c4 = ScannerHelper.getHexadecimalValue(this.source[this.currentPosition++])) > 15 || c4 < 0){ throw new InvalidInputException(INVALID_UNICODE_ESCAPE); } this.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); //need the unicode buffer if (this.withoutUnicodePtr == 0) { //buffer all the entries that have been left aside.... unicodeInitializeBuffer(this.currentPosition - unicodeSize - this.startPosition); } //fill the buffer with the char unicodeStore(); this.unicodeAsBackSlash = this.currentCharacter == '\\'; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public final boolean jumpOverUnicodeWhiteSpace() throws InvalidInputException { //BOOLEAN //handle the case of unicode. Jump over the next whiteSpace //making startPosition pointing on the next available char //On false, the currentCharacter is filled up with a potential //correct char this.wasAcr = false; getNextUnicodeChar(); return CharOperation.isWhitespace(this.currentCharacter); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
protected final void scanEscapeCharacter() throws InvalidInputException { // the string with "\\u" is a legal string of two chars \ and u //thus we use a direct access to the source (for regular cases). switch (this.currentCharacter) { case 'b' : this.currentCharacter = '\b'; break; case 't' : this.currentCharacter = '\t'; break; case 'n' : this.currentCharacter = '\n'; break; case 'f' : this.currentCharacter = '\f'; break; case 'r' : this.currentCharacter = '\r'; break; case '\"' : this.currentCharacter = '\"'; break; case '\'' : this.currentCharacter = '\''; break; case '\\' : this.currentCharacter = '\\'; break; default : // -----------octal escape-------------- // OctalDigit // OctalDigit OctalDigit // ZeroToThree OctalDigit OctalDigit int number = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (number >= 0 && number <= 7) { boolean zeroToThreeNot = number > 3; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { int digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7) { number = (number * 8) + digit; if (ScannerHelper.isDigit(this.currentCharacter = this.source[this.currentPosition++])) { if (zeroToThreeNot) {// has read \NotZeroToThree OctalDigit Digit --> ignore last character this.currentPosition--; } else { digit = ScannerHelper.getHexadecimalValue(this.currentCharacter); if (digit >= 0 && digit <= 7){ // has read \ZeroToThree OctalDigit OctalDigit number = (number * 8) + digit; } else {// has read \ZeroToThree OctalDigit NonOctalDigit --> ignore last character this.currentPosition--; } } } else { // has read \OctalDigit NonDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit NonOctalDigit--> ignore last character this.currentPosition--; } } else { // has read \OctalDigit --> ignore last character this.currentPosition--; } if (number > 255) throw new InvalidInputException(INVALID_ESCAPE); this.currentCharacter = (char) number; } else throw new InvalidInputException(INVALID_ESCAPE); } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
public int scanNumber(boolean dotPrefix) throws InvalidInputException { //when entering this method the currentCharacter is the first //digit of the number. It may be preceeded by a '.' when //dotPrefix is true boolean floating = dotPrefix; if (!dotPrefix && (this.currentCharacter == '0')) { if (getNextChar('x', 'X') >= 0) { //----------hexa----------------- int start = this.currentPosition; consumeDigits(16, true); int end = this.currentPosition; if (getNextChar('l', 'L') >= 0) { if (end == start) { throw new InvalidInputException(INVALID_HEXA); } return TokenNameLongLiteral; } else if (getNextChar('.')) { // hexadecimal floating point literal // read decimal part boolean hasNoDigitsBeforeDot = end == start; start = this.currentPosition; consumeDigits(16, true); end = this.currentPosition; if (hasNoDigitsBeforeDot && end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_HEXA); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } } else if (getNextChar('p', 'P') >= 0) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); if (getNextChar('f', 'F') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } throw new InvalidInputException(INVALID_HEXA); } if (this.sourceLevel < ClassFileConstants.JDK1_5) { throw new InvalidInputException(ILLEGAL_HEXA_LITERAL); } return TokenNameDoubleLiteral; } else { if (end == start) throw new InvalidInputException(INVALID_HEXA); return TokenNameIntegerLiteral; } } else if (getNextChar('b', 'B') >= 0) { //----------binary----------------- int start = this.currentPosition; consumeDigits(2, true); int end = this.currentPosition; if (end == start) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } throw new InvalidInputException(INVALID_BINARY); } if (getNextChar('l', 'L') >= 0) { if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameLongLiteral; } if (this.sourceLevel < ClassFileConstants.JDK1_7) { throw new InvalidInputException(BINARY_LITERAL_NOT_BELOW_17); } return TokenNameIntegerLiteral; } //there is no x or X nor b or B in the number //potential octal if (getNextCharAsDigit()) { //-------------potential octal----------------- consumeDigits(10); if (getNextChar('l', 'L') >= 0) { return TokenNameLongLiteral; } if (getNextChar('f', 'F') >= 0) { return TokenNameFloatingPointLiteral; } if (getNextChar('d', 'D') >= 0) { return TokenNameDoubleLiteral; } else { //make the distinction between octal and float .... boolean isInteger = true; if (getNextChar('.')) { isInteger = false; consumeDigits(10); } if (getNextChar('e', 'E') >= 0) { // consume next character isInteger = false; this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } consumeDigits(10); } if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; if (getNextChar('d', 'D') >= 0 || !isInteger) return TokenNameDoubleLiteral; return TokenNameIntegerLiteral; } } else { /* carry on */ } } consumeDigits(10); if ((!dotPrefix) && (getNextChar('l', 'L') >= 0)) return TokenNameLongLiteral; if ((!dotPrefix) && (getNextChar('.'))) { //decimal part that can be empty consumeDigits(10, true); floating = true; } //if floating is true both exponant and suffix may be optional if (getNextChar('e', 'E') >= 0) { floating = true; // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } if ((this.currentCharacter == '-') || (this.currentCharacter == '+')) { // consume next character this.unicodeAsBackSlash = false; if (((this.currentCharacter = this.source[this.currentPosition++]) == '\\') && (this.source[this.currentPosition] == 'u')) { getNextUnicodeChar(); } else { if (this.withoutUnicodePtr != 0) { unicodeStore(); } } } if (!ScannerHelper.isDigit(this.currentCharacter)) { if (this.currentCharacter == '_') { // wrongly place '_' consumeDigits(10); throw new InvalidInputException(INVALID_UNDERSCORE); } throw new InvalidInputException(INVALID_FLOAT); } // current character is a digit so we expect no digit first (the next character could be an underscore) consumeDigits(10); } if (getNextChar('d', 'D') >= 0) return TokenNameDoubleLiteral; if (getNextChar('f', 'F') >= 0) return TokenNameFloatingPointLiteral; //the long flag has been tested before return floating ? TokenNameDoubleLiteral : TokenNameIntegerLiteral; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/RecoveryScanner.java
public int getNextToken() throws InvalidInputException { if(this.pendingTokensPtr > -1) { int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } this.fakeTokenSource = null; this.precededByRemoved = false; if(this.data.insertedTokens != null) { for (int i = 0; i <= this.data.insertedTokensPtr; i++) { if(this.data.insertedTokensPosition[i] == this.currentPosition - 1 && i > this.skipNextInsertedTokens) { this.data.insertedTokenUsed[i] = true; this.pendingTokens = this.data.insertedTokens[i]; this.pendingTokensPtr = this.data.insertedTokens[i].length - 1; this.isInserted = true; this.startPosition = this.currentPosition; this.skipNextInsertedTokens = i; int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } } this.skipNextInsertedTokens = -1; } int previousLocation = this.currentPosition; int currentToken = super.getNextToken(); if(this.data.replacedTokens != null) { for (int i = 0; i <= this.data.replacedTokensPtr; i++) { if(this.data.replacedTokensStart[i] >= previousLocation && this.data.replacedTokensStart[i] <= this.startPosition && this.data.replacedTokensEnd[i] >= this.currentPosition - 1) { this.data.replacedTokenUsed[i] = true; this.pendingTokens = this.data.replacedTokens[i]; this.pendingTokensPtr = this.data.replacedTokens[i].length - 1; this.fakeTokenSource = FAKE_IDENTIFIER; this.isInserted = false; this.currentPosition = this.data.replacedTokensEnd[i] + 1; int nextToken = this.pendingTokens[this.pendingTokensPtr--]; if(nextToken == TerminalTokens.TokenNameIdentifier){ this.fakeTokenSource = FAKE_IDENTIFIER; } else { this.fakeTokenSource = CharOperation.NO_CHAR; } return nextToken; } } } if(this.data.removedTokensStart != null) { for (int i = 0; i <= this.data.removedTokensPtr; i++) { if(this.data.removedTokensStart[i] >= previousLocation && this.data.removedTokensStart[i] <= this.startPosition && this.data.removedTokensEnd[i] >= this.currentPosition - 1) { this.data.removedTokenUsed[i] = true; this.currentPosition = this.data.removedTokensEnd[i] + 1; this.precededByRemoved = false; return getNextToken(); } } } return currentToken; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseArguments(Object receiver) throws InvalidInputException { // Init int modulo = 0; // should be 2 for (Type,Type,...) or 3 for (Type arg,Type arg,...) int iToken = 0; char[] argName = null; List arguments = new ArrayList(10); int start = this.scanner.getCurrentTokenStartPosition(); Object typeRef = null; int dim = 0; boolean isVarargs = false; long[] dimPositions = new long[20]; // assume that there won't be more than 20 dimensions... char[] name = null; long argNamePos = -1; // Parse arguments declaration if method reference nextArg : while (this.index < this.scanner.eofPosition) { // Read argument type reference try { typeRef = parseQualifiedName(false); if (this.abort) return null; // May be aborted by specialized parser } catch (InvalidInputException e) { break nextArg; } boolean firstArg = modulo == 0; if (firstArg) { // verify position if (iToken != 0) break nextArg; } else if ((iToken % modulo) != 0) { break nextArg; } if (typeRef == null) { if (firstArg && this.currentTokenType == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } this.lineStarted = true; return createMethodReference(receiver, null); } break nextArg; } iToken++; // Read possible additional type info dim = 0; isVarargs = false; if (readToken() == TerminalTokens.TokenNameLBRACKET) { // array declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); while (readToken() == TerminalTokens.TokenNameLBRACKET) { consumeToken(); if (readToken() != TerminalTokens.TokenNameRBRACKET) { break nextArg; } consumeToken(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); } } else if (readToken() == TerminalTokens.TokenNameELLIPSIS) { // ellipsis declaration int dimStart = this.scanner.getCurrentTokenStartPosition(); dimPositions[dim++] = (((long) dimStart) << 32) + this.scanner.getCurrentTokenEndPosition(); consumeToken(); isVarargs = true; } // Read argument name argNamePos = -1; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); if (firstArg) { // verify position if (iToken != 1) break nextArg; } else if ((iToken % modulo) != 1) { break nextArg; } if (argName == null) { // verify that all arguments name are declared if (!firstArg) { break nextArg; } } argName = this.scanner.getCurrentIdentifierSource(); argNamePos = (((long)this.scanner.getCurrentTokenStartPosition())<<32)+this.scanner.getCurrentTokenEndPosition(); iToken++; } else if (argName != null) { // verify that no argument name is declared break nextArg; } // Verify token position if (firstArg) { modulo = iToken + 1; } else { if ((iToken % modulo) != (modulo - 1)) { break nextArg; } } // Read separator or end arguments declaration int token = readToken(); name = argName == null ? CharOperation.NO_CHAR : argName; if (token == TerminalTokens.TokenNameCOMMA) { // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); iToken++; } else if (token == TerminalTokens.TokenNameRPAREN) { // verify characters after arguments declaration (expecting white space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } // Create new argument Object argument = createArgumentReference(name, dim, isVarargs, typeRef, dimPositions, argNamePos); if (this.abort) return null; // May be aborted by specialized parser arguments.add(argument); consumeToken(); return createMethodReference(receiver, arguments); } else { break nextArg; } } // Something wrong happened => Invalid input throw new InvalidInputException(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseHtmlTag(int previousPosition, int endTextPosition) throws InvalidInputException { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseHref() throws InvalidInputException { boolean skipComments = this.scanner.skipComments; this.scanner.skipComments = true; try { int start = this.scanner.getCurrentTokenStartPosition(); char currentChar = readChar(); if (currentChar == 'a' || currentChar == 'A') { this.scanner.currentPosition = this.index; if (readToken() == TerminalTokens.TokenNameIdentifier) { consumeToken(); try { if (CharOperation.equals(this.scanner.getCurrentIdentifierSource(), HREF_TAG, false) && readToken() == TerminalTokens.TokenNameEQUAL) { consumeToken(); if (readToken() == TerminalTokens.TokenNameStringLiteral) { consumeToken(); while (this.index < this.javadocEnd) { // main loop to search for the </a> pattern // Skip all characters after string literal until closing '>' (see bug 68726) while (readToken() != TerminalTokens.TokenNameGREATER) { if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' || (this.inlineTagStarted && this.scanner.currentCharacter == '}')) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } return false; } this.currentTokenType = -1; // consume token without updating line end } consumeToken(); // update line end as new lines are allowed in URL description while (readToken() != TerminalTokens.TokenNameLESS) { if (this.scanner.currentPosition >= this.scanner.eofPosition || this.scanner.currentCharacter == '@' || (this.inlineTagStarted && this.scanner.currentCharacter == '}')) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } return false; } consumeToken(); } consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); currentChar = readChar(); // search for the </a> pattern and store last char read if (currentChar == '/') { currentChar = readChar(); if (currentChar == 'a' || currentChar =='A') { currentChar = readChar(); if (currentChar == '>') { return true; // valid href } } } // search for invalid char in tags if (currentChar == '\r' || currentChar == '\n' || currentChar == '\t' || currentChar == ' ') { break; } } } } } catch (InvalidInputException ex) { // Do nothing as we want to keep positions for error message } } } // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; // Signal syntax error if (this.tagValue != TAG_VALUE_VALUE) { // do not report error for @value tag, this will be done after... if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeHref(start, this.lineEnd); } } finally { this.scanner.skipComments = skipComments; } return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseMember(Object receiver) throws InvalidInputException { // Init this.identifierPtr = -1; this.identifierLengthPtr = -1; int start = this.scanner.getCurrentTokenStartPosition(); this.memberStart = start; // Get member identifier if (readToken() == TerminalTokens.TokenNameIdentifier) { if (this.scanner.currentCharacter == '.') { // member name may be qualified (inner class constructor reference) parseQualifiedName(true); } else { consumeToken(); pushIdentifier(true, false); } // Look for next token to know whether it's a field or method reference int previousPosition = this.index; if (readToken() == TerminalTokens.TokenNameLPAREN) { consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); try { return parseArguments(receiver); } catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); } return null; } // Reset position: we want to rescan last token this.index = previousPosition; this.scanner.currentPosition = previousPosition; this.currentTokenType = -1; // Verify character(s) after identifier (expecting space or end comment) if (!verifySpaceOrEndComment()) { int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(start, end); return null; } return createFieldReference(receiver); } int end = getTokenEndPosition() - 1; end = start > end ? start : end; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(start, end); // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseParam() throws InvalidInputException { // Store current state int start = this.tagSourceStart; int end = this.tagSourceEnd; boolean tokenWhiteSpace = this.scanner.tokenizeWhiteSpace; this.scanner.tokenizeWhiteSpace = true; try { // Verify that there are whitespaces after tag boolean isCompletionParser = (this.kind & COMPLETION_PARSER) != 0; if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidTag(start, this.scanner.getCurrentTokenEndPosition()); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; } // Get first non whitespace token this.identifierPtr = -1; this.identifierLengthPtr = -1; boolean hasMultiLines = this.scanner.currentPosition > (this.lineEnd+1); boolean isTypeParam = false; boolean valid = true, empty = true; boolean mayBeGeneric = this.sourceLevel >= ClassFileConstants.JDK1_5; int token = -1; nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameIdentifier : if (valid) { // store param name id pushIdentifier(true, false); start = this.scanner.getCurrentTokenStartPosition(); end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); break nextToken; } // $FALL-THROUGH$ - fall through next case to report error case TerminalTokens.TokenNameLESS: if (valid && mayBeGeneric) { // store '<' in identifiers stack as we need to add it to tag element (bug 79809) pushIdentifier(true, true); start = this.scanner.getCurrentTokenStartPosition(); end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); isTypeParam = true; break nextToken; } // $FALL-THROUGH$ - fall through next case to report error default: if (token == TerminalTokens.TokenNameLEFT_SHIFT) isTypeParam = true; if (valid && !hasMultiLines) start = this.scanner.getCurrentTokenStartPosition(); valid = false; if (!hasMultiLines) { empty = false; end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); break; } end = this.lineEnd; // $FALL-THROUGH$ - when several lines, fall through next case to report problem immediately case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.currentPosition > (this.lineEnd+1)) hasMultiLines = true; if (valid) break; // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) if (empty) this.sourceParser.problemReporter().javadocMissingParamName(start, end, this.sourceParser.modifiers); else if (mayBeGeneric && isTypeParam) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); else this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; } } // Scan more tokens for type parameter declaration if (isTypeParam && mayBeGeneric) { // Get type parameter name nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameWHITESPACE: if (valid && this.scanner.currentPosition <= (this.lineEnd+1)) { break; } // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; case TerminalTokens.TokenNameIdentifier : end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); if (valid) { // store param name id pushIdentifier(false, false); break nextToken; } break; default: end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); valid = false; break; } } // Get last character of type parameter declaration boolean spaces = false; nextToken: while (true) { this.currentTokenType = -1; try { token = readToken(); } catch (InvalidInputException e) { valid = false; } switch (token) { case TerminalTokens.TokenNameWHITESPACE: if (this.scanner.currentPosition > (this.lineEnd+1)) { // do not accept type parameter declaration on several lines hasMultiLines = true; valid = false; } spaces = true; if (valid) break; // $FALL-THROUGH$ - if not valid fall through next case to report error case TerminalTokens.TokenNameEOF: if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); if (!isCompletionParser) { this.scanner.currentPosition = start; this.index = start; } this.currentTokenType = -1; return false; case TerminalTokens.TokenNameGREATER: end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); if (valid) { // store '>' in identifiers stack as we need to add it to tag element (bug 79809) pushIdentifier(false, true); break nextToken; } break; default: if (!spaces) end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); valid = false; break; } } } // Verify that tag name is well followed by white spaces if (valid) { this.currentTokenType = -1; int restart = this.scanner.currentPosition; try { token = readTokenAndConsume(); } catch (InvalidInputException e) { valid = false; } if (token == TerminalTokens.TokenNameWHITESPACE) { this.scanner.resetTo(restart, this.javadocEnd); this.index = restart; return pushParamName(isTypeParam); } } // Report problem this.currentTokenType = -1; if (isCompletionParser) return false; if (this.reportProblems) { // we only need end if we report problems end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); try { while ((token=readToken()) != TerminalTokens.TokenNameWHITESPACE && token != TerminalTokens.TokenNameEOF) { this.currentTokenType = -1; end = hasMultiLines ? this.lineEnd: this.scanner.getCurrentTokenEndPosition(); } } catch (InvalidInputException e) { end = this.lineEnd; } if (mayBeGeneric && isTypeParam) this.sourceParser.problemReporter().javadocInvalidParamTypeParameter(start, end); else this.sourceParser.problemReporter().javadocInvalidParamTagName(start, end); } this.scanner.currentPosition = start; this.index = start; this.currentTokenType = -1; return false; } finally { // we have to make sure that this is reset to the previous value even if an exception occurs this.scanner.tokenizeWhiteSpace = tokenWhiteSpace; } }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object parseQualifiedName(boolean reset) throws InvalidInputException { // Reset identifier stack if requested if (reset) { this.identifierPtr = -1; this.identifierLengthPtr = -1; } // Scan tokens int primitiveToken = -1; int parserKind = this.kind & PARSER_KIND; nextToken : for (int iToken = 0; ; iToken++) { int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameIdentifier : if (((iToken & 1) != 0)) { // identifiers must be odd tokens break nextToken; } pushIdentifier(iToken == 0, false); consumeToken(); break; case TerminalTokens.TokenNameDOT : if ((iToken & 1) == 0) { // dots must be even tokens throw new InvalidInputException(); } consumeToken(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: if (iToken == 0) { pushIdentifier(true, true); primitiveToken = token; consumeToken(); break nextToken; } // Fall through default case to verify that we do not leave on a dot //$FALL-THROUGH$ default : if (iToken == 0) { if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return null; } if ((iToken & 1) == 0) { // cannot leave on a dot switch (parserKind) { case COMPLETION_PARSER: if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return syntaxRecoverQualifiedName(primitiveToken); case DOM_PARSER: if (this.currentTokenType != -1) { // Reset position: we want to rescan last token this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } // $FALL-THROUGH$ - fall through default case to raise exception default: throw new InvalidInputException(); } } break nextToken; } } // Reset position: we want to rescan last token if (parserKind != COMPLETION_PARSER && this.currentTokenType != -1) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; } if (this.identifierPtr>=0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; } return createTypeReference(primitiveToken); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected boolean parseReference() throws InvalidInputException { int currentPosition = this.scanner.currentPosition; try { Object typeRef = null; Object reference = null; int previousPosition = -1; int typeRefStartPosition = -1; // Get reference tokens nextToken : while (this.index < this.scanner.eofPosition) { previousPosition = this.index; int token = readTokenSafely(); switch (token) { case TerminalTokens.TokenNameStringLiteral : // @see "string" // If typeRef != null we may raise a warning here to let user know there's an unused reference... // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) if (typeRef != null) break nextToken; consumeToken(); int start = this.scanner.getCurrentTokenStartPosition(); if (this.tagValue == TAG_VALUE_VALUE) { // String reference are not allowed for @value tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getTokenEndPosition(), this.sourceParser.modifiers); return false; } // verify end line if (verifyEndLine(previousPosition)) { return createFakeReference(start); } if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd); return false; case TerminalTokens.TokenNameLESS : // @see <a href="URL#Value">label</a> // If typeRef != null we may raise a warning here to let user know there's an unused reference... // Currently as javadoc 1.4.2 ignore it, we do the same (see bug 69302) if (typeRef != null) break nextToken; consumeToken(); start = this.scanner.getCurrentTokenStartPosition(); if (parseHref()) { consumeToken(); if (this.tagValue == TAG_VALUE_VALUE) { // String reference are not allowed for @value tag if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getIndexPosition(), this.sourceParser.modifiers); return false; } // verify end line if (verifyEndLine(previousPosition)) { return createFakeReference(start); } if (this.reportProblems) this.sourceParser.problemReporter().javadocUnexpectedText(this.scanner.currentPosition, this.lineEnd); } else if (this.tagValue == TAG_VALUE_VALUE) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidValueReference(start, getIndexPosition(), this.sourceParser.modifiers); } return false; case TerminalTokens.TokenNameERROR : consumeToken(); if (this.scanner.currentCharacter == '#') { // @see ...#member reference = parseMember(typeRef); if (reference != null) { return pushSeeRef(reference); } return false; } char[] currentError = this.scanner.getCurrentIdentifierSource(); if (currentError.length>0 && currentError[0] == '"') { if (this.reportProblems) { boolean isUrlRef = false; if (this.tagValue == TAG_SEE_VALUE) { int length=currentError.length, i=1 /* first char is " */; while (i<length && ScannerHelper.isLetter(currentError[i])) { i++; } if (i<(length-2) && currentError[i] == ':' && currentError[i+1] == '/' && currentError[i+2] == '/') { isUrlRef = true; } } if (isUrlRef) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=207765 // handle invalid URL references in javadoc with dedicated message this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition()); } else { this.sourceParser.problemReporter().javadocInvalidReference(this.scanner.getCurrentTokenStartPosition(), getTokenEndPosition()); } } return false; } break nextToken; case TerminalTokens.TokenNameIdentifier : if (typeRef == null) { typeRefStartPosition = this.scanner.getCurrentTokenStartPosition(); typeRef = parseQualifiedName(true); if (this.abort) return false; // May be aborted by specialized parser break; } break nextToken; default : break nextToken; } } // Verify that we got a reference if (reference == null) reference = typeRef; if (reference == null) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; if (this.tagValue == TAG_VALUE_VALUE) { if ((this.kind & DOM_PARSER) != 0) createTag(); return true; } if (this.reportProblems) { this.sourceParser.problemReporter().javadocMissingReference(this.tagSourceStart, this.tagSourceEnd, this.sourceParser.modifiers); } return false; } // Reset position at the end of type reference if (this.lastIdentifierEndPosition > this.javadocStart) { this.index = this.lastIdentifierEndPosition+1; this.scanner.currentPosition = this.index; } this.currentTokenType = -1; // In case of @value, we have an invalid reference (only static field refs are valid for this tag) if (this.tagValue == TAG_VALUE_VALUE) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(typeRefStartPosition, this.lineEnd); return false; } int currentIndex = this.index; // store current index char ch = readChar(); switch (ch) { // Verify that line end does not start with an open parenthese (which could be a constructor reference wrongly written...) // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=47215 case '(' : if (this.reportProblems) this.sourceParser.problemReporter().javadocMissingHashCharacter(typeRefStartPosition, this.lineEnd, String.valueOf(this.source, typeRefStartPosition, this.lineEnd-typeRefStartPosition+1)); return false; // Search for the :// URL pattern // See bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=168849 case ':' : ch = readChar(); if (ch == '/' && ch == readChar()) { if (this.reportProblems) { this.sourceParser.problemReporter().javadocInvalidSeeUrlReference(typeRefStartPosition, this.lineEnd); return false; } } } // revert to last stored index this.index = currentIndex; // Verify that we get white space after reference if (!verifySpaceOrEndComment()) { this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; int end = this.starPosition == -1 ? this.lineEnd : this.starPosition; if (this.source[end]=='\n') end--; if (this.reportProblems) this.sourceParser.problemReporter().javadocMalformedSeeReference(typeRefStartPosition, end); return false; } // Everything is OK, store reference return pushSeeRef(reference); } catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); } // Reset position to avoid missing tokens when new line was encountered this.index = this.tokenPreviousPosition; this.scanner.currentPosition = this.tokenPreviousPosition; this.currentTokenType = -1; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected int readToken() throws InvalidInputException { if (this.currentTokenType < 0) { this.tokenPreviousPosition = this.scanner.currentPosition; this.currentTokenType = this.scanner.getNextToken(); if (this.scanner.currentPosition > (this.lineEnd+1)) { // be sure to be on next line (lineEnd is still on the same line) this.lineStarted = false; while (this.currentTokenType == TerminalTokens.TokenNameMULTIPLY) { this.currentTokenType = this.scanner.getNextToken(); } } this.index = this.scanner.currentPosition; this.lineStarted = true; // after having read a token, line is obviously started... } return this.currentTokenType; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected int readTokenAndConsume() throws InvalidInputException { int token = readToken(); consumeToken(); return token; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
protected Object syntaxRecoverQualifiedName(int primitiveToken) throws InvalidInputException { // do nothing, just an entry point for recovery return null; }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createArgumentReference(char[] name, int dim, boolean isVarargs, Object typeRef, long[] dimPositions, long argNamePos) throws InvalidInputException { try { MethodRefParameter argument = this.ast.newMethodRefParameter(); ASTNode node = (ASTNode) typeRef; int argStart = node.getStartPosition(); int argEnd = node.getStartPosition()+node.getLength()-1; if (dim > 0) argEnd = (int) dimPositions[dim-1]; if (argNamePos >= 0) argEnd = (int) argNamePos; if (name.length != 0) { final SimpleName argName = new SimpleName(this.ast); argName.internalSetIdentifier(new String(name)); argument.setName(argName); int argNameStart = (int) (argNamePos >>> 32); argName.setSourceRange(argNameStart, argEnd-argNameStart+1); } Type argType = null; if (node.getNodeType() == ASTNode.PRIMITIVE_TYPE) { argType = (PrimitiveType) node; // if (dim > 0) { // argType = this.ast.newArrayType(argType, dim); // argType.setSourceRange(argStart, ((int) dimPositions[dim-1])-argStart+1); // } } else { Name argTypeName = (Name) node; argType = this.ast.newSimpleType(argTypeName); argType.setSourceRange(argStart, node.getLength()); } if (dim > 0 && !isVarargs) { for (int i=0; i<dim; i++) { argType = this.ast.newArrayType(argType); argType.setSourceRange(argStart, ((int) dimPositions[i])-argStart+1); } } argument.setType(argType); argument.setSourceRange(argStart, argEnd - argStart + 1); return argument; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createFieldReference(Object receiver) throws InvalidInputException { try { MemberRef fieldRef = this.ast.newMemberRef(); SimpleName fieldName = new SimpleName(this.ast); fieldName.internalSetIdentifier(new String(this.identifierStack[0])); fieldRef.setName(fieldName); int start = (int) (this.identifierPositionStack[0] >>> 32); int end = (int) this.identifierPositionStack[0]; fieldName.setSourceRange(start, end - start + 1); if (receiver == null) { start = this.memberStart; fieldRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; fieldRef.setQualifier(typeRef); start = typeRef.getStartPosition(); end = fieldName.getStartPosition()+fieldName.getLength()-1; fieldRef.setSourceRange(start, end-start+1); } return fieldRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected Object createMethodReference(Object receiver, List arguments) throws InvalidInputException { try { // Create method ref MethodRef methodRef = this.ast.newMethodRef(); SimpleName methodName = new SimpleName(this.ast); int length = this.identifierLengthStack[0] - 1; // may be > 0 for member class constructor reference methodName.internalSetIdentifier(new String(this.identifierStack[length])); methodRef.setName(methodName); int start = (int) (this.identifierPositionStack[length] >>> 32); int end = (int) this.identifierPositionStack[length]; methodName.setSourceRange(start, end - start + 1); // Set qualifier if (receiver == null) { start = this.memberStart; methodRef.setSourceRange(start, end - start + 1); } else { Name typeRef = (Name) receiver; methodRef.setQualifier(typeRef); start = typeRef.getStartPosition(); } // Add arguments if (arguments != null) { Iterator parameters = arguments.listIterator(); while (parameters.hasNext()) { MethodRefParameter param = (MethodRefParameter) parameters.next(); methodRef.parameters().add(param); } } methodRef.setSourceRange(start, this.scanner.getCurrentTokenEndPosition()-start+1); return methodRef; } catch (ClassCastException ex) { throw new InvalidInputException(); } }
// in dom/org/eclipse/jdt/core/dom/DocCommentParser.java
protected boolean parseTag(int previousPosition) throws InvalidInputException { // Read tag name int currentPosition = this.index; int token = readTokenAndConsume(); char[] tagName = CharOperation.NO_CHAR; if (currentPosition == this.scanner.startPosition) { this.tagSourceStart = this.scanner.getCurrentTokenStartPosition(); this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); tagName = this.scanner.getCurrentIdentifierSource(); } else { this.tagSourceEnd = currentPosition-1; } // Try to get tag name other than java identifier // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=51660) if (this.scanner.currentCharacter != ' ' && !ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { tagNameToken: while (token != TerminalTokens.TokenNameEOF && this.index < this.scanner.eofPosition) { int length = tagName.length; // !, ", #, %, &, ', -, :, <, >, * chars and spaces are not allowed in tag names switch (this.scanner.currentCharacter) { case '}': case '*': // break for '*' as this is perhaps the end of comment (bug 65288) case '!': case '#': case '%': case '&': case '\'': case '"': case ':': case '<': case '>': break tagNameToken; case '-': // allowed in tag names as this character is often used in doclets (bug 68087) System.arraycopy(tagName, 0, tagName = new char[length+1], 0, length); tagName[length] = this.scanner.currentCharacter; break; default: if (this.scanner.currentCharacter == ' ' || ScannerHelper.isWhitespace(this.scanner.currentCharacter)) { break tagNameToken; } token = readTokenAndConsume(); char[] ident = this.scanner.getCurrentIdentifierSource(); System.arraycopy(tagName, 0, tagName = new char[length+ident.length], 0, length); System.arraycopy(ident, 0, tagName, length, ident.length); break; } this.tagSourceEnd = this.scanner.getCurrentTokenEndPosition(); this.scanner.getNextChar(); this.index = this.scanner.currentPosition; } } int length = tagName.length; this.index = this.tagSourceEnd+1; this.scanner.currentPosition = this.tagSourceEnd+1; this.tagSourceStart = previousPosition; // tage name may be empty (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=125903) if (tagName.length == 0) { return false; } // Decide which parse to perform depending on tag name this.tagValue = NO_TAG_VALUE; boolean valid = true; switch (token) { case TerminalTokens.TokenNameIdentifier : switch (tagName[0]) { case 'c': if (length == TAG_CATEGORY_LENGTH && CharOperation.equals(TAG_CATEGORY, tagName)) { this.tagValue = TAG_CATEGORY_VALUE; valid = parseIdentifierTag(false); // TODO (frederic) reconsider parameter value when @category will be significant in spec } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'd': if (length == TAG_DEPRECATED_LENGTH && CharOperation.equals(TAG_DEPRECATED, tagName)) { this.deprecated = true; this.tagValue = TAG_DEPRECATED_VALUE; } else { this.tagValue = TAG_OTHERS_VALUE; } createTag(); break; case 'i': if (length == TAG_INHERITDOC_LENGTH && CharOperation.equals(TAG_INHERITDOC, tagName)) { if (this.reportProblems) { recordInheritedPosition((((long) this.tagSourceStart) << 32) + this.tagSourceEnd); } this.tagValue = TAG_INHERITDOC_VALUE; } else { this.tagValue = TAG_OTHERS_VALUE; } createTag(); break; case 'p': if (length == TAG_PARAM_LENGTH && CharOperation.equals(TAG_PARAM, tagName)) { this.tagValue = TAG_PARAM_VALUE; valid = parseParam(); } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'e': if (length == TAG_EXCEPTION_LENGTH && CharOperation.equals(TAG_EXCEPTION, tagName)) { this.tagValue = TAG_EXCEPTION_VALUE; valid = parseThrows(); } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 's': if (length == TAG_SEE_LENGTH && CharOperation.equals(TAG_SEE, tagName)) { this.tagValue = TAG_SEE_VALUE; if (this.inlineTagStarted) { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @see inside inline comment valid = false; } else { valid = parseReference(); } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'l': if (length == TAG_LINK_LENGTH && CharOperation.equals(TAG_LINK, tagName)) { this.tagValue = TAG_LINK_VALUE; } else if (length == TAG_LINKPLAIN_LENGTH && CharOperation.equals(TAG_LINKPLAIN, tagName)) { this.tagValue = TAG_LINKPLAIN_VALUE; } if (this.tagValue != NO_TAG_VALUE) { if (this.inlineTagStarted) { valid = parseReference(); } else { // bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=53290 // Cannot have @link outside inline comment valid = false; } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case 'v': if (this.sourceLevel >= ClassFileConstants.JDK1_5 && length == TAG_VALUE_LENGTH && CharOperation.equals(TAG_VALUE, tagName)) { this.tagValue = TAG_VALUE_VALUE; if (this.inlineTagStarted) { valid = parseReference(); } else { valid = false; } } else { this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; default: this.tagValue = TAG_OTHERS_VALUE; createTag(); } break; case TerminalTokens.TokenNamereturn : this.tagValue = TAG_RETURN_VALUE; valid = parseReturn(); break; case TerminalTokens.TokenNamethrows : this.tagValue = TAG_THROWS_VALUE; valid = parseThrows(); break; case TerminalTokens.TokenNameabstract: case TerminalTokens.TokenNameassert: case TerminalTokens.TokenNameboolean: case TerminalTokens.TokenNamebreak: case TerminalTokens.TokenNamebyte: case TerminalTokens.TokenNamecase: case TerminalTokens.TokenNamecatch: case TerminalTokens.TokenNamechar: case TerminalTokens.TokenNameclass: case TerminalTokens.TokenNamecontinue: case TerminalTokens.TokenNamedefault: case TerminalTokens.TokenNamedo: case TerminalTokens.TokenNamedouble: case TerminalTokens.TokenNameelse: case TerminalTokens.TokenNameextends: case TerminalTokens.TokenNamefalse: case TerminalTokens.TokenNamefinal: case TerminalTokens.TokenNamefinally: case TerminalTokens.TokenNamefloat: case TerminalTokens.TokenNamefor: case TerminalTokens.TokenNameif: case TerminalTokens.TokenNameimplements: case TerminalTokens.TokenNameimport: case TerminalTokens.TokenNameinstanceof: case TerminalTokens.TokenNameint: case TerminalTokens.TokenNameinterface: case TerminalTokens.TokenNamelong: case TerminalTokens.TokenNamenative: case TerminalTokens.TokenNamenew: case TerminalTokens.TokenNamenull: case TerminalTokens.TokenNamepackage: case TerminalTokens.TokenNameprivate: case TerminalTokens.TokenNameprotected: case TerminalTokens.TokenNamepublic: case TerminalTokens.TokenNameshort: case TerminalTokens.TokenNamestatic: case TerminalTokens.TokenNamestrictfp: case TerminalTokens.TokenNamesuper: case TerminalTokens.TokenNameswitch: case TerminalTokens.TokenNamesynchronized: case TerminalTokens.TokenNamethis: case TerminalTokens.TokenNamethrow: case TerminalTokens.TokenNametransient: case TerminalTokens.TokenNametrue: case TerminalTokens.TokenNametry: case TerminalTokens.TokenNamevoid: case TerminalTokens.TokenNamevolatile: case TerminalTokens.TokenNamewhile: case TerminalTokens.TokenNameenum : case TerminalTokens.TokenNameconst : case TerminalTokens.TokenNamegoto : this.tagValue = TAG_OTHERS_VALUE; createTag(); break; } this.textStart = this.index; return valid; }
149
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException ex) { // give up }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException iie) { // give up }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { //ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (InvalidInputException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
catch (InvalidInputException e) { // invalid class name }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (InvalidInputException e) { return null; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { openBodyEnd = this.fDocument.length; openBodyStart = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { closeBodyStart = this.fDocument.length; closeBodyEnd = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/jdom/DOMType.java
catch(InvalidInputException e) { closeBodyStart = this.fDocument.length; closeBodyEnd = this.fDocument.length; }
// in model/org/eclipse/jdt/internal/core/Member.java
catch (InvalidInputException ex) { // try if there is inherited Javadoc }
// in model/org/eclipse/jdt/internal/core/InternalNamingConventions.java
catch(InvalidInputException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/InternalNamingConventions.java
catch(InvalidInputException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return -1; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException ex) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { // ignore }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (InvalidInputException e) { return; }
// in model/org/eclipse/jdt/core/JavaConventions.java
catch (InvalidInputException e) { return null; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(currentTokenEndPosition-1); newLine = false; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(commentEnd); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // skip }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // maybe an unterminated string or comment lastColumn += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // Assume length is one int tokenLength = 1; if (nodeStart > (previousEnd+1)) { tokenLength++; // include space between nodes } if ((this.column + tokenLength) > maxColumn) { return 1; } }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // does not happen as syntax is correct }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { // maybe an unterminated string or comment textLength += (this.scanner.atEnd() ? this.scanner.eofPosition : this.scanner.currentPosition) - this.scanner.startPosition; }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // there's nothing to do if this exception happens }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // leave }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { // skip }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException iie) { token = consumeInvalidToken(textEnd); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor.java
catch(InvalidInputException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java
catch (InvalidInputException e) { // ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { break nextArg; }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException ex) { // ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionJavadocParser.java
catch (InvalidInputException e) { consumeToken(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (InvalidInputException e) { return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.unicodeAsBackSlash = false; this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return -1; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = temp; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch(InvalidInputException e) { this.currentPosition = pos; this.withoutUnicodePtr = temp2; return false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException ex) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch (InvalidInputException e) { // Nothing to do }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ // it's impossible because we added pending tokens before }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ pos = this.scanner.currentPosition; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(InvalidInputException e){ if (!this.hasReportedError){ problemReporter().scannerError(this, e.getMessage()); this.hasReportedError = true; } this.lastCheckPoint = this.scanner.currentPosition; this.currentToken = 0; this.restartRecovery = true; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/diagnose/LexStream.java
catch (InvalidInputException e) { // return next token }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { consumeToken(); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { break nextArg; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { // Do nothing as we want to keep positions for error message }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { int end = this.scanner.getCurrentTokenEndPosition() < this.lineEnd ? this.scanner.getCurrentTokenEndPosition() : this.scanner.getCurrentTokenStartPosition(); end = end < this.lineEnd ? end : this.lineEnd; if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidSeeReferenceArgs(start, end); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { valid = false; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException e) { end = this.lineEnd; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidReference(currentPosition, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException ex) { if (this.reportProblems) this.sourceParser.problemReporter().javadocInvalidThrowsClass(start, getTokenEndPosition()); }
// in compiler/org/eclipse/jdt/internal/compiler/parser/AbstractCommentParser.java
catch (InvalidInputException iie) { // token is already set to error }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/problem/ProblemReporter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/NodeFinder.java
catch (InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // Should not happen, but return no extended position... return nodeStart; }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/DefaultCommentMapper.java
catch (InvalidInputException e) { // Should not happen, but return no extended position... return nodeEnd; }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch (InvalidInputException e){ // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
catch(InvalidInputException e) { // ignore }
19
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch(InvalidInputException e) { throw new AbortFormatting(e); }
// in codeassist/org/eclipse/jdt/internal/codeassist/complete/CompletionScanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (InvalidInputException e) { if (e.getMessage().equals(INVALID_ESCAPE)) { // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed for (int lookAhead = 0; lookAhead < 50; lookAhead++) { if (this.currentPosition + lookAhead == this.eofPosition) break; if (this.source[this.currentPosition + lookAhead] == '\n') break; if (this.source[this.currentPosition + lookAhead] == '\"') { this.currentPosition += lookAhead + 1; break; } } } throw e; // rethrow }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/TokenScanner.java
catch (InvalidInputException e) { throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); }
// in dom/org/eclipse/jdt/core/dom/Statement.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/SimpleName.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/Javadoc.java
catch (InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/CharacterLiteral.java
catch (InvalidInputException e) { throw new IllegalArgumentException("illegal character literal");//$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/NumberLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException("Invalid string literal : >" + token + "<");//$NON-NLS-1$//$NON-NLS-2$ }
// in dom/org/eclipse/jdt/core/dom/StringLiteral.java
catch(InvalidInputException e) { throw new IllegalArgumentException(); }
15
unknown (Lib) InvocationTargetException 0 0 0 6
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (InvocationTargetException e) { // should never happen }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (InvocationTargetException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (InvocationTargetException e) { // ignored }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (InvocationTargetException e) { // concrete AST node classes do not die in the constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
unknown (Domain) JavaModelException
public class JavaModelException extends CoreException {

	private static final long serialVersionUID = -760398656505871287L; // backward compatible

	CoreException nestedCoreException;
/**
 * Creates a Java model exception that wrappers the given <code>Throwable</code>.
 * The exception contains a Java-specific status object with severity
 * <code>IStatus.ERROR</code> and the given status code.
 *
 * @param e the <code>Throwable</code>
 * @param code one of the Java-specific status codes declared in
 *   <code>IJavaModelStatusConstants</code>
 * @see IJavaModelStatusConstants
 * @see org.eclipse.core.runtime.IStatus#ERROR
 */
public JavaModelException(Throwable e, int code) {
	this(new JavaModelStatus(code, e));
}
/**
 * Creates a Java model exception for the given <code>CoreException</code>.
 * Equivalent to
 * <code>JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION</code>.
 *
 * @param exception the <code>CoreException</code>
 */
public JavaModelException(CoreException exception) {
	super(exception.getStatus());
	this.nestedCoreException = exception;
}
/**
 * Creates a Java model exception for the given Java-specific status object.
 *
 * @param status the Java-specific status object
 */
public JavaModelException(IJavaModelStatus status) {
	super(status);
}
/**
 * Returns the underlying <code>Throwable</code> that caused the failure.
 *
 * @return the wrappered <code>Throwable</code>, or <code>null</code> if the
 *   direct case of the failure was at the Java model layer
 */
public Throwable getException() {
	if (this.nestedCoreException == null) {
		return getStatus().getException();
	} else {
		return this.nestedCoreException;
	}
}
/**
 * Returns the Java model status object for this exception.
 * Equivalent to <code>(IJavaModelStatus) getStatus()</code>.
 *
 * @return a status object
 */
public IJavaModelStatus getJavaModelStatus() {
	IStatus status = getStatus();
	if (status instanceof IJavaModelStatus) {
		return (IJavaModelStatus)status;
	} else {
		// A regular IStatus is created only in the case of a CoreException.
		// See bug 13492 Should handle JavaModelExceptions that contains CoreException more gracefully
		return new JavaModelStatus(this.nestedCoreException);
	}
}
/**
 * Returns whether this exception indicates that a Java model element does not
 * exist. Such exceptions have a status with a code of
 * <code>IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code> or
 * <code>IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH</code>.
 * This is a convenience method.
 *
 * @return <code>true</code> if this exception indicates that a Java model
 *   element does not exist
 * @see IJavaModelStatus#isDoesNotExist()
 * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
 * @see IJavaModelStatusConstants#ELEMENT_NOT_ON_CLASSPATH
 */
public boolean isDoesNotExist() {
	IJavaModelStatus javaModelStatus = getJavaModelStatus();
	return javaModelStatus != null && javaModelStatus.isDoesNotExist();
}

/**
 * Prints this exception's stack trace to the given print stream.
 *
 * @param output the print stream
 * @since 3.0
 */
public void printStackTrace(PrintStream output) {
	synchronized(output) {
		super.printStackTrace(output);
		Throwable throwable = getException();
		if (throwable != null) {
			output.print("Caused by: "); //$NON-NLS-1$
			throwable.printStackTrace(output);
		}
	}
}

/**
 * Prints this exception's stack trace to the given print writer.
 *
 * @param output the print writer
 * @since 3.0
 */
public void printStackTrace(PrintWriter output) {
	synchronized(output) {
		super.printStackTrace(output);
		Throwable throwable = getException();
		if (throwable != null) {
			output.print("Caused by: "); //$NON-NLS-1$
			throwable.printStackTrace(output);
		}
	}
}
/*
 * Returns a printable representation of this exception suitable for debugging
 * purposes only.
 */
public String toString() {
	StringBuffer buffer= new StringBuffer();
	buffer.append("Java Model Exception: "); //$NON-NLS-1$
	if (getException() != null) {
		if (getException() instanceof CoreException) {
			CoreException c= (CoreException)getException();
			buffer.append("Core Exception [code "); //$NON-NLS-1$
			buffer.append(c.getStatus().getCode());
			buffer.append("] "); //$NON-NLS-1$
			buffer.append(c.getStatus().getMessage());
		} else {
			buffer.append(getException().toString());
		}
	} else {
		buffer.append(getStatus().toString());
	}
	return buffer.toString();
}
}
133
            
// 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/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
protected IBinaryType getBinaryInfo(ClassFile classFile, IResource resource) throws CoreException { BinaryType binaryType = (BinaryType) classFile.getType(); if (classFile.isOpen()) return (IBinaryType) binaryType.getElementInfo(); // reuse the info from the java model cache // create a temporary info IBinaryType info; try { PackageFragment pkg = (PackageFragment) classFile.getParent(); PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent(); if (root.isArchive()) { // class file in a jar String classFileName = classFile.getElementName(); String classFilePath = Util.concatWith(pkg.names, classFileName, '/'); ZipFile zipFile = null; try { zipFile = ((JarPackageFragmentRoot) root).getJar(); info = ClassFileReader.read(zipFile, classFilePath); } finally { JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } } else { // class file in a directory info = Util.newClassFileReader(resource); } if (info == null) throw binaryType.newNotPresentException(); return info; } catch (ClassFormatException e) { //e.printStackTrace(); return null; } catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// 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, 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 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/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/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/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/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 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/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/JarEntryFile.java
public InputStream getContents() throws CoreException { ZipFile zipFile = null; try { zipFile = getZipFile(); if (JavaModelManager.ZIP_ACCESS_VERBOSE) { System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ } String entryName = getEntryName(); ZipEntry zipEntry = zipFile.getEntry(entryName); if (zipEntry == null){ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entryName)); } byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); return new ByteArrayInputStream(contents); } catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } finally { // avoid leaking ZipFiles JavaModelManager.getJavaModelManager().closeZipFile(zipFile); } }
// 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/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/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/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/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/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 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/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 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 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
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/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
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
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/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
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/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/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/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/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 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
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/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/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/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
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 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 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/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 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/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/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/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/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 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 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/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, 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/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/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/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 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, 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 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 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/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/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/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/Initializer.java
public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaModelException { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this)); }
72
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (java.io.IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (CoreException e) { throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in search/org/eclipse/jdt/core/search/SearchEngine.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/MovePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (IOException ioe) { throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException)e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (BadLocationException e) { // content changed under us throw new JavaModelException(e, IJavaModelStatusConstants.INVALID_CONTENTS); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaModelOperation.java
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/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (ClasspathEntry.AssertionFailedException e) { IJavaModelStatus status = new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, e.getMessage()); throw new JavaModelException(status); }
// in model/org/eclipse/jdt/internal/core/JarEntryFile.java
catch (IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFolderChange.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/DeletePackageFragmentRootOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(IllegalArgumentException e){ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (BadLocationException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (CoreException e) { if (e instanceof JavaModelException) { throw (JavaModelException) e; } else { throw new JavaModelException(e); } }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(CoreException e){ throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ExternalFoldersManager.java
catch(CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/Buffer.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
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); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e){ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch(IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/SetContainerOperation.java
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); } }
// in model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
catch (CoreException ce) { throw new JavaModelException(ce); }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/ProjectReferenceChange.java
catch(CoreException e){ if (!ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(this.project.getElementName())) throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (IOException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (CoreException e) { throw new JavaModelException(e); }
// in model/org/eclipse/jdt/internal/core/BatchOperation.java
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/SetVariablesOperation.java
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); } }
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(), "&nbsp;".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 } } }
280
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (JavaModelException e) { // ignore }
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (JavaModelException e) { // copy doesn't exist: ignore }
// in search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
catch (JavaModelException e) { Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$ return new IPath[0]; }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchPattern.java
catch (JavaModelException jme) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchPattern.java
catch (JavaModelException jme) { return; }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (JavaModelException e) { // working copy doesn't exist: cannot happen }
// in search/org/eclipse/jdt/internal/core/search/matching/JavaSearchNameEnvironment.java
catch (JavaModelException e) { // project doesn't exist this.locations = new ClasspathLocation[0]; return; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem collecting super type names: leave it null }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException jme) { // skip }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with classpath in this project -> skip it }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { // problem with classpath in last project -> ignore }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { throw e; }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
catch (JavaModelException e) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/MethodLocator.java
catch (JavaModelException e) { // inaccurate matches will be found }
// in search/org/eclipse/jdt/internal/core/search/matching/PackageReferenceLocator.java
catch(JavaModelException e) { // unable to determine kind; tolerate this match }
// in search/org/eclipse/jdt/internal/core/search/matching/ConstructorPattern.java
catch (JavaModelException e) { // do nothing }
// in search/org/eclipse/jdt/internal/core/search/matching/SuperTypeNamesCollector.java
catch (JavaModelException e) { // ignore: continue with next element }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { // project is not a java project }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
catch(JavaModelException e) { return new IPath[0]; }
// in search/org/eclipse/jdt/internal/core/search/TypeNameMatchRequestorWrapper.java
catch (JavaModelException e) { // skip }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/JavaSearchDocument.java
catch (JavaModelException e) { if (BasicSearchEngine.VERBOSE || JobManager.VERBOSE) { // used during search and during indexing e.printStackTrace(); } return null; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { return false; }
// in search/org/eclipse/jdt/internal/core/search/IndexSelector.java
catch (JavaModelException e) { // ignored }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
catch(JavaModelException e){ // cannot retrieve classpath info }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (JavaModelException npe) { // elt doesn't exist: return the element }
// in model/org/eclipse/jdt/internal/core/ClassFile.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // if type doesn't exist, no matching method can exist return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // default to using the outer most declaring type name IType type = this; IType enclosingType = getDeclaringType(); while (enclosingType != null) { type = enclosingType; enclosingType = type.getDeclaringType(); } return type.getElementName() + Util.defaultJavaExtension(); }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/BinaryType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // root doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // project doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e2) { // project doesn't exist -> ignore continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e1) { // project does not exist -> ignore continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (VERBOSE) { e.printStackTrace(); } return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // java model could not be opened }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external archives"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { if (!e.isDoesNotExist()) Util.log(e, "Exception while updating external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project doesn't exist any longer, continue with next one if (!e.isDoesNotExist()) Util.log(e, "Exception while updating project references"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // a project no longer exists }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch(JavaModelException e) { // project no longer exists }
// in model/org/eclipse/jdt/internal/core/DeltaProcessor.java
catch (JavaModelException e) { // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/CopyPackageFragmentRootOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch(JavaModelException e){ return new JavaModelStatus(e); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) { e.printStackTrace(); } // project no longer exist return result; }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { pkgFragmentRoots = new PackageFragmentRoot[] {}; }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { if (DeltaProcessor.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/ClasspathChange.java
catch (JavaModelException e) { // project doesn't exist return; }
// in model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClassFileInfo.java
catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // working copy doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return false; // the class is not present, do not accept. }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { continue; // the root is not present, continue; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // pkg does not exist // -> try next package }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { continue; // the package fragment root is not present; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException jme) { // give up }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return; // the package is not present }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // package doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // cu doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException e) { // package doesn't exist -> ignore }
// in model/org/eclipse/jdt/internal/core/NameLookup.java
catch (JavaModelException npe) { return false; // the enclosing type is not present }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // an exception occurs, return nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // isStatic == false }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { //nothing to do }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // type is null }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { // type is null }
// in model/org/eclipse/jdt/internal/core/SelectionRequestor.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // ignore }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { // no source can be attached mapper = null; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch(JavaModelException e){ // could not read classpath, then assume it is outside return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ClasspathValidation.java
catch (JavaModelException e) { // project doesn't exist IProject resource = this.project.getProject(); if (resource.isAccessible()) { this.project.flushClasspathProblemMarkers(true/*flush cycle markers*/, true/*flush classpath format markers*/); // remove problems and tasks created by the builder JavaBuilder.removeProblemsAndTasksFor(resource); } return; }
// in model/org/eclipse/jdt/internal/core/JavaModel.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.VERBOSE) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { return e.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // in doubt, there is a conflict return true; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // project doesn't exist: return null }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { Util.log(e, "Could not set classpath variable " + varName + " to " + newPath); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // skip }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // cannot retrieve Java projects }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException jme) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/ClassFileWorkingCopy.java
catch (JavaModelException e) { return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch(JavaModelException e) { return new IProject[0]; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/BinaryField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException jme) { throw jme; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java
catch (JavaModelException e) { // root doesn't exist: consider package has no nonJavaResources this.nonJavaResources = NO_NON_JAVA_RESOURCES; }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch(JavaModelException e) { javadocContents = null; }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (JavaModelException e) { // element doesn't exist: return false }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(JavaModelException jme) { // Proceed with raw classpath }
// in model/org/eclipse/jdt/internal/core/BinaryMember.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
catch (JavaModelException npe) { return; }
// in model/org/eclipse/jdt/internal/core/PackageFragment.java
catch (JavaModelException e) { return e.getStatus(); }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch(JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { // igmore this project }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) { e.printStackTrace(); } return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { if (DEBUG) e.printStackTrace(); return false; }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
catch (JavaModelException e) { // project doesn't exist }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (JavaModelException e) { // cannot happen since element is open return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
catch (JavaModelException e) { // types/cu exist since cu is opened }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // project doesn't exit: ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
catch (JavaModelException e) { return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
catch (JavaModelException e) { // if the focus type is not present, or if cannot get workbench path // we cannot create the hierarchy return; }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { continue; }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
catch (JavaModelException e) { superRefKind = SuperTypeReferencePattern.ALL_SUPER_TYPES; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { // nothing can be done return null; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { // continue with next project continue; }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/DeltaProcessingState.java
catch (JavaModelException e) { return this.javaProjectNamesCache; }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/ModelUpdater.java
catch (JavaModelException e) { // do nothing - we already checked if open }
// in model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/ElementCache.java
catch (JavaModelException npe) { return false; }
// in model/org/eclipse/jdt/internal/core/MultiOperation.java
catch (JavaModelException jme) { if (errorsCounter == errors.length) { // resize System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter); } errors[errorsCounter++] = jme.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // ignore and try to find another project }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // java model is not accessible return null; }
// in model/org/eclipse/jdt/internal/core/util/HandleFactory.java
catch (JavaModelException e) { // JavaModelException from getResolvedClasspath - a problem occurred while accessing project: nothing we can do, ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { // declaring type doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (JavaModelException e) { // does not exist return null; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/util/JavaElementFinder.java
catch (JavaModelException e) { this.exception = e; }
// in model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
catch (JavaModelException e) { // cu doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { isClasspathResolved = false; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // project does not exist: cannot happen since this is the info of the project roots = new IPackageFragmentRoot[0]; reverseMap.clear(); }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // root doesn't exist: ignore return; }
// in model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
catch (JavaModelException e) { // project doesn't exit continue; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java
catch (JavaModelException jme) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMethod.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
catch (JavaModelException e) { // type doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
catch (JavaModelException e) { // receiver doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java
catch (JavaModelException e) { // type parameter does not exist: ignore }
// in model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
catch (JavaModelException npe) { return null; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException npe) { // fall back to using owner }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException jme) { if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) { // in case of package-info.java the type doesn't exist in the model, // but the CU may still help in order to fetch package level annotations. return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction); } // no usable answer }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (JavaModelException e) { // Do nothing }
// in model/org/eclipse/jdt/internal/core/CreateImportOperation.java
catch (JavaModelException e) { // cu doesn't exit: ignore }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return new IPackageFragmentRoot[] {}; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return false; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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
catch (JavaModelException e) { // project doesn't exist: return an empty array }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException jme) { projectOptions = new Hashtable(); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return true; // unsure }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ return false; // not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { return false; // Perhaps, not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ return false; // not a Java project }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // project doesn't exist return null; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { // do nothing }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch(JavaModelException e){ // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // if type doesn't exist, no matching method can exist return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { // exception thrown only when showing parameters return null; }
// in model/org/eclipse/jdt/internal/core/SourceType.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
catch (JavaModelException jme) { return jme.getJavaModelStatus(); }
// in model/org/eclipse/jdt/internal/core/ExternalJavaProject.java
catch (JavaModelException e) { // getPerProjectInfo() never throws JavaModelException for an ExternalJavaProject }
// in model/org/eclipse/jdt/internal/core/Initializer.java
catch (JavaModelException e) { buffer.append("<JavaModelException in toString of " + getElementName()); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelStatus.java
catch(JavaModelException e){ // project doesn't exist: ignore }
// in model/org/eclipse/jdt/internal/core/UserLibraryManager.java
catch (JavaModelException e) { Util.log(e, "Exception while setting user library '"+ libName +"'."); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { return null; }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
catch (JavaModelException e) { // type parameter does not exist: ignore }
// in model/org/eclipse/jdt/internal/compiler/parser/SourceTypeConverter.java
catch (JavaModelException e) { return null; /* } finally { System.out.println("Spent " + (System.currentTimeMillis() - start) + "ms to convert " + ((JavaElement) converter.cu).toStringWithAncestors()); */ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // project no longer exist: ignore continue; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch(JavaModelException jme) { // Creation of external folder project failed. Log it and continue; Util.log(jme, "Error while processing external folders"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // /search failed: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { // refreshing failed: ignore }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (JavaModelException e) { Util.log(e, "Exception while removing variable " + variableName); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/core/CorrectionEngine.java
catch (JavaModelException e) { return; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch(JavaModelException e) { // Do nothing }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
catch (JavaModelException e) { // method doesn't exist: ignore }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceType.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceMethod.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/impl/AssistSourceField.java
catch (JavaModelException e) { // happen only if force open is true return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(JavaModelException e){ parameters = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionProposal.java
catch(JavaModelException e){ parameters = null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (JavaModelException e) { // do nothing }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (JavaModelException e) { return null; }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalExtendedCompletionContext.java
catch (JavaModelException e) { Util.log(e, "Cannot compute enclosing element"); //$NON-NLS-1$ return null; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (JavaModelException e) { return name; }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (JavaModelException e) { return name; }
// in dom/org/eclipse/jdt/core/dom/PackageBinding.java
catch(JavaModelException e) { return AnnotationBinding.NoAnnotations; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { // project doesn't exist -> simple parse without resolving parse(compilationUnits, requestor, apiLevel, options, flags, monitor); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch (JavaModelException e) { flags &= ~ICompilationUnit.ENABLE_BINDINGS_RECOVERY; compilationUnitDeclaration = CompilationUnitResolver.parse( sourceUnit, searcher, this.compilerOptions, flags); needToResolveBindings = false; }
18
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/ReconcileWorkingCopyOperation.java
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) }
// in model/org/eclipse/jdt/internal/core/Openable.java
catch (JavaModelException e) { newElements.remove(this); throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { Util.setSourceAttachmentProperty(getPath(), null); // loose info - will be recomputed throw e; }
// in model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
catch (JavaModelException e) { //problem resolving children; structure remains unknown info.setChildren(new IJavaElement[]{}); throw e; }
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().abortOnMissingSource.get() == Boolean.TRUE) { IOException ioException = e.getJavaModelStatus().getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException)e.getException() : new IOException(e.getMessage()); throw new AbortCompilationUnit(null, ioException, encoding); } else { Util.log(e, Messages.bind(Messages.file_notFound, file.getFullPath().toString())); } return CharOperation.NO_CHAR; }
// in model/org/eclipse/jdt/internal/core/builder/AbstractImageBuilder.java
catch (JavaModelException e) { if (e.getJavaModelStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST) { throw e; } if (!CharOperation.equals(javaElement.getElementName().toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) { throw e; } // else silently swallow the exception as the synthetic interface type package-info has no // source range really. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=258145 }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException jme) { throw jme; }
// in model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
catch (JavaModelException e) { throw e; }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
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
catch (JavaModelException e) { JavaModelManager.getJavaModelManager().getDeltaProcessor().flush(); throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (JavaModelException e) { throw new IllegalArgumentException(element + " does not exist"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
// in dom/org/eclipse/jdt/core/dom/ASTParser.java
catch(JavaModelException e) { // an error occured accessing the java element StringWriter stringWriter = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(stringWriter); e.printStackTrace(writer); } finally { if (writer != null) writer.close(); } throw new IllegalStateException(String.valueOf(stringWriter.getBuffer())); }
5
unknown (Lib) MalformedTreeException 0 0 0 3
            
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (MalformedTreeException e) { e.printStackTrace(); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
2
            
// in model/org/eclipse/jdt/internal/core/CompilationUnit.java
catch (MalformedTreeException e) { throw new JavaModelException(e, IJavaModelStatusConstants.BAD_TEXT_EDIT_LOCATION); }
// in formatter/org/eclipse/jdt/internal/formatter/Scribe.java
catch (MalformedTreeException ex) { // log exception in case of error CommentFormatterUtil.log(ex); throw ex; }
0
unknown (Lib) MalformedURLException 0 0 0 2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, value)); }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (MalformedURLException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC, this)); }
0
unknown (Lib) MissingResourceException 0 0 0 9
            
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch (MissingResourceException e) { return '!' + key + '!'; }
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch (MissingResourceException e) { return '!' + key + '!'; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (MissingResourceException e) { // If we got an exception looking for the message, fail gracefully by just returning // the id we were looking for. In most cases this is semi-informative so is not too bad. return "Missing message: " + id + " in: " + Main.bundleName; //$NON-NLS-2$ //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { result[i] = name[i]; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (MissingResourceException e) { // available ID }
4
            
// in antadapter/org/eclipse/jdt/internal/antadapter/AntAdapterMessages.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + BUNDLE_NAME.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + Main.bundleName.replace('.', '/') + ".properties for locale " + locale); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(MissingResourceException e) { System.out.println("Missing resource : " + bundleName.replace('.', '/') + ".properties for locale " + loc); //$NON-NLS-1$//$NON-NLS-2$ throw e; }
0
runtime (Domain) MissingSourceFileException
public class MissingSourceFileException extends RuntimeException {

	protected String missingSourceFile;
	private static final long serialVersionUID = -1416609004971115719L; // backward compatible

public MissingSourceFileException(String missingSourceFile) {
	this.missingSourceFile = missingSourceFile;
}
}
0 0
            
// in model/org/eclipse/jdt/internal/core/builder/SourceFile.java
catch (CoreException e) { throw new AbortCompilation(true, new MissingSourceFileException(this.resource.getFullPath().toString())); }
0 1
            
// in model/org/eclipse/jdt/internal/core/builder/JavaBuilder.java
catch (MissingSourceFileException e) { // do not log this exception since its thrown to handle aborted compiles because of missing source files if (DEBUG) System.out.println(Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile)); removeProblemsAndTasksFor(this.currentProject); // make this the only problem for this project IMarker marker = this.currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER); marker.setAttributes( new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.SOURCE_ID}, new Object[] { Messages.bind(Messages.build_missingSourceFile, e.missingSourceFile), new Integer(IMarker.SEVERITY_ERROR), JavaBuilder.SOURCE_ID } ); }
0 0
unknown (Lib) NegativeArraySizeException 0 0 0 2
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
2
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/ConstructorDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
// in compiler/org/eclipse/jdt/internal/compiler/ast/AbstractMethodDeclaration.java
catch(NegativeArraySizeException e) { throw new AbortMethod(this.scope.referenceCompilationUnit().compilationResult, null); }
2
unknown (Lib) NoSuchMethodException 0 0 0 6
            
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch(NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x }
// in antadapter/org/eclipse/jdt/core/JDTCompilerAdapter.java
catch (NoSuchMethodException e) { // if not found, then we cannot use this method (ant 1.5) // debug level is only available with ant 1.5.x }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (NoSuchMethodException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (NoSuchMethodException e) { // ignored }
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
            
// in dom/org/eclipse/jdt/core/dom/AST.java
catch (NoSuchMethodException e) { // all AST node classes have a Foo(AST) constructor // therefore nodeClass is not legit throw new IllegalArgumentException(); }
1
runtime (Lib) NullPointerException 1
            
// in dom/org/eclipse/jdt/core/dom/CompilationUnit.java
void setLineEndTable(int[] lineEndTable) { if (lineEndTable == null) { throw new NullPointerException(); } // alternate root is *not* considered a structural property // but we protect them nevertheless checkModifiable(); this.lineEndTable = lineEndTable; }
0 0 2
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (NullPointerException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316 return null; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/ScannerHelper.java
catch (NullPointerException e) { return false; }
0 0
unknown (Lib) NumberFormatException 9
            
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
private int extractInt(char[] array, int start, int end) { int value = 0; for (int i = start; i < end; i++) { final char currentChar = array[i]; int digit = 0; switch(currentChar) { case '0' : digit = 0; break; case '1' : digit = 1; break; case '2' : digit = 2; break; case '3' : digit = 3; break; case '4' : digit = 4; break; case '5' : digit = 5; break; case '6' : digit = 6; break; case '7' : digit = 7; break; case '8' : digit = 8; break; case '9' : digit = 9; break; default : throw new NumberFormatException(); } value *= 10; if (digit < 0) throw new NumberFormatException(); value += digit; } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
private int extractInt(char[] array, int start, int end) { int value = 0; for (int i = start; i < end; i++) { final char currentChar = array[i]; int digit = 0; switch(currentChar) { case '0' : digit = 0; break; case '1' : digit = 1; break; case '2' : digit = 2; break; case '3' : digit = 3; break; case '4' : digit = 4; break; case '5' : digit = 5; break; case '6' : digit = 6; break; case '7' : digit = 7; break; case '8' : digit = 8; break; case '9' : digit = 9; break; default : throw new NumberFormatException(); } value *= 10; if (digit < 0) throw new NumberFormatException(); value += digit; } return value; }
// in compiler/org/eclipse/jdt/internal/compiler/util/FloatUtil.java
private static long convertHexFloatingPointLiteralToBits(char[] source) { int length = source.length; long mantissa = 0; // Step 1: process the '0x' lead-in int next = 0; char nextChar = source[next]; nextChar = source[next]; if (nextChar == '0') { next++; } else { throw new NumberFormatException(); } nextChar = source[next]; if (nextChar == 'X' || nextChar == 'x') { next++; } else { throw new NumberFormatException(); } // Step 2: process leading '0's either before or after the '.' int binaryPointPosition = -1; loop: while (true) { nextChar = source[next]; switch (nextChar) { case '0': next++; continue loop; case '.': binaryPointPosition = next; next++; continue loop; default: break loop; } } // Step 3: process the mantissa // leading zeros have been trimmed int mantissaBits = 0; int leadingDigitPosition = -1; loop: while (true) { nextChar = source[next]; int hexdigit; switch (nextChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': hexdigit = nextChar - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': hexdigit = (nextChar - 'a') + 10; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': hexdigit = (nextChar - 'A') + 10; break; case '.': binaryPointPosition = next; next++; continue loop; default: if (binaryPointPosition < 0) { // record virtual '.' as being to right of all digits binaryPointPosition = next; } break loop; } if (mantissaBits == 0) { // this is the first non-zero hex digit // ignore leading binary 0's in hex digit leadingDigitPosition = next; mantissa = hexdigit; mantissaBits = 4; } else if (mantissaBits < 60) { // middle hex digits mantissa <<= 4; mantissa |= hexdigit; mantissaBits += 4; } else { // more mantissa bits than we can handle // drop this hex digit on the ground } next++; continue loop; } // Step 4: process the 'P' nextChar = source[next]; if (nextChar == 'P' || nextChar == 'p') { next++; } else { throw new NumberFormatException(); } // Step 5: process the exponent int exponent = 0; int exponentSign = +1; loop: while (next < length) { nextChar = source[next]; switch (nextChar) { case '+': exponentSign = +1; next++; continue loop; case '-': exponentSign = -1; next++; continue loop; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': int digit = nextChar - '0'; exponent = (exponent * 10) + digit; next++; continue loop; default: break loop; } } // Step 6: process the optional 'f' or 'd' boolean doublePrecision = true; if (next < length) { nextChar = source[next]; switch (nextChar) { case 'f': case 'F': doublePrecision = false; next++; break; case 'd': case 'D': doublePrecision = true; next++; break; default: throw new NumberFormatException(); } } // at this point, all the parsing is done // Step 7: handle mantissa of zero if (mantissa == 0) { return 0L; } // Step 8: normalize non-zero mantissa // mantissa is in right-hand mantissaBits // ensure that top bit (as opposed to hex digit) is 1 int scaleFactorCompensation = 0; long top = (mantissa >>> (mantissaBits - 4)); if ((top & 0x8) == 0) { mantissaBits--; scaleFactorCompensation++; if ((top & 0x4) == 0) { mantissaBits--; scaleFactorCompensation++; if ((top & 0x2) == 0) { mantissaBits--; scaleFactorCompensation++; } } } // Step 9: convert double literals to IEEE double long result = 0L; if (doublePrecision) { long fraction; if (mantissaBits > DOUBLE_PRECISION) { // more bits than we can keep int extraBits = mantissaBits - DOUBLE_PRECISION; // round to DOUBLE_PRECISION bits fraction = mantissa >>> (extraBits - 1); long lowBit = fraction & 0x1; fraction += lowBit; fraction = fraction >>> 1; if ((fraction & (1L << DOUBLE_PRECISION)) != 0) { fraction = fraction >>> 1; scaleFactorCompensation -= 1; } } else { // less bits than the faction can hold - pad on right with 0s fraction = mantissa << (DOUBLE_PRECISION - mantissaBits); } int scaleFactor = 0; // how many bits to move '.' to before leading hex digit if (mantissaBits > 0) { if (leadingDigitPosition < binaryPointPosition) { // e.g., 0x80.0p0 has scaleFactor == +8 scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition); // e.g., 0x10.0p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } else { // e.g., 0x0.08p0 has scaleFactor == -4 scaleFactor = -4 * (leadingDigitPosition - binaryPointPosition - 1); // e.g., 0x0.01p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } } int e = (exponentSign * exponent) + scaleFactor; if (e - 1 > MAX_DOUBLE_EXPONENT) { // overflow to +infinity result = Double.doubleToLongBits(Double.POSITIVE_INFINITY); } else if (e - 1 >= MIN_NORMALIZED_DOUBLE_EXPONENT) { // can be represented as a normalized double // the left most bit must be discarded (it's always a 1) long biasedExponent = e - 1 + DOUBLE_EXPONENT_BIAS; result = fraction & ~(1L << DOUBLE_FRACTION_WIDTH); result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT); } else if (e - 1 > MIN_UNNORMALIZED_DOUBLE_EXPONENT) { // can be represented as an unnormalized double long biasedExponent = 0; result = fraction >>> (MIN_NORMALIZED_DOUBLE_EXPONENT - e + 1); result |= (biasedExponent << DOUBLE_EXPONENT_SHIFT); } else { // underflow - return Double.NaN result = Double.doubleToLongBits(Double.NaN); } return result; } // Step 10: convert float literals to IEEE single long fraction; if (mantissaBits > SINGLE_PRECISION) { // more bits than we can keep int extraBits = mantissaBits - SINGLE_PRECISION; // round to DOUBLE_PRECISION bits fraction = mantissa >>> (extraBits - 1); long lowBit = fraction & 0x1; fraction += lowBit; fraction = fraction >>> 1; if ((fraction & (1L << SINGLE_PRECISION)) != 0) { fraction = fraction >>> 1; scaleFactorCompensation -= 1; } } else { // less bits than the faction can hold - pad on right with 0s fraction = mantissa << (SINGLE_PRECISION - mantissaBits); } int scaleFactor = 0; // how many bits to move '.' to before leading hex digit if (mantissaBits > 0) { if (leadingDigitPosition < binaryPointPosition) { // e.g., 0x80.0p0 has scaleFactor == +8 scaleFactor = 4 * (binaryPointPosition - leadingDigitPosition); // e.g., 0x10.0p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } else { // e.g., 0x0.08p0 has scaleFactor == -4 scaleFactor = -4 * (leadingDigitPosition - binaryPointPosition - 1); // e.g., 0x0.01p0 has scaleFactorCompensation == +3 scaleFactor -= scaleFactorCompensation; } } int e = (exponentSign * exponent) + scaleFactor; if (e - 1 > MAX_SINGLE_EXPONENT) { // overflow to +infinity result = Float.floatToIntBits(Float.POSITIVE_INFINITY); } else if (e - 1 >= MIN_NORMALIZED_SINGLE_EXPONENT) { // can be represented as a normalized single // the left most bit must be discarded (it's always a 1) long biasedExponent = e - 1 + SINGLE_EXPONENT_BIAS; result = fraction & ~(1L << SINGLE_FRACTION_WIDTH); result |= (biasedExponent << SINGLE_EXPONENT_SHIFT); } else if (e - 1 > MIN_UNNORMALIZED_SINGLE_EXPONENT) { // can be represented as an unnormalized single long biasedExponent = 0; result = fraction >>> (MIN_NORMALIZED_SINGLE_EXPONENT - e + 1); result |= (biasedExponent << SINGLE_EXPONENT_SHIFT); } else { // underflow - return Float.NaN result = Float.floatToIntBits(Float.NaN); } return result; }
// in compiler/org/eclipse/jdt/core/compiler/CharOperation.java
public static final int parseInt(char[] array, int start, int length) throws NumberFormatException { if (length == 1) { int result = array[start] - '0'; if (result < 0 || result > 9) { throw new NumberFormatException("invalid digit"); //$NON-NLS-1$ } return result; } else { return Integer.parseInt(new String(array, start, length)); } }
0 1
            
// in compiler/org/eclipse/jdt/core/compiler/CharOperation.java
public static final int parseInt(char[] array, int start, int length) throws NumberFormatException { if (length == 1) { int result = array[start] - '0'; if (result < 0 || result > 9) { throw new NumberFormatException("invalid digit"); //$NON-NLS-1$ } return result; } else { return Integer.parseInt(new String(array, start, length)); } }
69
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { // by default we don't support a class file version we cannot recognize return false; }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/BinaryMethod.java
catch(NumberFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/SourceMapper.java
catch(NumberFormatException e) { // ignore }
// in model/org/eclipse/jdt/internal/core/util/Util.java
catch (NumberFormatException e) { return null; }
// in model/org/eclipse/jdt/internal/core/util/PublicScanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
// in model/org/eclipse/jdt/internal/core/SourceField.java
catch (NumberFormatException e) { // not a parsable constant return null; }
// in model/org/eclipse/jdt/internal/core/JavaModelCache.java
catch (NumberFormatException e) { // ignore Util.log(e, "Could not parse value for " + RATIO_PROPERTY + ": " + property); //$NON-NLS-1$ //$NON-NLS-2$ }
// in formatter/org/eclipse/jdt/internal/formatter/comment/HTMLEntity2JavaReader.java
catch (NumberFormatException e) { // ignore }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_annotation = Alignment.M_NO_ALIGNMENT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_enum_constant = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_explicit_constructor_call = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_arguments_in_qualified_allocation_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_assignment = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_binary_expression = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_compact_if = Alignment.M_ONE_PER_LINE_SPLIT | Alignment.M_INDENT_BY_ONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_conditional_expression = Alignment.M_ONE_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_enum_constants = Alignment.NONE; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_expressions_in_array_initializer = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_multiple_fields = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_parameters_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_parameters_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_resources_in_try = Alignment.M_NEXT_PER_LINE_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_selector_in_method_invocation = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superclass_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superinterfaces_in_enum_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_superinterfaces_in_type_declaration = Alignment.M_NEXT_SHIFTED_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_throws_clause_in_constructor_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_throws_clause_in_method_declaration = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.alignment_for_union_type_in_multicatch = Alignment.M_COMPACT_SPLIT; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.continuation_indentation = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.continuation_indentation_for_array_initializer = 2; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_after_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_after_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_field = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_first_class_body_declaration = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_imports = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_member_type = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_method = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_new_chunk = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_before_package = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_between_import_groups = 1; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_between_type_declarations = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.blank_lines_at_beginning_of_method_body = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.comment_line_length = 80; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.indentation_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.number_of_empty_lines_to_preserve = 0; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.tab_size = 4; }
// in formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java
catch (NumberFormatException e) { this.page_width = 80; }
// in formatter/org/eclipse/jdt/core/formatter/IndentManipulation.java
catch (NumberFormatException e) { return def; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in compiler/org/eclipse/jdt/internal/compiler/parser/Scanner.java
catch (NumberFormatException e) { currentTag = new NLSTag(pos + sourceDelta, end + sourceDelta, currentLine, -1); }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch (NumberFormatException nfe) { output.append(message, end + 1, start - end); }
// in compiler/org/eclipse/jdt/internal/compiler/problem/DefaultProblemFactory.java
catch(NumberFormatException e) { // key ill-formed }
// in compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
catch(NumberFormatException e){ // ignore ill-formatted limit }
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Float.valueOf(...) doesn't handle hex decimal floats try { float v = FloatUtil.valueOfHexFloatLiteral(this.source); if (v == Float.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Float.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = FloatConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/FloatLiteral.java
catch (NumberFormatException e1) { // if the computation of the constant fails }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e) { // hex floating point literal // being rejected by 1.4 libraries where Double.valueOf(...) doesn't handle hex decimal floats try { double v = FloatUtil.valueOfHexDoubleLiteral(this.source); if (v == Double.POSITIVE_INFINITY) { // error: the number is too large to represent return; } if (Double.isNaN(v)) { // error: the number is too small to represent return; } this.value = v; this.constant = DoubleConstant.fromValue(v); } catch (NumberFormatException e1) { // if the computation of the constant fails } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ast/DoubleLiteral.java
catch (NumberFormatException e1) { // if the computation of the constant fails }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/ImportRewriteAnalyzer.java
catch (NumberFormatException e) { // fall through }
8
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.repetition", currentArg)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (NumberFormatException e) { throw new IllegalArgumentException(this.bind("configure.maxProblems", currentArg)); //$NON-NLS-1$ }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
// in formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java
catch (NumberFormatException e) { throw WRONG_ARGUMENT; }
2
unknown (Lib) OperationCanceledException 49
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { if (VERBOSE) { Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$ Util.verbose(scope.toString()); } if (participants == null) { if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$ return; } /* initialize progress monitor */ int length = participants.length; if (monitor != null) monitor.beginTask(Messages.engine_searching, 100 * length); IndexManager indexManager = JavaModelManager.getIndexManager(); requestor.beginReporting(); for (int i = 0; i < length; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); SearchParticipant participant = participants[i]; try { if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()})); participant.beginSearching(); requestor.enterParticipant(participant); PathCollector pathCollector = new PathCollector(); indexManager.performConcurrentJob( new PatternSearchJob(pattern, participant, scope, pathCollector), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor==null ? null : new SubProgressMonitor(monitor, 50)); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // locate index matches if any (note that all search matches could have been issued during index querying) if (monitor != null) monitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()})); String[] indexMatchPaths = pathCollector.getPaths(); if (indexMatchPaths != null) { pathCollector = null; // release int indexMatchLength = indexMatchPaths.length; SearchDocument[] indexMatches = new SearchDocument[indexMatchLength]; for (int j = 0; j < indexMatchLength; j++) { indexMatches[j] = participant.getDocument(indexMatchPaths[j]); } SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant); participant.locateMatches(matches, pattern, scope, requestor, monitor==null ? null : new SubProgressMonitor(monitor, 50)); } } finally { requestor.exitParticipant(participant); participant.doneSearching(); } } } finally { requestor.endReporting(); if (monitor != null) monitor.done(); } }
// 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 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/JavaSearchParticipant.java
public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { MatchLocator matchLocator = new MatchLocator( pattern, requestor, scope, monitor ); /* eliminating false matches and locating them */ if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); matchLocator.locateMatches(indexMatches); }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMatches, int start, int length) throws CoreException { initialize(javaProject, length); // create and resolve binding (equivalent to beginCompilation() in Compiler) boolean mustResolvePattern = this.pattern.mustResolve; boolean mustResolve = mustResolvePattern; this.patternLocator.mayBeGeneric = this.options.sourceLevel >= ClassFileConstants.JDK1_5; boolean bindingsWereCreated = mustResolve; try { for (int i = start, maxUnits = start + length; i < maxUnits; i++) { PossibleMatch possibleMatch = possibleMatches[i]; try { if (!parseAndBuildBindings(possibleMatch, mustResolvePattern)) continue; // Currently we only need to resolve over pattern flag if there's potential parameterized types if (this.patternLocator.mayBeGeneric) { // If pattern does not resolve then rely on possible match node set resolution // which may have been modified while locator was adding possible matches to it if (!mustResolvePattern && !mustResolve) { mustResolve = possibleMatch.nodeSet.mustResolve; bindingsWereCreated = mustResolve; } } else { // Reset matching node resolution with pattern one if there's no potential parameterized type // to minimize side effect on previous search behavior possibleMatch.nodeSet.mustResolve = mustResolvePattern; } // possible match node resolution has been merged with pattern one, so rely on it to know // whether we need to process compilation unit now or later if (!possibleMatch.nodeSet.mustResolve) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } process(possibleMatch, bindingsWereCreated); if (this.numberOfMatches>0 && this.matchesToProcess[this.numberOfMatches-1] == possibleMatch) { // forget last possible match as it was processed this.numberOfMatches--; } } } finally { if (possibleMatch.hasSimilarMatch()) { // If there is similar match, then also process it // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=211872 possibleMatches[i] = possibleMatch.getSimilarMatch(); i--; } if (!possibleMatch.nodeSet.mustResolve) possibleMatch.cleanUp(); } } if (mustResolve) this.lookupEnvironment.completeTypeBindings(); // create hierarchy resolver if needed IType focusType = getFocusType(); if (focusType == null) { this.hierarchyResolver = null; } else if (!createHierarchyResolver(focusType, possibleMatches)) { // focus type is not visible, use the super type names instead of the bindings if (computeSuperTypeNames(focusType) == null) return; } } catch (AbortCompilation e) { bindingsWereCreated = false; } if (!mustResolve) { return; } // possible match resolution for (int i = 0; i < this.numberOfMatches; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); PossibleMatch possibleMatch = this.matchesToProcess[i]; this.matchesToProcess[i] = null; // release reference to processed possible match try { process(possibleMatch, bindingsWereCreated); } catch (AbortCompilation e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } catch (JavaModelException e) { // problem with class path: it could not find base classes // continue and try next matching openable reporting innacurate matches (since bindings will be null) bindingsWereCreated = false; } finally { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } if (this.options.verbose) System.out.println( Messages.bind(Messages.compilation_done, new String[] { String.valueOf(i + 1), String.valueOf(this.numberOfMatches), new String(possibleMatch.parsedUnit.getFileName()) })); // cleanup compilation unit result possibleMatch.cleanUp(); } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
public void locateMatches(SearchDocument[] searchDocuments) throws CoreException { if (this.patternLocator == null) return; int docsLength = searchDocuments.length; int progressLength = docsLength; if (BasicSearchEngine.VERBOSE) { System.out.println("Locating matches in documents ["); //$NON-NLS-1$ for (int i = 0; i < docsLength; i++) System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$ System.out.println("]"); //$NON-NLS-1$ } IJavaProject[] javaModelProjects = null; if (this.searchPackageDeclaration) { javaModelProjects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects(); progressLength += javaModelProjects.length; } // init infos for progress increasing int n = progressLength<1000 ? Math.min(Math.max(progressLength/200+1, 2),4) : 5 *(progressLength/1000); this.progressStep = progressLength < n ? 1 : progressLength / n; // step should not be 0 this.progressWorked = 0; // extract working copies ArrayList copies = new ArrayList(); for (int i = 0; i < docsLength; i++) { SearchDocument document = searchDocuments[i]; if (document instanceof WorkingCopyDocument) { copies.add(((WorkingCopyDocument)document).workingCopy); } } int copiesLength = copies.size(); this.workingCopies = new org.eclipse.jdt.core.ICompilationUnit[copiesLength]; copies.toArray(this.workingCopies); JavaModelManager manager = JavaModelManager.getJavaModelManager(); this.bindings = new SimpleLookupTable(); try { // optimize access to zip files during search operation manager.cacheZipFiles(this); // initialize handle factory (used as a cache of handles so as to optimize space) if (this.handleFactory == null) this.handleFactory = new HandleFactory(); if (this.progressMonitor != null) { this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$ } // initialize pattern for polymorphic search (i.e. method reference pattern) this.patternLocator.initializePolymorphicSearch(this); JavaProject previousJavaProject = null; PossibleMatchSet matchSet = new PossibleMatchSet(); Util.sort(searchDocuments, new Util.Comparer() { public int compare(Object a, Object b) { return ((SearchDocument)a).getPath().compareTo(((SearchDocument)b).getPath()); } }); int displayed = 0; // progress worked displayed String previousPath = null; SearchParticipant searchParticipant = null; for (int i = 0; i < docsLength; i++) { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // skip duplicate paths SearchDocument searchDocument = searchDocuments[i]; if (searchParticipant == null) { searchParticipant = searchDocument.getParticipant(); } searchDocuments[i] = null; // free current document String pathString = searchDocument.getPath(); if (i > 0 && pathString.equals(previousPath)) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; } previousPath = pathString; Openable openable; org.eclipse.jdt.core.ICompilationUnit workingCopy = null; if (searchDocument instanceof WorkingCopyDocument) { workingCopy = ((WorkingCopyDocument)searchDocument).workingCopy; openable = (Openable) workingCopy; } else { openable = this.handleFactory.createOpenable(pathString, this.scope); } if (openable == null) { if (this.progressMonitor != null) { this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } displayed++; continue; // match is outside classpath } // create new parser and lookup environment if this is a new project IResource resource = null; JavaProject javaProject = (JavaProject) openable.getJavaProject(); resource = workingCopy != null ? workingCopy.getResource() : openable.getResource(); if (resource == null) resource = javaProject.getProject(); // case of a file in an external jar or external folder if (!javaProject.equals(previousJavaProject)) { // locate matches in previous project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, i-displayed); displayed = i; } catch (JavaModelException e) { // problem with classpath in this project -> skip it } matchSet.reset(); } previousJavaProject = javaProject; } matchSet.add(new PossibleMatch(this, resource, openable, searchDocument,this.pattern.mustResolve)); } // last project if (previousJavaProject != null) { try { locateMatches(previousJavaProject, matchSet, docsLength-displayed); } catch (JavaModelException e) { // problem with classpath in last project -> ignore } } if (this.searchPackageDeclaration) { locatePackageDeclarations(searchParticipant, javaModelProjects); } } finally { if (this.progressMonitor != null) this.progressMonitor.done(); if (this.nameEnvironment != null) this.nameEnvironment.cleanup(); manager.flushZipFiles(this); this.bindings = null; } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected void locatePackageDeclarations(SearchPattern searchPattern, SearchParticipant participant, IJavaProject[] projects) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } if (searchPattern instanceof OrPattern) { SearchPattern[] patterns = ((OrPattern) searchPattern).patterns; for (int i = 0, length = patterns.length; i < length; i++) { locatePackageDeclarations(patterns[i], participant, projects); } } else if (searchPattern instanceof PackageDeclarationPattern) { IJavaElement focus = searchPattern.focus; if (focus != null) { if (encloses(focus)) { SearchMatch match = new PackageDeclarationMatch(focus.getAncestor(IJavaElement.PACKAGE_FRAGMENT), SearchMatch.A_ACCURATE, -1, -1, participant, focus.getResource()); report(match); } return; } PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern) searchPattern; boolean isWorkspaceScope = this.scope == JavaModelManager.getJavaModelManager().getWorkspaceScope(); IPath[] scopeProjectsAndJars = isWorkspaceScope ? null : this.scope.enclosingProjectsAndJars(); int scopeLength = isWorkspaceScope ? 0 : scopeProjectsAndJars.length; SimpleSet packages = new SimpleSet(); for (int i = 0, length = projects.length; i < length; i++) { IJavaProject javaProject = projects[i]; if (this.progressMonitor != null) { if (this.progressMonitor.isCanceled()) throw new OperationCanceledException(); this.progressWorked++; if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep); } // Verify that project belongs to the scope if (!isWorkspaceScope) { boolean found = false; for (int j=0; j<scopeLength; j++) { if (javaProject.getPath().equals(scopeProjectsAndJars[j])) { found = true; break; } } if (!found) continue; } // Get all project package fragment names this.nameLookup = ((JavaProject) projects[i]).newNameLookup(this.workingCopies); IPackageFragment[] packageFragments = this.nameLookup.findPackageFragments(new String(pkgPattern.pkgName), false, true); int pLength = packageFragments == null ? 0 : packageFragments.length; // Report matches avoiding duplicate names for (int p=0; p<pLength; p++) { IPackageFragment fragment = packageFragments[p]; if (packages.addIfNotIncluded(fragment) == null) continue; if (encloses(fragment)) { IResource resource = fragment.getResource(); if (resource == null) // case of a file in an external jar resource = javaProject.getProject(); try { if (encloses(fragment)) { SearchMatch match = new PackageDeclarationMatch(fragment, SearchMatch.A_ACCURATE, -1, -1, participant, resource); report(match); } } catch (JavaModelException e) { throw e; } catch (CoreException e) { throw new JavaModelException(e); } } } } } }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
protected boolean parseAndBuildBindings(PossibleMatch possibleMatch, boolean mustResolve) throws CoreException { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); try { if (BasicSearchEngine.VERBOSE) System.out.println("Parsing " + possibleMatch.openable.toStringWithAncestors()); //$NON-NLS-1$ this.parser.nodeSet = possibleMatch.nodeSet; CompilationResult unitResult = new CompilationResult(possibleMatch, 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = this.parser.dietParse(possibleMatch, unitResult); if (parsedUnit != null) { if (!parsedUnit.isEmpty()) { if (mustResolve) { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } if (hasAlreadyDefinedType(parsedUnit)) return false; // skip type has it is hidden so not visible getMethodBodies(parsedUnit, possibleMatch.nodeSet); if (this.patternLocator.mayBeGeneric && !mustResolve && possibleMatch.nodeSet.mustResolve) { // special case: possible match node set force resolution although pattern does not // => we need to build types for this compilation unit this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); } } // add the possibleMatch with its parsedUnit to matchesToProcess possibleMatch.parsedUnit = parsedUnit; int size = this.matchesToProcess.length; if (this.numberOfMatches == size) System.arraycopy(this.matchesToProcess, 0, this.matchesToProcess = new PossibleMatch[size == 0 ? 1 : size * 2], 0, this.numberOfMatches); this.matchesToProcess[this.numberOfMatches++] = possibleMatch; } } finally { this.parser.nodeSet = null; } return true; }
// in search/org/eclipse/jdt/internal/core/search/matching/LocalVariablePattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) { IPackageFragmentRoot root = (IPackageFragmentRoot)this.localVariable.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); String documentPath; String relativePath; if (root.isArchive()) { IType type = (IType)this.localVariable.getAncestor(IJavaElement.TYPE); relativePath = (type.getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class; documentPath = root.getPath() + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath; } else { IPath path = this.localVariable.getPath(); documentPath = path.toString(); relativePath = Util.relativePath(path, 1/*remove project segment*/); } if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path if (!requestor.acceptIndexMatch(documentPath, this, participant, access)) throw new OperationCanceledException(); } } else if (scope.encloses(documentPath)) { if (!requestor.acceptIndexMatch(documentPath, this, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/TypeParameterPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) { IPackageFragmentRoot root = (IPackageFragmentRoot) this.typeParameter.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); String documentPath; String relativePath; if (root.isArchive()) { IType type = (IType) this.typeParameter.getAncestor(IJavaElement.TYPE); relativePath = (type.getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class; documentPath = root.getPath() + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + relativePath; } else { IPath path = this.typeParameter.getPath(); documentPath = path.toString(); relativePath = Util.relativePath(path, 1/*remove project segment*/); } if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, index.containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the path if (!requestor.acceptIndexMatch(documentPath, this, participant, access)) throw new OperationCanceledException(); } } else if (scope.encloses(documentPath)) { if (!requestor.acceptIndexMatch(documentPath, this, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/internal/core/search/matching/IntersectingPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor progressMonitor) throws IOException { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); resetQuery(); SimpleSet intersectedNames = null; try { index.startQuery(); do { SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); SimpleSet newIntersectedNames = new SimpleSet(3); for (int i = 0, l = entries.length; i < l; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { String[] names = entry.getDocumentNames(index); if (intersectedNames != null) { for (int j = 0, n = names.length; j < n; j++) if (intersectedNames.includes(names[j])) newIntersectedNames.add(names[j]); } else { for (int j = 0, n = names.length; j < n; j++) newIntersectedNames.add(names[j]); } } } if (newIntersectedNames.elementSize == 0) return; intersectedNames = newIntersectedNames; } while (hasNextQuery()); } finally { index.stopQuery(); } String containerPath = index.containerPath; char separator = index.separator; Object[] names = intersectedNames.values; for (int i = 0, l = names.length; i < l; i++) if (names[i] != null) acceptMatch((String) names[i], containerPath, separator, null/*no pattern*/, requestor, participant, scope, progressMonitor); // AndPatterns cannot provide the decoded result }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
public boolean performConcurrentJob(IJob searchJob, int waitingPolicy, IProgressMonitor progress) { if (VERBOSE) Util.verbose("STARTING concurrent job - " + searchJob); //$NON-NLS-1$ searchJob.ensureReadyToRun(); boolean status = IJob.FAILED; try { int concurrentJobWork = 100; if (progress != null) progress.beginTask("", concurrentJobWork); //$NON-NLS-1$ if (awaitingJobsCount() > 0) { switch (waitingPolicy) { case IJob.ForceImmediate : if (VERBOSE) Util.verbose("-> NOT READY - forcing immediate - " + searchJob);//$NON-NLS-1$ try { disable(); // pause indexing status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); } finally { enable(); } if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ return status; case IJob.CancelIfNotReady : if (VERBOSE) Util.verbose("-> NOT READY - cancelling - " + searchJob); //$NON-NLS-1$ if (VERBOSE) Util.verbose("CANCELED concurrent job - " + searchJob); //$NON-NLS-1$ throw new OperationCanceledException(); case IJob.WaitUntilReady : IProgressMonitor subProgress = null; try { int totalWork = 1000; if (progress != null) { subProgress = new SubProgressMonitor(progress, concurrentJobWork * 8 / 10); subProgress.beginTask("", totalWork); //$NON-NLS-1$ concurrentJobWork = concurrentJobWork * 2 / 10; } // use local variable to avoid potential NPE (see bug 20435 NPE when searching java method // and bug 42760 NullPointerException in JobManager when searching) Thread t = this.processingThread; int originalPriority = t == null ? -1 : t.getPriority(); try { if (t != null) t.setPriority(Thread.currentThread().getPriority()); synchronized(this) { this.awaitingClients++; } IJob previousJob = null; int awaitingJobsCount; int lastJobsCount = totalWork; float lastWorked = 0; float totalWorked = 0; while ((awaitingJobsCount = awaitingJobsCount()) > 0) { if ((subProgress != null && subProgress.isCanceled()) || this.processingThread == null) throw new OperationCanceledException(); IJob currentJob = currentJob(); // currentJob can be null when jobs have been added to the queue but job manager is not enabled if (currentJob != null && currentJob != previousJob) { if (VERBOSE) Util.verbose("-> NOT READY - waiting until ready - " + searchJob);//$NON-NLS-1$ if (subProgress != null) { String indexing = Messages.bind(Messages.jobmanager_filesToIndex, currentJob.getJobFamily(), Integer.toString(awaitingJobsCount)); subProgress.subTask(indexing); // ratio of the amount of work relative to the total work float ratio = awaitingJobsCount < totalWork ? 1 : ((float) totalWork) / awaitingJobsCount; if (lastJobsCount > awaitingJobsCount) { totalWorked += (lastJobsCount - awaitingJobsCount) * ratio; } else { // more jobs were added, just increment by the ratio totalWorked += ratio; } if (totalWorked - lastWorked >= 1) { subProgress.worked((int) (totalWorked - lastWorked)); lastWorked = totalWorked; } lastJobsCount = awaitingJobsCount; } previousJob = currentJob; } try { if (VERBOSE) Util.verbose("-> GOING TO SLEEP - " + searchJob);//$NON-NLS-1$ Thread.sleep(50); } catch (InterruptedException e) { // ignore } } } finally { synchronized(this) { this.awaitingClients--; } if (t != null && originalPriority > -1 && t.isAlive()) t.setPriority(originalPriority); } } finally { if (subProgress != null) subProgress.done(); } } } status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); } finally { if (progress != null) progress.done(); if (VERBOSE) Util.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ } return status; }
// in search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
public Index[] getIndexes(IPath[] locations, IProgressMonitor progressMonitor) { // acquire the in-memory indexes on the fly int length = locations.length; Index[] locatedIndexes = new Index[length]; int count = 0; if (this.javaLikeNamesChanged) { this.javaLikeNamesChanged = hasJavaLikeNamesChanged(); } for (int i = 0; i < length; i++) { if (progressMonitor != null && progressMonitor.isCanceled()) { throw new OperationCanceledException(); } // may trigger some index recreation work IPath indexLocation = locations[i]; Index index = getIndex(indexLocation); if (index == null) { // only need containerPath if the index must be built IPath containerPath = (IPath) this.indexLocations.keyForValue(indexLocation); if (containerPath != null) {// sanity check index = getIndex(containerPath, indexLocation, true /*reuse index file*/, false /*do not create if none*/); if (index != null && this.javaLikeNamesChanged && !index.isIndexForJar()) { // When a change in java like names extension has been detected, all // non jar files indexes (i.e. containing sources) need to be rebuilt. // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=286379 File indexFile = index.getIndexFile(); if (indexFile.exists()) { if (DEBUG) Util.verbose("Change in javaLikeNames - removing index file for " + containerPath ); //$NON-NLS-1$ indexFile.delete(); } this.indexes.put(indexLocation, null); rebuildIndex(indexLocation, containerPath); index = null; } } else { if (!getJavaPluginWorkingLocation().isPrefixOf(indexLocation)) { // the index belongs to non-jdt search participant if (indexLocation.toFile().exists()) { try { IPath container = getParticipantsContainer(indexLocation); if (container != null) { index = new Index(indexLocation.toOSString(), container.toOSString(), true /*reuse index file*/); this.indexes.put(indexLocation, index); } } catch (IOException e) { // ignore } } } } } if (index != null) locatedIndexes[count++] = index; // only consider indexes which are ready } if (this.javaLikeNamesChanged) { writeJavaLikeNamesFile(); this.javaLikeNamesChanged = false; } if (count < length) { System.arraycopy(locatedIndexes, 0, locatedIndexes=new Index[count], 0, count); } return locatedIndexes; }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
public boolean execute(IProgressMonitor progressMonitor) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); boolean isComplete = COMPLETE; this.executionTime = 0; Index[] indexes = getIndexes(progressMonitor); try { int max = indexes.length; if (progressMonitor != null) progressMonitor.beginTask("", max); //$NON-NLS-1$ for (int i = 0; i < max; i++) { isComplete &= search(indexes[i], progressMonitor); if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } if (JobManager.VERBOSE) Util.verbose("-> execution time: " + this.executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$ return isComplete; } finally { if (progressMonitor != null) progressMonitor.done(); } }
// in search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
public boolean search(Index index, IProgressMonitor progressMonitor) { if (index == null) return COMPLETE; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); ReadWriteMonitor monitor = index.monitor; if (monitor == null) return COMPLETE; // index got deleted since acquired try { monitor.enterRead(); // ask permission to read long start = System.currentTimeMillis(); MatchLocator.findIndexMatches(this.pattern, index, this.requestor, this.participant, this.scope, progressMonitor); this.executionTime += System.currentTimeMillis() - start; return COMPLETE; } catch (IOException e) { if (e instanceof java.io.EOFException) e.printStackTrace(); return FAILED; } finally { monitor.exitRead(); // finished reading } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void acceptMatch(String relativePath, String containerPath, char separator, SearchPattern pattern, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) { if (scope instanceof JavaSearchScope) { JavaSearchScope javaSearchScope = (JavaSearchScope) scope; // Get document path access restriction from java search scope // Note that requestor has to verify if needed whether the document violates the access restriction or not AccessRuleSet access = javaSearchScope.getAccessRuleSet(relativePath, containerPath); if (access != JavaSearchScope.NOT_ENCLOSED) { // scope encloses the document path StringBuffer documentPath = new StringBuffer(containerPath.length() + 1 + relativePath.length()); documentPath.append(containerPath); documentPath.append(separator); documentPath.append(relativePath); if (!requestor.acceptIndexMatch(documentPath.toString(), pattern, participant, access)) throw new OperationCanceledException(); } } else { StringBuffer buffer = new StringBuffer(containerPath.length() + 1 + relativePath.length()); buffer.append(containerPath); buffer.append(separator); buffer.append(relativePath); String documentPath = buffer.toString(); boolean encloses = (scope instanceof HierarchyScope) ? ((HierarchyScope)scope).encloses(documentPath, monitor) : scope.encloses(documentPath); if (encloses) if (!requestor.acceptIndexMatch(documentPath, pattern, participant, null)) throw new OperationCanceledException(); } }
// in search/org/eclipse/jdt/core/search/SearchPattern.java
public void findIndexMatches(Index index, IndexQueryRequestor requestor, SearchParticipant participant, IJavaSearchScope scope, IProgressMonitor monitor) throws IOException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); try { index.startQuery(); SearchPattern pattern = currentPattern(); EntryResult[] entries = pattern.queryIn(index); if (entries == null) return; SearchPattern decodedResult = pattern.getBlankPattern(); String containerPath = index.containerPath; char separator = index.separator; for (int i = 0, l = entries.length; i < l; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); EntryResult entry = entries[i]; decodedResult.decodeIndexKey(entry.getWord()); if (pattern.matchesDecodedKey(decodedResult)) { // TODO (kent) some clients may not need the document names String[] names = entry.getDocumentNames(index); for (int j = 0, n = names.length; j < n; j++) acceptMatch(names[j], containerPath, separator, decodedResult, requestor, participant, scope, monitor); } } } finally { index.stopQuery(); } }
// 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 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/JavaModelOperation.java
protected void checkCanceled() { if (isCanceled()) { throw new OperationCanceledException(Messages.operation_cancelled); } }
// 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/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/builder/BuildNotifier.java
public void checkCancel() { if (this.monitor != null && this.monitor.isCanceled()) throw new OperationCanceledException(); }
// 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/hierarchy/TypeHierarchy.java
protected void checkCanceled() { if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { throw new OperationCanceledException(); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); BinaryTypeBinding typeBinding = this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction); try { this.remember(binaryType, typeBinding); } catch (AbortCompilation e) { // ignore } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); // find most enclosing type first (needed when explicit askForType(...) is done // with a member type (e.g. p.A$B)) ISourceType sourceType = sourceTypes[0]; while (sourceType.getEnclosingType() != null) sourceType = sourceType.getEnclosingType(); // build corresponding compilation unit CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1, this.options.maxProblemsPerUnit); CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit( new ISourceType[] {sourceType}, // ignore secondary types, to improve laziness SourceTypeConverter.MEMBER_TYPE, // need member types // no need for field initialization this.lookupEnvironment.problemReporter, result); // build bindings if (unit != null) { try { this.lookupEnvironment.buildTypeBindings(unit, accessRestriction); org.eclipse.jdt.core.ICompilationUnit cu = ((SourceTypeElementInfo)sourceType).getHandle().getCompilationUnit(); rememberAllTypes(unit, cu, false); this.lookupEnvironment.completeTypeBindings(unit, true/*build constructor only*/); } catch (AbortCompilation e) { // missing 'java.lang' package: ignore } } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
private void reportHierarchy(IType focus, TypeDeclaration focusLocalType, ReferenceBinding binaryTypeBinding) { // set focus type binding if (focus != null) { if (binaryTypeBinding != null) { // binary type this.focusType = binaryTypeBinding; } else { // source type if (focusLocalType != null) { // anonymous or local type this.focusType = focusLocalType.binding; } else { // top level or member type char[] fullyQualifiedName = focus.getFullyQualifiedName().toCharArray(); setFocusType(CharOperation.splitOn('.', fullyQualifiedName)); } } } // be resilient and fix super type bindings fixSupertypeBindings(); int objectIndex = -1; IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; for (int current = this.typeIndex; current >= 0; current--) { if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); ReferenceBinding typeBinding = this.typeBindings[current]; // java.lang.Object treated at the end if (typeBinding.id == TypeIds.T_JavaLangObject) { objectIndex = current; continue; } IGenericType suppliedType = this.typeModels[current]; if (!subOrSuperOfFocus(typeBinding)) { continue; // ignore types outside of hierarchy } IType superclass; if (typeBinding.isInterface()){ // do not connect interfaces to Object superclass = null; } else { superclass = findSuperClass(suppliedType, typeBinding); } IType[] superinterfaces = findSuperInterfaces(suppliedType, typeBinding); this.builder.connect(suppliedType, this.builder.getHandle(suppliedType, typeBinding), superclass, superinterfaces); } // add java.lang.Object only if the super class is not missing if (objectIndex > -1 && (!this.hasMissingSuperClass || this.focusType == null)) { IGenericType objectType = this.typeModels[objectIndex]; this.builder.connect(objectType, this.builder.getHandle(objectType, this.typeBindings[objectIndex]), null, null); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
public void resolve(Openable[] openables, HashSet localTypes, IProgressMonitor monitor) { try { int openablesLength = openables.length; CompilationUnitDeclaration[] parsedUnits = new CompilationUnitDeclaration[openablesLength]; boolean[] hasLocalType = new boolean[openablesLength]; org.eclipse.jdt.core.ICompilationUnit[] cus = new org.eclipse.jdt.core.ICompilationUnit[openablesLength]; int unitsIndex = 0; CompilationUnitDeclaration focusUnit = null; ReferenceBinding focusBinaryBinding = null; IType focus = this.builder.getType(); Openable focusOpenable = null; if (focus != null) { if (focus.isBinary()) { focusOpenable = (Openable)focus.getClassFile(); } else { focusOpenable = (Openable)focus.getCompilationUnit(); } } // build type bindings Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); for (int i = 0; i < openablesLength; i++) { Openable openable = openables[i]; if (openable instanceof org.eclipse.jdt.core.ICompilationUnit) { org.eclipse.jdt.core.ICompilationUnit cu = (org.eclipse.jdt.core.ICompilationUnit)openable; // contains a potential subtype as a local or anonymous type? boolean containsLocalType = false; if (localTypes == null) { // case of hierarchy on region containsLocalType = true; } else { IPath path = cu.getPath(); containsLocalType = localTypes.contains(path.toString()); } // build parsed unit CompilationUnitDeclaration parsedUnit = null; if (cu.isOpen()) { // create parsed unit from source element infos CompilationResult result = new CompilationResult((ICompilationUnit)cu, i, openablesLength, this.options.maxProblemsPerUnit); SourceTypeElementInfo[] typeInfos = null; try { IType[] topLevelTypes = cu.getTypes(); int topLevelLength = topLevelTypes.length; if (topLevelLength == 0) continue; // empty cu: no need to parse (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65677) typeInfos = new SourceTypeElementInfo[topLevelLength]; for (int j = 0; j < topLevelLength; j++) { IType topLevelType = topLevelTypes[j]; typeInfos[j] = (SourceTypeElementInfo)((JavaElement)topLevelType).getElementInfo(); } } catch (JavaModelException e) { // types/cu exist since cu is opened } int flags = !containsLocalType ? SourceTypeConverter.MEMBER_TYPE : SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE | SourceTypeConverter.LOCAL_TYPE; parsedUnit = SourceTypeConverter.buildCompilationUnit( typeInfos, flags, this.lookupEnvironment.problemReporter, result); // We would have got all the necessary local types by now and hence there is no further need // to parse the method bodies. Parser.getMethodBodies, which is called latter in this function, // will not parse the method statements if ASTNode.HasAllMethodBodies is set. if (containsLocalType) parsedUnit.bits |= ASTNode.HasAllMethodBodies; } else { // create parsed unit from file IFile file = (IFile) cu.getResource(); ICompilationUnit sourceUnit = this.builder.createCompilationUnitFromPath(openable, file); CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); parsedUnit = parser.dietParse(sourceUnit, unitResult); } if (parsedUnit != null) { hasLocalType[unitsIndex] = containsLocalType; cus[unitsIndex] = cu; parsedUnits[unitsIndex++] = parsedUnit; try { this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); if (openable.equals(focusOpenable)) { focusUnit = parsedUnit; } } catch (AbortCompilation e) { // classpath problem for this type: ignore } } } else { // cache binary type binding ClassFile classFile = (ClassFile)openable; IBinaryType binaryType = (IBinaryType) JavaModelManager.getJavaModelManager().getInfo(classFile.getType()); if (binaryType == null) { // create binary type from file if (classFile.getPackageFragmentRoot().isArchive()) { binaryType = this.builder.createInfoFromClassFileInJar(classFile); } else { IResource file = classFile.resource(); binaryType = this.builder.createInfoFromClassFile(classFile, file); } } if (binaryType != null) { try { BinaryTypeBinding binaryTypeBinding = this.lookupEnvironment.cacheBinaryType(binaryType, false/*don't need field and method (bug 125067)*/, null /*no access restriction*/); remember(binaryType, binaryTypeBinding); if (openable.equals(focusOpenable)) { focusBinaryBinding = binaryTypeBinding; } } catch (AbortCompilation e) { // classpath problem for this type: ignore } } } } // remember type declaration of focus if local/anonymous early (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=210498) TypeDeclaration focusLocalType = null; if (focus != null && focusBinaryBinding == null && focusUnit != null && ((Member)focus).getOuterMostLocalContext() != null) { focusLocalType = new ASTNodeFinder(focusUnit).findType(focus); } for (int i = 0; i <= this.typeIndex; i++) { IGenericType suppliedType = this.typeModels[i]; if (suppliedType != null && suppliedType.isBinaryType()) { CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted; // fault in its hierarchy... try { // ensure that unitBeingCompleted is set so that we don't get an AbortCompilation for a missing type // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213249 ) if (previousUnitBeingCompleted == null) { this.lookupEnvironment.unitBeingCompleted = FakeUnit; } ReferenceBinding typeBinding = this.typeBindings[i]; typeBinding.superclass(); typeBinding.superInterfaces(); } catch (AbortCompilation e) { // classpath problem for this type: ignore } finally { this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted; } } } // complete type bindings (i.e. connect super types) for (int i = 0; i < unitsIndex; i++) { CompilationUnitDeclaration parsedUnit = parsedUnits[i]; if (parsedUnit != null) { try { if (hasLocalType[i]) { // NB: no-op if method bodies have been already parsed if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); parser.getMethodBodies(parsedUnit); } } catch (AbortCompilation e) { // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) hasLocalType[i] = false; } } } // complete type bindings and build fields and methods only for local types // (in this case the constructor is needed when resolving local types) // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=145333) try { this.lookupEnvironment.completeTypeBindings(parsedUnits, hasLocalType, unitsIndex); // remember type bindings for (int i = 0; i < unitsIndex; i++) { CompilationUnitDeclaration parsedUnit = parsedUnits[i]; if (parsedUnit != null && !parsedUnit.hasErrors()) { boolean containsLocalType = hasLocalType[i]; if (containsLocalType) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); parsedUnit.scope.faultInTypes(); parsedUnit.resolve(); } rememberAllTypes(parsedUnit, cus[i], containsLocalType); } } } catch (AbortCompilation e) { // skip it silently } worked(monitor, 1); // if no potential subtype was a real subtype of the binary focus type, no need to go further // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=54043) if (focusBinaryBinding == null && focus != null && focus.isBinary()) { char[] fullyQualifiedName = focus.getFullyQualifiedName().toCharArray(); focusBinaryBinding = this.lookupEnvironment.getCachedType(CharOperation.splitOn('.', fullyQualifiedName)); if (focusBinaryBinding == null) return; } reportHierarchy(focus, focusLocalType, focusBinaryBinding); } catch (ClassCastException e){ // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object if (TypeHierarchy.DEBUG) e.printStackTrace(); } finally { reset(); } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyResolver.java
protected void worked(IProgressMonitor monitor, int work) { if (monitor != null) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } else { monitor.worked(work); } } }
// in model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
protected void worked(IProgressMonitor monitor, int work) { if (monitor != null) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } else { monitor.worked(work); } } }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
public void findTypes(char[] prefix, final boolean findMembers, boolean camelCaseMatch, int searchFor, final ISearchRequestor storage, IProgressMonitor monitor) { /* if (true){ findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; } */ try { final String excludePath; if (this.unitToSkip != null) { if (!(this.unitToSkip instanceof IJavaElement)) { // revert to model investigation findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); return; } excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); } else { excludePath = null; } int lastDotIndex = CharOperation.lastIndexOf('.', prefix); char[] qualification, simpleName; if (lastDotIndex < 0) { qualification = null; if (camelCaseMatch) { simpleName = prefix; } else { simpleName = CharOperation.toLowerCase(prefix); } } else { qualification = CharOperation.subarray(prefix, 0, lastDotIndex); if (camelCaseMatch) { simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length); } else { simpleName = CharOperation.toLowerCase( CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length)); } } IProgressMonitor progressMonitor = new IProgressMonitor() { boolean isCanceled = false; public void beginTask(String name, int totalWork) { // implements interface method } public void done() { // implements interface method } public void internalWorked(double work) { // implements interface method } public boolean isCanceled() { return this.isCanceled; } public void setCanceled(boolean value) { this.isCanceled = value; } public void setTaskName(String name) { // implements interface method } public void subTask(String name) { // implements interface method } public void worked(int work) { // implements interface method } }; IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0) return; // accept only top level types storage.acceptType(packageName, simpleTypeName, enclosingTypeNames, modifiers, access); } }; int matchRule = SearchPattern.R_PREFIX_MATCH; if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH; if (monitor != null) { IndexManager indexManager = JavaModelManager.getIndexManager(); if (indexManager.awaitingJobsCount() == 0) { // indexes were already there, so perform an immediate search to avoid any index rebuilt new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { // indexes were not ready, give the indexing a chance to finish small jobs by sleeping 100ms... try { Thread.sleep(100); } catch (InterruptedException e) { // Do nothing } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (indexManager.awaitingJobsCount() == 0) { // indexes are now ready, so perform an immediate search to avoid any index rebuilt new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { // Indexes are still not ready, so look for types in the model instead of a search request findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } } } else { try { new BasicSearchEngine(this.workingCopies).searchAllTypeNames( qualification, SearchPattern.R_EXACT_MATCH, simpleName, matchRule, // not case sensitive searchFor, getSearchScope(), typeRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, progressMonitor); } catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } } } catch (JavaModelException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); } }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
public void findConstructorDeclarations(char[] prefix, boolean camelCaseMatch, final ISearchRequestor storage, IProgressMonitor monitor) { try { final String excludePath; if (this.unitToSkip != null && this.unitToSkip instanceof IJavaElement) { excludePath = ((IJavaElement) this.unitToSkip).getPath().toString(); } else { excludePath = null; } int lastDotIndex = CharOperation.lastIndexOf('.', prefix); char[] qualification, simpleName; if (lastDotIndex < 0) { qualification = null; if (camelCaseMatch) { simpleName = prefix; } else { simpleName = CharOperation.toLowerCase(prefix); } } else { qualification = CharOperation.subarray(prefix, 0, lastDotIndex); if (camelCaseMatch) { simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length); } else { simpleName = CharOperation.toLowerCase( CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length)); } } IProgressMonitor progressMonitor = new IProgressMonitor() { boolean isCanceled = false; public void beginTask(String name, int totalWork) { // implements interface method } public void done() { // implements interface method } public void internalWorked(double work) { // implements interface method } public boolean isCanceled() { return this.isCanceled; } public void setCanceled(boolean value) { this.isCanceled = value; } public void setTaskName(String name) { // implements interface method } public void subTask(String name) { // implements interface method } public void worked(int work) { // implements interface method } }; IRestrictedAccessConstructorRequestor constructorRequestor = new IRestrictedAccessConstructorRequestor() { public void acceptConstructor( int modifiers, char[] simpleTypeName, int parameterCount, char[] signature, char[][] parameterTypes, char[][] parameterNames, int typeModifiers, char[] packageName, int extraFlags, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; storage.acceptConstructor( modifiers, simpleTypeName, parameterCount, signature, parameterTypes, parameterNames, typeModifiers, packageName, extraFlags, path, access); } }; int matchRule = SearchPattern.R_PREFIX_MATCH; if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH; if (monitor != null) { IndexManager indexManager = JavaModelManager.getIndexManager(); while (indexManager.awaitingJobsCount() > 0) { try { Thread.sleep(50); // indexes are not ready, sleep 50ms... } catch (InterruptedException e) { // Do nothing } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations( qualification, simpleName, matchRule, getSearchScope(), constructorRequestor, FORCE_IMMEDIATE_SEARCH, progressMonitor); } else { try { new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations( qualification, simpleName, matchRule, getSearchScope(), constructorRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, progressMonitor); } catch (OperationCanceledException e) { // Do nothing } } } catch (JavaModelException e) { // Do nothing } }
// in model/org/eclipse/jdt/internal/compiler/SourceElementParser.java
public CompilationUnitDeclaration parseCompilationUnit( ICompilationUnit unit, boolean fullParse, IProgressMonitor pm) { boolean old = this.diet; CompilationUnitDeclaration parsedUnit = null; try { this.diet = true; this.reportReferenceInfo = fullParse; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit); parsedUnit = parse(unit, compilationUnitResult); if (pm != null && pm.isCanceled()) throw new OperationCanceledException(Messages.operation_cancelled); if (this.scanner.recordLineSeparator) { this.requestor.acceptLineSeparatorPositions(compilationUnitResult.getLineSeparatorPositions()); } int initialStart = this.scanner.initialPosition; int initialEnd = this.scanner.eofPosition; if (this.reportLocalDeclarations || fullParse){ this.diet = false; getMethodBodies(parsedUnit); } this.scanner.resetTo(initialStart, initialEnd); this.notifier.notifySourceElementRequestor( parsedUnit, this.scanner.initialPosition, this.scanner.eofPosition, this.reportReferenceInfo, this.sourceEnds, this.nodesToCategories); return parsedUnit; } catch (AbortCompilation e) { // ignore this exception } finally { this.diet = old; reset(); } return parsedUnit; }
// in codeassist/org/eclipse/jdt/internal/codeassist/CompletionEngine.java
void checkCancel() { if (this.monitor != null && this.monitor.isCanceled()) { throw new OperationCanceledException(); } }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
private void worked(int work) { if (this.monitor != null) { if (this.monitor.isCanceled()) throw new OperationCanceledException(); this.monitor.worked(work); } }
// in dom/org/eclipse/jdt/core/dom/ASTConverter.java
protected void checkCanceled() { if (this.monitor != null && this.monitor.isCanceled()) throw new OperationCanceledException(); }
0 0 9
            
// in search/org/eclipse/jdt/internal/core/search/BasicSearchEngine.java
catch (OperationCanceledException oce) { // do nothing }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (OperationCanceledException e) { // catch this exception so as to not enter the catch(RuntimeException e) below throw e; }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findExactTypes( new String(name), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { findTypes( new String(prefix), storage, convertSearchFilterToModelFilter(searchFor)); }
// in model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
catch (OperationCanceledException e) { // Do nothing }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
catch (OperationCanceledException e) { // do nothing }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
4
            
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
catch (OperationCanceledException e) { // catch this exception so as to not enter the catch(RuntimeException e) below throw e; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) throw e; // else indexes were not ready: catch the exception so that jars are still refreshed }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (OperationCanceledException e) { throw e; }
0
unknown (Lib) OutOfMemoryError 0 0 0 1
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
1
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
catch (OutOfMemoryError oom) { // DEBUG oom.printStackTrace(); System.err.println("-------------------- DEBUG --------------------"); //$NON-NLS-1$ System.err.println("file = "+this.indexFile); //$NON-NLS-1$ System.err.println("offset = "+offset); //$NON-NLS-1$ System.err.println("size = "+size); //$NON-NLS-1$ System.err.println("-------------------- END --------------------"); //$NON-NLS-1$ throw oom; }
0
unknown (Lib) ParserConfigurationException 0 0 0 4
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(ParserConfigurationException e){ return; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { return null; }
2
            
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (ParserConfigurationException e) { throw new IOException(Messages.file_badFormat); }
0
unknown (Lib) ProtocolException 0 0 0 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(ProtocolException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0 0
runtime (Lib) RuntimeException 7
            
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
int internalGetSetIntProperty(SimplePropertyDescriptor property, boolean get, int value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
boolean internalGetSetBooleanProperty(SimplePropertyDescriptor property, boolean get, boolean value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
Object internalGetSetObjectProperty(SimplePropertyDescriptor property, boolean get, Object value) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
ASTNode internalGetSetChildProperty(ChildPropertyDescriptor property, boolean get, ASTNode child) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
List internalGetChildListProperty(ChildListPropertyDescriptor property) { throw new RuntimeException("Node does not have this property"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
static void addProperty(StructuralPropertyDescriptor property, List propertyList) { Class nodeClass = (Class) propertyList.get(0); if (property.getNodeClass() != nodeClass) { // easily made cut-and-paste mistake throw new RuntimeException("Structural property descriptor has wrong node class!"); //$NON-NLS-1$ } propertyList.add(property); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
IBinding createBinding(String key) { if (this.bindingTables == null) throw new RuntimeException("Cannot be called outside ASTParser#createASTs(...)"); //$NON-NLS-1$ BindingKeyResolver keyResolver = new BindingKeyResolver(key, this, this.lookupEnvironment); Binding compilerBinding = keyResolver.getCompilerBinding(); if (compilerBinding == null) return null; DefaultBindingResolver resolver = new DefaultBindingResolver(this.lookupEnvironment, null/*no owner*/, this.bindingTables, false, this.fromJavaProject); return resolver.getBinding(compilerBinding); }
0 0 31
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (RuntimeException e) { // internal compiler failure this.logger.logException(e); if (this.systemExitWhenFinished) { this.logger.flush(); this.logger.close(); System.exit(-1); } return false; }
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
catch (RuntimeException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=182154 // logging the entry that could not be indexed and continue with the next one // we remove all entries relative to the boggus document this.document.removeAllIndexEntries(); Util.log(IStatus.WARNING, "The Java indexing could not index " + this.document.getPath() + ". This .class file doesn't follow the class file format specification. Please report this issue against the .class file vendor"); //$NON-NLS-1$ //$NON-NLS-2$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (file.exists()) Util.log(e, "Unable to read variable and containers file (file is corrupt)"); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in model/org/eclipse/jdt/internal/core/LocalVariable.java
catch(RuntimeException e) { return null; }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/internal/core/util/BindingKeyResolver.java
catch (RuntimeException e) { Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$ return null; }
// in model/org/eclipse/jdt/internal/core/SourceRefElement.java
catch(RuntimeException e) { return null; }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/ProcessTaskManager.java
catch (RuntimeException e) { synchronized (this) { this.processingThread = null; this.caughtException = e; } return; }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (RuntimeException e) { synchronized (this) { this.caughtException = e; shutdown(); } return; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
catch (RuntimeException e) { // since debugger sometimes call toString methods, problems can easily happen when // toString is called on an instance that is being initialized buffer.setLength(p); buffer.append("!"); //$NON-NLS-1$ buffer.append(standardToString()); }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared fields"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declared methods"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring method"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve declaring class"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve interfaces"); //$NON-NLS-1$ }
// in dom/org/eclipse/jdt/core/dom/TypeBinding.java
catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the classpath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299 */ org.eclipse.jdt.internal.core.util.Util.log(e, "Could not retrieve superclass"); //$NON-NLS-1$ return this.resolver.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ }
13
            
// in search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
catch (RuntimeException e) { if (this.processingThread != null) { // if not shutting down // log exception Util.log(e, "Background Indexer Crash Recovery"); //$NON-NLS-1$ // keep job manager alive discardJobs(null); this.processingThread = null; reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent } throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { shutdown(); throw e; }
// in model/org/eclipse/jdt/internal/core/CompilationUnitProblemFinder.java
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); }
// in model/org/eclipse/jdt/core/JavaCore.java
catch (RuntimeException e) { if (JavaModelManager.CP_RESOLVE_VERBOSE || JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) e.printStackTrace(); throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/classfmt/ClassFileReader.java
catch(RuntimeException e) { ClassFormatException exception = new ClassFormatException(e, this.classFileName); throw exception; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { unit = processingTask.unitToProcess; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
// in dom/org/eclipse/jdt/core/dom/CompilationUnitResolver.java
catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow }
0
unknown (Lib) SAXException 0 0 0 4
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SAXException e) { return; }
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { return null; }
2
            
// in model/org/eclipse/jdt/internal/core/UserLibrary.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (SAXException e) { throw new IOException(Messages.file_badFormat); }
0
unknown (Lib) SecurityException 0 0 0 7
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (SecurityException e) { e.printStackTrace(); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch(SecurityException se) { // could not delete file: cannot do much more }
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SecurityException e) { // ignore }
// in compiler/org/eclipse/jdt/internal/compiler/ReadManager.java
catch (SecurityException e) { // ignored }
// in compiler/org/eclipse/jdt/internal/compiler/util/Messages.java
catch (SecurityException e) { // ignore }
0
            
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (RuntimeException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
// in model/org/eclipse/jdt/internal/core/JavaModelManager.java
catch (IOException e) { try { file.delete(); } catch(SecurityException se) { // could not delete file: cannot do much more } throw new CoreException( new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Messages.bind(Messages.build_cannotSaveState, info.project.getName()), e)); }
0
runtime (Domain) SelectionNodeFound
public class SelectionNodeFound extends RuntimeException {

	public Binding binding;
	public boolean isDeclaration;
	private static final long serialVersionUID = -7335444736618092295L; // backward compatible

public SelectionNodeFound() {
	this(null, false); // we found a problem in the selection node
}
public SelectionNodeFound(Binding binding) {
	this(binding, false);
}
public SelectionNodeFound(Binding binding, boolean isDeclaration) {
	this.binding = binding;
	this.isDeclaration = isDeclaration;
}
}
58
            
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java
public void resolve(BlockScope scope) { super.resolve(scope); // tolerate some error cases if (this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnArgumentName.java
public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { super.bind(scope, typeBinding, used); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnArgumentName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java
public TypeBinding resolveType(BlockScope scope) { // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.tokens, this); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext) { throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSuperReference.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding binding = super.resolveType(scope); if (binding == null || !binding.isValidBinding()) throw new SelectionNodeFound(); else throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); if (this.binding == null) { throw new SelectionNodeFound(); } // tolerate some error cases if (!this.binding.isValidBinding()) { switch (this.binding.problemId()) { case ProblemReasons.NotVisible: // visibility is ignored break; case ProblemReasons.NotFound: if (this.resolvedType != null && this.resolvedType.isValidBinding()) { throw new SelectionNodeFound(this.resolvedType); } throw new SelectionNodeFound(); default: throw new SelectionNodeFound(); } } if (this.anonymousType == null) throw new SelectionNodeFound(this.binding); // if selecting a type for an anonymous type creation, we have to // find its target super constructor (if extending a class) or its target // super interface (if extending an interface) if (this.anonymousType.binding != null) { LocalTypeBinding localType = (LocalTypeBinding) this.anonymousType.binding; if (localType.superInterfaces == Binding.NO_SUPERINTERFACES) { // find the constructor binding inside the super constructor call ConstructorDeclaration constructor = (ConstructorDeclaration) this.anonymousType.declarationOf(this.binding.original()); if (constructor != null) { throw new SelectionNodeFound(constructor.constructorCall.binding); } throw new SelectionNodeFound(this.binding); } // open on the only super interface throw new SelectionNodeFound(localType.superInterfaces[0]); } else { if (this.resolvedType.isInterface()) { throw new SelectionNodeFound(this.resolvedType); } throw new SelectionNodeFound(this.binding); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java
public TypeBinding resolveType(BlockScope scope) { TypeBinding binding = super.resolveType(scope); if (binding == null || !binding.isValidBinding()) throw new SelectionNodeFound(); else throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleNameReference.java
public TypeBinding resolveType(BlockScope scope) { if (this.actualReceiverType != null) { this.binding = scope.getField(this.actualReceiverType, this.token, this); if (this.binding != null && this.binding.isValidBinding()) { throw new SelectionNodeFound(this.binding); } } // it can be a package, type, member type, local variable or field this.binding = scope.getBinding(this.token, Binding.VARIABLE | Binding.TYPE | Binding.PACKAGE, this, true /*resolve*/); if (!this.binding.isValidBinding()) { if (this.binding instanceof ProblemFieldBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidField(this, (FieldBinding) this.binding); } else if (this.binding instanceof ProblemReferenceBinding || this.binding instanceof MissingTypeBinding) { // tolerate some error cases if (this.binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(this.binding); } scope.problemReporter().invalidType(this, (TypeBinding) this.binding); } else { scope.problemReporter().unresolvableReference(this, this.binding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnLocalName.java
public void resolve(BlockScope scope) { super.resolve(scope); throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnMessageSend.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); // tolerate some error cases if(this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) { throw new SelectionNodeFound(); } else { if(this.binding.isDefaultAbstract()) { throw new SelectionNodeFound(findNonDefaultAbstractMethod(this.binding)); // 23594 } else { throw new SelectionNodeFound(this.binding); } } }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnNameOfMemberValuePair.java
public void resolveTypeExpecting(BlockScope scope, TypeBinding requiredType) { super.resolveTypeExpecting(scope, requiredType); if(this.binding != null) { throw new SelectionNodeFound(this.binding); } throw new SelectionNodeFound(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.getTypeOrPackage(this.tokens); if (!binding.isValidBinding()) { // tolerate some error cases if (binding.problemId() == ProblemReasons.NotVisible){ throw new SelectionNodeFound(binding); } if (binding instanceof TypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) binding); } else if (binding instanceof PackageBinding) { ProblemReferenceBinding problemBinding = new ProblemReferenceBinding(((PackageBinding)binding).compoundName, null, binding.problemId()); scope.problemReporter().invalidType(this, problemBinding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
protected TypeBinding getTypeBinding(Scope scope) { // it can be a package, type or member type Binding binding = scope.getTypeOrPackage(new char[][] {this.token}); if (!binding.isValidBinding()) { if (binding instanceof TypeBinding) { scope.problemReporter().invalidType(this, (TypeBinding) binding); } else if (binding instanceof PackageBinding) { ProblemReferenceBinding problemBinding = new ProblemReferenceBinding(((PackageBinding)binding).compoundName, null, binding.problemId()); scope.problemReporter().invalidType(this, problemBinding); } throw new SelectionNodeFound(); } throw new SelectionNodeFound(binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnSingleTypeReference.java
public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { super.resolveTypeEnclosing(scope, enclosingType); // tolerate some error cases if (this.resolvedType == null || !(this.resolvedType.isValidBinding() || this.resolvedType.problemId() == ProblemReasons.NotVisible)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedSingleTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedSingleTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnFieldReference.java
public TypeBinding resolveType(BlockScope scope) { super.resolveType(scope); // tolerate some error cases if (this.binding == null || !(this.binding.isValidBinding() || this.binding.problemId() == ProblemReasons.NotVisible || this.binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName || this.binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation || this.binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) throw new SelectionNodeFound(); else throw new SelectionNodeFound(this.binding); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) { super.resolveType(scope, checkBounds); //// removed unnecessary code to solve bug 94653 //if(this.resolvedType != null && this.resolvedType.isRawType()) { // ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType()); // throw new SelectionNodeFound(parameterizedTypeBinding); //} throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedQualifiedTypeReference.java
public TypeBinding resolveType(ClassScope scope) { super.resolveType(scope); //// removed unnecessary code to solve bug 94653 //if(this.resolvedType != null && this.resolvedType.isRawType()) { // ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType()); // throw new SelectionNodeFound(parameterizedTypeBinding); //} throw new SelectionNodeFound(this.resolvedType); }
// in codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionJavadoc.java
private void internalResolve(Scope scope) { if (this.selectedNode != null) { switch (scope.kind) { case Scope.CLASS_SCOPE: this.selectedNode.resolveType((ClassScope)scope); break; case Scope.METHOD_SCOPE: this.selectedNode.resolveType((MethodScope)scope); break; } Binding binding = null; if (this.selectedNode instanceof JavadocFieldReference) { JavadocFieldReference fieldRef = (JavadocFieldReference) this.selectedNode; binding = fieldRef.binding; if (binding == null && fieldRef.methodBinding != null) { binding = fieldRef.methodBinding; } } else if (this.selectedNode instanceof JavadocMessageSend) { binding = ((JavadocMessageSend) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocAllocationExpression) { binding = ((JavadocAllocationExpression) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocSingleNameReference) { binding = ((JavadocSingleNameReference) this.selectedNode).binding; } else if (this.selectedNode instanceof JavadocSingleTypeReference) { JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) this.selectedNode; if (typeRef.packageBinding == null) { binding = typeRef.resolvedType; } } else if (this.selectedNode instanceof JavadocQualifiedTypeReference) { JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) this.selectedNode; if (typeRef.packageBinding == null) { binding = typeRef.resolvedType; } } else { binding = this.selectedNode.resolvedType; } throw new SelectionNodeFound(binding); } else if (this.inheritDocSelected) { // no selection node when inheritDoc tag is selected // But we need to detect it to enable code select on inheritDoc ReferenceContext referenceContext = scope.referenceContext(); if (referenceContext instanceof MethodDeclaration) { throw new SelectionNodeFound(((MethodDeclaration) referenceContext).binding); } } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.selector == assistIdentifier){ if (constructorDeclaration.binding != null) { throw new SelectionNodeFound(constructorDeclaration.binding); } else { if (constructorDeclaration.scope != null) { throw new SelectionNodeFound(new MethodBinding(constructorDeclaration.modifiers, constructorDeclaration.selector, null, null, null, constructorDeclaration.scope.referenceType().binding)); } } } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { if (fieldDeclaration.name == assistIdentifier){ throw new SelectionNodeFound(fieldDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) { if (localTypeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(localTypeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) { if (memberTypeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(memberTypeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { if (methodDeclaration.selector == assistIdentifier){ if (methodDeclaration.binding != null) { throw new SelectionNodeFound(methodDeclaration.binding); } else { if (methodDeclaration.scope != null) { throw new SelectionNodeFound(new MethodBinding(methodDeclaration.modifiers, methodDeclaration.selector, null, null, null, methodDeclaration.scope.referenceType().binding)); } } } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { if (typeDeclaration.name == assistIdentifier) { throw new SelectionNodeFound(typeDeclaration.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeParameter typeParameter, BlockScope scope) { if (typeParameter.name == assistIdentifier) { throw new SelectionNodeFound(typeParameter.binding); } return true; }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
public boolean visit(TypeParameter typeParameter, ClassScope scope) { if (typeParameter.name == assistIdentifier) { throw new SelectionNodeFound(typeParameter.binding); } return true; }
0 0 2
            
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
// in codeassist/org/eclipse/jdt/internal/codeassist/SelectionEngine.java
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); } }
0 0
runtime (Domain) ShouldNotImplement
public class ShouldNotImplement extends RuntimeException {
	private static final long serialVersionUID = 2669970476264283736L; // backward compatible
	public ShouldNotImplement(String message) {
		super(message);
	}
}
10
            
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public boolean booleanValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "boolean" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public byte byteValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "byte" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public char charValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "char" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public double doubleValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "double" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public float floatValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "float" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public int intValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "int" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public long longValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotCastedInto, new String[] { typeName(), "long" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public short shortValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "short" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/impl/Constant.java
public String stringValue() { throw new ShouldNotImplement(Messages.bind(Messages.constant_cannotConvertedTo, new String[] { typeName(), "String" })); //$NON-NLS-1$ }
// in compiler/org/eclipse/jdt/internal/compiler/ast/Expression.java
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { if (this.constant != Constant.NotAConstant) { // generate a constant expression int pc = codeStream.position; codeStream.generateConstant(this.constant, this.implicitConversion); codeStream.recordPositionsFrom(pc, this.sourceStart); } else { // actual non-constant code generation throw new ShouldNotImplement(Messages.ast_missingCode); } }
0 0 2
            
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ShouldNotImplement e) { this.contentsOffset = startingContentsOffset; }
// in compiler/org/eclipse/jdt/internal/compiler/ClassFile.java
catch(ShouldNotImplement e) { this.contentsOffset = startingContentsOffset; }
0 0
unknown (Lib) SocketException 0 0 0 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(SocketException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0 0
unknown (Lib) SocketTimeoutException 0 0 0 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch (SocketTimeoutException e) { throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CANNOT_RETRIEVE_ATTACHED_JAVADOC_TIMEOUT, this)); }
0
runtime (Domain) SourceTypeCollisionException
public class SourceTypeCollisionException extends RuntimeException {
	private static final long serialVersionUID = 4798247636899127380L;

	public ICompilationUnit[] newAnnotationProcessorUnits;
}
2
            
// in compiler/org/eclipse/jdt/internal/compiler/lookup/CompilationUnitScope.java
void buildTypeBindings(AccessRestriction accessRestriction) { this.topLevelTypes = new SourceTypeBinding[0]; // want it initialized if the package cannot be resolved boolean firstIsSynthetic = false; if (this.referenceContext.compilationResult.compilationUnit != null) { char[][] expectedPackageName = this.referenceContext.compilationResult.compilationUnit.getPackageName(); if (expectedPackageName != null && !CharOperation.equals(this.currentPackageName, expectedPackageName)) { // only report if the unit isn't structurally empty if (this.referenceContext.currentPackage != null || this.referenceContext.types != null || this.referenceContext.imports != null) { problemReporter().packageIsNotExpectedPackage(this.referenceContext); } this.currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR : expectedPackageName; } } if (this.currentPackageName == CharOperation.NO_CHAR_CHAR) { // environment default package is never null this.fPackage = this.environment.defaultPackage; } else { if ((this.fPackage = this.environment.createPackage(this.currentPackageName)) == null) { if (this.referenceContext.currentPackage != null) { problemReporter().packageCollidesWithType(this.referenceContext); // only report when the unit has a package statement } // ensure fPackage is not null this.fPackage = this.environment.defaultPackage; return; } else if (this.referenceContext.isPackageInfo()) { // resolve package annotations now if this is "package-info.java". if (this.referenceContext.types == null || this.referenceContext.types.length == 0) { this.referenceContext.types = new TypeDeclaration[1]; this.referenceContext.createPackageInfoType(); firstIsSynthetic = true; } // ensure the package annotations are copied over before resolution if (this.referenceContext.currentPackage != null) this.referenceContext.types[0].annotations = this.referenceContext.currentPackage.annotations; } recordQualifiedReference(this.currentPackageName); // always dependent on your own package } // Skip typeDeclarations which know of previously reported errors TypeDeclaration[] types = this.referenceContext.types; int typeLength = (types == null) ? 0 : types.length; this.topLevelTypes = new SourceTypeBinding[typeLength]; int count = 0; nextType: for (int i = 0; i < typeLength; i++) { TypeDeclaration typeDecl = types[i]; if (this.environment.isProcessingAnnotations && this.environment.isMissingType(typeDecl.name)) throw new SourceTypeCollisionException(); // resolved a type ref before APT generated the type ReferenceBinding typeBinding = this.fPackage.getType0(typeDecl.name); recordSimpleReference(typeDecl.name); // needed to detect collision cases if (typeBinding != null && typeBinding.isValidBinding() && !(typeBinding instanceof UnresolvedReferenceBinding)) { // if its an unresolved binding - its fixed up whenever its needed, see UnresolvedReferenceBinding.resolve() if (this.environment.isProcessingAnnotations) throw new SourceTypeCollisionException(); // resolved a type ref before APT generated the type // if a type exists, check that its a valid type // it can be a NotFound problem type if its a secondary type referenced before its primary type found in additional units // and it can be an unresolved type which is now being defined problemReporter().duplicateTypes(this.referenceContext, typeDecl); continue nextType; } if (this.fPackage != this.environment.defaultPackage && this.fPackage.getPackage(typeDecl.name) != null) { // if a package exists, it must be a valid package - cannot be a NotFound problem package // this is now a warning since a package does not really 'exist' until it contains a type, see JLS v2, 7.4.3 problemReporter().typeCollidesWithPackage(this.referenceContext, typeDecl); } if ((typeDecl.modifiers & ClassFileConstants.AccPublic) != 0) { char[] mainTypeName; if ((mainTypeName = this.referenceContext.getMainTypeName()) != null // mainTypeName == null means that implementor of ICompilationUnit decided to return null && !CharOperation.equals(mainTypeName, typeDecl.name)) { problemReporter().publicClassMustMatchFileName(this.referenceContext, typeDecl); // tolerate faulty main type name (91091), allow to proceed into type construction } } ClassScope child = new ClassScope(this, typeDecl); SourceTypeBinding type = child.buildType(null, this.fPackage, accessRestriction); if (firstIsSynthetic && i == 0) type.modifiers |= ClassFileConstants.AccSynthetic; if (type != null) this.topLevelTypes[count++] = type; } // shrink topLevelTypes... only happens if an error was reported if (count != this.topLevelTypes.length) System.arraycopy(this.topLevelTypes, 0, this.topLevelTypes = new SourceTypeBinding[count], 0, count); }
0 0 3
            
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { reset(); // a generated type was referenced before it was created // the compiler either created a MissingType or found a BinaryType for it // so add the processor's generated files & start over, // but remember to only pass the generated files to the annotation processor int originalLength = originalUnits.length; int newProcessedLength = e.newAnnotationProcessorUnits.length; ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength]; System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength); System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength); this.annotationProcessorStartIndex = originalLength; compile(combinedUnits); return; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
2
            
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
// in compiler/org/eclipse/jdt/internal/compiler/Compiler.java
catch (SourceTypeCollisionException e) { e.newAnnotationProcessorUnits = newProcessedUnits; throw e; }
0
checked (Lib) Throwable 0 0 0 1
            
// in compiler/org/eclipse/jdt/internal/compiler/ast/SwitchStatement.java
catch (Throwable e) { e.printStackTrace(); }
0 0
unknown (Lib) UTFDataFormatException 3
            
// in search/org/eclipse/jdt/internal/core/index/DiskIndex.java
private char[] readStreamChars(FileInputStream stream) throws IOException { // read chars array length if (stream != null && this.bufferIndex + 2 >= this.bufferEnd) readStreamBuffer(stream); int length = (this.streamBuffer[this.bufferIndex++] & 0xFF) << 8; length += this.streamBuffer[this.bufferIndex++] & 0xFF; // fill the chars from bytes buffer char[] word = new char[length]; int i = 0; while (i < length) { // how many characters can be decoded without refilling the buffer? int charsInBuffer = i + ((this.bufferEnd - this.bufferIndex) / 3); // all the characters must already be in the buffer if we're at the end of the stream if (charsInBuffer > length || this.bufferEnd != this.streamBuffer.length || stream == null) charsInBuffer = length; while (i < charsInBuffer) { byte b = this.streamBuffer[this.bufferIndex++]; switch (b & 0xF0) { case 0x00 : case 0x10 : case 0x20 : case 0x30 : case 0x40 : case 0x50 : case 0x60 : case 0x70 : word[i++]= (char) b; break; case 0xC0 : case 0xD0 : char next = (char) this.streamBuffer[this.bufferIndex++]; if ((next & 0xC0) != 0x80) { throw new UTFDataFormatException(); } char ch = (char) ((b & 0x1F) << 6); ch |= next & 0x3F; word[i++] = ch; break; case 0xE0 : char first = (char) this.streamBuffer[this.bufferIndex++]; char second = (char) this.streamBuffer[this.bufferIndex++]; if ((first & second & 0xC0) != 0x80) { throw new UTFDataFormatException(); } ch = (char) ((b & 0x0F) << 12); ch |= ((first& 0x3F) << 6); ch |= second & 0x3F; word[i++] = ch; break; default: throw new UTFDataFormatException(); } } if (i < length && stream != null) readStreamBuffer(stream); } return word; }
0 0 0 0 0
unknown (Lib) UnknownHostException 0 0 0 1
            
// in model/org/eclipse/jdt/internal/core/JavaElement.java
catch(UnknownHostException e) { // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845 }
0 0
unknown (Lib) UnsupportedClassVersionError 0 0 0 1
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch(UnsupportedClassVersionError e) { // report a warning this.logger.logIncorrectVMVersionForAnnotationProcessing(); }
0 0
unknown (Lib) UnsupportedEncodingException 0 0 0 11
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/ClasspathEntry.java
catch (UnsupportedEncodingException e) { // ignore (UTF8 is always supported) }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default property = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not read .classpath with UTF-8 encoding"); //$NON-NLS-1$ // fallback to default xmlClasspath = new String(bytes); }
// in model/org/eclipse/jdt/internal/core/JavaProject.java
catch (UnsupportedEncodingException e) { Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$ // fallback to default bytes = value.getBytes(); }
// in compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
catch(UnsupportedEncodingException e){ // ignore unsupported encoding }
// in compiler/org/eclipse/jdt/internal/compiler/util/Util.java
catch (UnsupportedEncodingException e) { // encoding is not supported reader = new BufferedReader(new InputStreamReader(stream)); }
4
            
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(this.main.bind("configure.cannotOpenLogInvalidEncoding", logFileName)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", customEncoding)); //$NON-NLS-1$ }
// in batch/org/eclipse/jdt/internal/compiler/batch/Main.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( this.bind("configure.unsupportedEncoding", currentArg)); //$NON-NLS-1$ }
// in model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); }
3
runtime (Lib) UnsupportedOperationException 10
            
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionContext.java
public IJavaElement getEnclosingElement() { if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$ if (this.extendedContext == null) return null; return this.extendedContext.getEnclosingElement(); }
// in codeassist/org/eclipse/jdt/internal/codeassist/InternalCompletionContext.java
public IJavaElement[] getVisibleElements(String typeSignature) { if (!this.isExtended) throw new UnsupportedOperationException("Operation only supported in extended context"); //$NON-NLS-1$ if (this.extendedContext == null) return new IJavaElement[0]; return this.extendedContext.getVisibleElements(typeSignature); }
// in dom/org/eclipse/jdt/internal/core/dom/rewrite/RewriteEventStore.java
public void remove() { throw new UnsupportedOperationException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public void remove() { throw new UnsupportedOperationException(); }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void unsupportedIn2() { if (this.ast.apiLevel == AST.JLS2_INTERNAL) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void unsupportedIn2_3() { if (this.ast.apiLevel <= AST.JLS3) { throw new UnsupportedOperationException("Operation only supported in JLS4 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
final void supportedOnlyIn2() { if (this.ast.apiLevel != AST.JLS2_INTERNAL) { throw new UnsupportedOperationException("Operation only supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/ASTNode.java
public static ASTNode copySubtree(AST target, ASTNode node) { if (node == null) { return null; } if (target == null) { throw new IllegalArgumentException(); } if (target.apiLevel() != node.getAST().apiLevel()) { throw new UnsupportedOperationException(); } ASTNode newNode = node.clone(target); return newNode; }
// in dom/org/eclipse/jdt/core/dom/AST.java
void supportedOnlyIn2() { if (this.apiLevel != AST.JLS2) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
// in dom/org/eclipse/jdt/core/dom/AST.java
void unsupportedIn2() { if (this.apiLevel == AST.JLS2) { throw new UnsupportedOperationException("Operation not supported in JLS2 AST"); //$NON-NLS-1$ } }
0 0 0 0 0
runtime (Domain) WrappedCoreException
public static class WrappedCoreException extends RuntimeException {
	private static final long serialVersionUID = 8354329870126121212L; // backward compatible
	public CoreException coreException;
	public WrappedCoreException(CoreException coreException) {
		this.coreException = coreException;
	}
}
1
            
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
public boolean visit(TypeDeclaration typeDeclaration, BlockScope unused) { try { char[] simpleName; if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { simpleName = CharOperation.NO_CHAR; } else { simpleName = typeDeclaration.name; } int occurrenceCount = this.occurrencesCounts.get(simpleName); if (occurrenceCount == HashtableOfIntValues.NO_VALUE) { occurrenceCount = 1; } else { occurrenceCount = occurrenceCount + 1; } this.occurrencesCounts.put(simpleName, occurrenceCount); if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { this.locator.reportMatching(typeDeclaration, this.enclosingElement, -1, this.nodeSet, occurrenceCount); } else { Integer level = (Integer) this.nodeSet.matchingNodes.removeKey(typeDeclaration); this.locator.reportMatching(typeDeclaration, this.enclosingElement, level != null ? level.intValue() : -1, this.nodeSet, occurrenceCount); } return false; // don't visit members as this was done during reportMatching(...) } catch (CoreException e) { throw new WrappedCoreException(e); } }
1
            
// in search/org/eclipse/jdt/internal/core/search/matching/MemberDeclarationVisitor.java
catch (CoreException e) { throw new WrappedCoreException(e); }
0 2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
2
            
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
// in search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
catch (WrappedCoreException e) { throw e.coreException; }
0
unknown (Lib) ZipException 0 0 0 1
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
1
            
// in antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java
catch (ZipException e) { throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$ }
0

Miscellanous Metrics

nF = Number of Finally 301
nF = Number of Try-Finally (without catch) 188
Number of Methods with Finally (nMF) 267 / 18140 (1.5%)
Number of Finally with a Continue 1
Number of Finally with a Return 1
Number of Finally with a Throw 0
Number of Finally with a Break 1
Number of different exception types thrown 36
Number of Domain exception types thrown 20
Number of different exception types caught 64
Number of Domain exception types caught 23
Number of exception declarations in signatures 1441
Number of different exceptions types declared in method signatures 17
Number of library exceptions types declared in method signatures 11
Number of Domain exceptions types declared in method signatures 6
Number of Catch with a continue 13
Number of Catch with a return 297
Number of Catch with a Break 13
nbIf = Number of If 34646
nbFor = Number of For 4490
Number of Method with an if 8394 / 18140
Number of Methods with a for 2689 / 18140
Number of Method starting with a try 155 / 18140 (0.9%)
Number of Expressions 317930
Number of Expressions in try 30581 (9.6%)