org.eclipse.jdt.internal.compiler.ClassFile Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.ClassFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestorWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see ICodeSnippetRequestor
 */
public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) {
	int length = classFiles.length;
	byte[][] classFileBytes = new byte[length][];
	String[][] compoundNames = new String[length][];
	for (int i = 0; i < length; i++) {
		ClassFile classFile = classFiles[i];
		classFileBytes[i] = classFile.getBytes();
		char[][] classFileCompundName = classFile.getCompoundName();
		int length2 = classFileCompundName.length;
		String[] compoundName = new String[length2];
		for (int j = 0; j < length2; j++){
			compoundName[j] = new String(classFileCompundName[j]);
		}
		compoundNames[i] = compoundName;
	}
	return this.requestor.acceptClassFiles(classFileBytes, compoundNames, codeSnippetClassName == null ? null : new String(codeSnippetClassName));
}
 
Example #2
Source File: StackMapFrameCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void reset(ClassFile givenClassFile) {
	super.reset(givenClassFile);
	this.stateIndexesCounter = 0;
	if (this.framePositions != null) {
		this.framePositions.clear();
	}
	if (this.exceptionMarkers != null) {
		this.exceptionMarkers.clear();
	}
	if (this.stackDepthMarkers != null) {
		this.stackDepthMarkers.clear();
	}
	if (this.stackMarkers != null) {
		this.stackMarkers.clear();
	}
}
 
Example #3
Source File: StackMapFrameCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void init(ClassFile targetClassFile) {
	super.init(targetClassFile);
	this.stateIndexesCounter = 0;
	if (this.framePositions != null) {
		this.framePositions.clear();
	}
	if (this.exceptionMarkers != null) {
		this.exceptionMarkers.clear();
	}
	if (this.stackDepthMarkers != null) {
		this.stackDepthMarkers.clear();
	}
	if (this.stackMarkers != null) {
		this.stackMarkers.clear();
	}
}
 
Example #4
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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();
	}
}
 
Example #5
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
private void writeClassFile(Resource<File> input, String relativeStringName, ClassFile classFile) throws IOException {
  final byte[] bytes = classFile.getBytes();
  final File outputFile = new File(getOutputDirectory(), relativeStringName);

  // context.associatedOutput resets output attributes set during earlier iterations of this incremental compile
  // so deal with classfile digest before context.associatedOutput
  final byte[] oldHash = context.getAttribute(outputFile, ATTR_CLASS_DIGEST, byte[].class);
  final byte[] hash = digestClassFile(outputFile, bytes);
  boolean significantChange = oldHash == null || hash == null || !Arrays.equals(hash, oldHash);

  final Output<File> output = context.associatedOutput(input, outputFile);

  if (hash != null) {
    // TODO evaluate if this is useful
    // trade-off is between storing digest on disk between builds
    // and recomputing the hash each time class files are written
    context.setAttribute(outputFile, ATTR_CLASS_DIGEST, hash);
  }

  if (significantChange) {
    // find all sources that reference this type and put them into work queue
    strategy.addDependentsOf(CharOperation.toString(classFile.getCompoundName()));
  }

  try (final BufferedOutputStream os = new BufferedOutputStream(output.newOutputStream())) {
    os.write(bytes);
    os.flush();
  }
}
 
Example #6
Source File: ConstantPool.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void initialize(ClassFile givenClassFile) {
	this.poolContent = givenClassFile.header;
	this.currentOffset = givenClassFile.headerOffset;
	// currentOffset is initialized to 0 by default
	this.currentIndex = 1;
	this.classFile = givenClassFile;
}
 
Example #7
Source File: ConstantPool.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * ConstantPool constructor comment.
 */
public ConstantPool(ClassFile classFile) {
	this.UTF8Cache = new CharArrayCache(UTF8_INITIAL_SIZE);
	this.stringCache = new CharArrayCache(STRING_INITIAL_SIZE);
	this.methodsAndFieldsCache = new HashtableOfObject(METHODS_AND_FIELDS_INITIAL_SIZE);
	this.classCache = new CharArrayCache(CLASS_INITIAL_SIZE);
	this.nameAndTypeCacheForFieldsAndMethods = new HashtableOfObject(NAMEANDTYPE_INITIAL_SIZE);
	this.offsets = new int[5];
	initialize(classFile);
}
 
Example #8
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
	 * outputPath is formed like:
	 *	   c:\temp\ the last character is a file separator
	 * relativeFileName is formed like:
	 *     java\lang\String.class
	 * @param generatePackagesStructure a flag to know if the packages structure has to be generated.
	 * @param outputPath the given output directory
	 * @param relativeFileName the given relative file name
	 * @param classFile the given classFile to write
	 *
	 */
	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();
		}
	}
 
Example #9
Source File: CompilationUnitDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void cleanUp() {
	if (this.types != null) {
		for (int i = 0, max = this.types.length; i < max; i++) {
			cleanUp(this.types[i]);
		}
		for (int i = 0, max = this.localTypeCount; i < max; i++) {
		    LocalTypeBinding localType = this.localTypes[i];
			// null out the type's scope backpointers
			localType.scope = null; // local members are already in the list
			localType.enclosingCase = null;
		}
	}

	this.compilationResult.recoveryScannerData = null; // recovery is already done

	ClassFile[] classFiles = this.compilationResult.getClassFiles();
	for (int i = 0, max = classFiles.length; i < max; i++) {
		// clear the classFile back pointer to the bindings
		ClassFile classFile = classFiles[i];
		// null out the classfile backpointer to a type binding
		classFile.referenceBinding = null;
		classFile.innerClassesBindings = null;
		classFile.bootstrapMethods = null;
		classFile.missingTypes = null;
		classFile.visitedTypes = null;
	}

	this.suppressWarningAnnotations = null;
}
 
Example #10
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void generateCode(ClassScope classScope, ClassFile classFile) {
	int problemResetPC = 0;
	classFile.codeStream.wideMode = false;
	boolean restart = false;
	do {
		try {
			problemResetPC = classFile.contentsOffset;
			this.generateCode(classFile);
			restart = false;
		} catch (AbortMethod e) {
			// Restart code generation if possible ...
			if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
				// a branch target required a goto_w, restart code generation in wide mode.
				classFile.contentsOffset = problemResetPC;
				classFile.methodCount--;
				classFile.codeStream.resetInWideMode(); // request wide mode
				restart = true;
			} else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
				classFile.contentsOffset = problemResetPC;
				classFile.methodCount--;
				classFile.codeStream.resetForCodeGenUnusedLocals();
				restart = true;
			} else {
				throw new AbortType(this.compilationResult, e.problem);
			}
		}
	} while (restart);
}
 
Example #11
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 */
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;
	}
}
 
Example #12
Source File: VariablesInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new variables info.
 * The name of the global variable class is the simple name of this class.
 * The package name can be null if the variables have been defined in the default package.
 */
public VariablesInfo(char[] packageName, char[] className, ClassFile[] classFiles, GlobalVariable[] variables, int variableCount) {
	this.packageName = packageName;
	this.className = className;
	this.classFiles = classFiles;
	this.variables = variables;
	this.variableCount = variableCount;
}
 
Example #13
Source File: StackMapFrameCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public StackMapFrameCodeStream(ClassFile givenClassFile) {
	super(givenClassFile);
	this.generateAttributes |= ClassFileConstants.ATTR_STACK_MAP;
}
 
Example #14
Source File: JRJdtCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void acceptResult(CompilationResult result) 
{
	String className = ((CompilationUnit) result.getCompilationUnit()).className;
	
	int classIdx;
	for (classIdx = 0; classIdx < units.length; ++classIdx)
	{
		if (className.equals(units[classIdx].getName()))
		{
			break;
		}
	}
	
	if (result.hasErrors()) 
	{
		//IProblem[] problems = result.getErrors();
		IProblem[] problems = getJavaCompilationErrors(result);
		
		unitResults[classIdx].problems = problems;

		String sourceCode = units[classIdx].getSourceCode();
		
		for (int i = 0; i < problems.length; i++) 
		{
			IProblem problem = problems[i];

			if (IProblem.UndefinedMethod == problem.getID())
			{
				if (
					problem.getSourceStart() >= 0
					&& problem.getSourceEnd() >= 0
					)
				{									
					String methodName = 
						sourceCode.substring(
							problem.getSourceStart(),
							problem.getSourceEnd() + 1
							);
					
					Method method = FunctionsUtil.getInstance(jasperReportsContext).getMethod4Function(methodName);
					if (method != null)
					{
						unitResults[classIdx].addMissingMethod(method);
						//continue;
					}
				}
			}
		}
	}
	else
	{
		ClassFile[] resultClassFiles = result.getClassFiles();
		for (int i = 0; i < resultClassFiles.length; i++) 
		{
			units[classIdx].setCompileData(resultClassFiles[i].getBytes());
		}
	}
}
 
Example #15
Source File: CompilerJdt.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void acceptResult(CompilationResult result) {
  if (result == null) {
    return; // ah?
  }

  final String sourceName = new String(result.getFileName());
  final File sourceFile = new File(sourceName);

  Resource<File> input = context.getProcessedSource(sourceFile);

  // track type references
  if (result.rootReferences != null && result.qualifiedReferences != null && result.simpleNameReferences != null) {
    context.setAttribute(input.getResource(), ATTR_REFERENCES, new ReferenceCollection(result.rootReferences, result.qualifiedReferences, result.simpleNameReferences));
  }

  if (result.hasProblems()) {
    for (CategorizedProblem problem : result.getProblems()) {
      if (problem.isError() || isShowWarnings()) {
        MessageSeverity severity = problem.isError() ? MessageSeverity.ERROR : MessageSeverity.WARNING;
        input.addMessage(problem.getSourceLineNumber(), ((DefaultProblem) problem).column, problem.getMessage(), severity, null /* cause */);
      }
    }
  }

  try {
    if (!result.hasErrors() && !isProcOnly()) {
      for (ClassFile classFile : result.getClassFiles()) {
        char[] filename = classFile.fileName();
        int length = filename.length;
        char[] relativeName = new char[length + 6];
        System.arraycopy(filename, 0, relativeName, 0, length);
        System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6);
        CharOperation.replace(relativeName, '/', File.separatorChar);
        String relativeStringName = new String(relativeName);
        writeClassFile(input, relativeStringName, classFile);
      }
    }
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  // XXX double check affected sources are recompiled when this source has errors
}
 
Example #16
Source File: ProgramVariantCompilationResult.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public void setCompilationList(List<ClassFile> compilationList) {
	this.compilationList = compilationList;
}
 
Example #17
Source File: ProgramVariantCompilationResult.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public List<ClassFile> getCompilationList() {
	return compilationList;
}
 
Example #18
Source File: ProgramVariantCompilationResult.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public ProgramVariantCompilationResult(List<ClassFile> comp, Set<String> error, CtClass ctCl,String generatedSourceCode) {
	this.compilationList = comp;
	this.error = error; 
	this.compiledCtType = ctCl;
	this.generatedSourceCode = generatedSourceCode;
}
 
Example #19
Source File: ProgramVariantCompilationResult.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public ProgramVariantCompilationResult(List<ClassFile> comp, Set<String> error, CtClass ctCl) {
	this.compilationList = comp;
	this.error = error; 
	this.compiledCtType = ctCl;
}
 
Example #20
Source File: BatchImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void acceptSecondaryType(ClassFile classFile) {
	if (this.secondaryTypes != null)
		this.secondaryTypes.add(classFile.fileName());
}
 
Example #21
Source File: CodeSnippetClassFile.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * INTERNAL USE-ONLY
 * Request the creation of a ClassFile compatible representation of a problematic type
 *
 * @param typeDeclaration org.eclipse.jdt.internal.compiler.ast.TypeDeclaration
 * @param unitResult org.eclipse.jdt.internal.compiler.CompilationUnitResult
 */
public static void createProblemType(TypeDeclaration typeDeclaration, CompilationResult unitResult) {
	SourceTypeBinding typeBinding = typeDeclaration.binding;
	ClassFile classFile = new CodeSnippetClassFile(typeBinding, null, true);

	// inner attributes
	if (typeBinding.hasMemberTypes()) {
		// see bug 180109
		ReferenceBinding[] members = typeBinding.memberTypes;
		for (int i = 0, l = members.length; i < l; i++)
			classFile.recordInnerClasses(members[i]);
	}
	// TODO (olivier) handle cases where a field cannot be generated (name too long)
	// TODO (olivier) handle too many methods
	// inner attributes
	if (typeBinding.isNestedType()) {
		classFile.recordInnerClasses(typeBinding);
	}
	TypeVariableBinding[] typeVariables = typeBinding.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);
		}
	}

	// add its fields
	FieldBinding[] fields = typeBinding.fields();
	if ((fields != null) && (fields != Binding.NO_FIELDS)) {
		classFile.addFieldInfos();
	} else {
		// we have to set the number of fields to be equals to 0
		classFile.contents[classFile.contentsOffset++] = 0;
		classFile.contents[classFile.contentsOffset++] = 0;
	}
	// leave some space for the methodCount
	classFile.setForMethodInfos();
	// add its user defined methods
	int problemsLength;
	CategorizedProblem[] problems = unitResult.getErrors();
	if (problems == null) {
		problems = new CategorizedProblem[0];
	}
	CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
	System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
	AbstractMethodDeclaration[] methodDecls = typeDeclaration.methods;
	boolean abstractMethodsOnly = false;
	if (methodDecls != null) {
		if (typeBinding.isInterface()) {
			if (typeBinding.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_8)
				abstractMethodsOnly = true;
			// We generate a clinit which contains all the problems, since we may not be able to generate problem methods (< 1.8) and problem constructors (all levels).
			classFile.addProblemClinit(problemsCopy);
		}
		for (int i = 0, length = methodDecls.length; i < length; i++) {
			AbstractMethodDeclaration methodDecl = methodDecls[i];
			MethodBinding method = methodDecl.binding;
			if (method == null) continue;
			if (abstractMethodsOnly) {
				method.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract;
			}
			if (method.isConstructor()) {
				if (typeBinding.isInterface()) continue;
				classFile.addProblemConstructor(methodDecl, method, problemsCopy);
			} else if (method.isAbstract()) {
				classFile.addAbstractMethod(methodDecl, method);
			} else {
				classFile.addProblemMethod(methodDecl, method, problemsCopy);
			}
		}
		// add abstract methods
		classFile.addDefaultAbstractMethods();
	}
	// propagate generation of (problem) member types
	if (typeDeclaration.memberTypes != null) {
		for (int i = 0, max = typeDeclaration.memberTypes.length; i < max; i++) {
			TypeDeclaration memberType = typeDeclaration.memberTypes[i];
			if (memberType.binding != null) {
				ClassFile.createProblemType(memberType, unitResult);
			}
		}
	}
	classFile.addAttributes();
	unitResult.record(typeBinding.constantPoolName(), classFile);
}
 
Example #22
Source File: AnnotationMethodDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void generateCode(ClassFile classFile) {
	classFile.generateMethodInfoHeader(this.binding);
	int methodAttributeOffset = classFile.contentsOffset;
	int attributeNumber = classFile.generateMethodInfoAttributes(this.binding, this);
	classFile.completeMethodInfo(this.binding, methodAttributeOffset, attributeNumber);
}
 
Example #23
Source File: CodeSnippetTypeDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Generic bytecode generation for type
 */
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);
	}
}
 
Example #24
Source File: TypeAnnotationCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void init(ClassFile targetClassFile) {
	super.init(targetClassFile);
	this.allTypeAnnotationContexts = new ArrayList();
}
 
Example #25
Source File: TypeAnnotationCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void reset(ClassFile givenClassFile) {
	super.reset(givenClassFile);
	this.allTypeAnnotationContexts = new ArrayList();
}
 
Example #26
Source File: TypeAnnotationCodeStream.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public TypeAnnotationCodeStream(ClassFile givenClassFile) {
	super(givenClassFile);
	this.generateAttributes |= ClassFileConstants.ATTR_TYPE_ANNOTATION;
	this.allTypeAnnotationContexts = new ArrayList();
}
 
Example #27
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void recordNestedType(ClassFile classFile, TypeBinding typeBinding) {
	if (classFile.visitedTypes == null) {
		classFile.visitedTypes = new HashSet(3);
	} else if (classFile.visitedTypes.contains(typeBinding)) {
		// type is already visited
		return;
	}
	classFile.visitedTypes.add(typeBinding);
	if (typeBinding.isParameterizedType()
			&& ((typeBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0)) {
		ParameterizedTypeBinding parameterizedTypeBinding = (ParameterizedTypeBinding) typeBinding;
		ReferenceBinding genericType = parameterizedTypeBinding.genericType();
		if ((genericType.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
			recordNestedType(classFile, genericType);
		}
		TypeBinding[] arguments = parameterizedTypeBinding.arguments;
		if (arguments != null) {
			for (int j = 0, max2 = arguments.length; j < max2; j++) {
				TypeBinding argument = arguments[j];
				if (argument.isWildcard()) {
					WildcardBinding wildcardBinding = (WildcardBinding) argument;
					TypeBinding bound = wildcardBinding.bound;
					if (bound != null
							&& ((bound.tagBits & TagBits.ContainsNestedTypeReferences) != 0)) {
						recordNestedType(classFile, bound);
					}
					ReferenceBinding superclass = wildcardBinding.superclass();
					if (superclass != null
							&& ((superclass.tagBits & TagBits.ContainsNestedTypeReferences) != 0)) {
						recordNestedType(classFile, superclass);
					}
					ReferenceBinding[] superInterfaces = wildcardBinding.superInterfaces();
					if (superInterfaces != null) {
						for (int k = 0, max3 =  superInterfaces.length; k < max3; k++) {
							ReferenceBinding superInterface = superInterfaces[k];
							if ((superInterface.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
								recordNestedType(classFile, superInterface);
							}
						}
					}
				} else if ((argument.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
					recordNestedType(classFile, argument);
				}
			}
		}
	} else if (typeBinding.isTypeVariable()
			&& ((typeBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0)) {
		TypeVariableBinding typeVariableBinding = (TypeVariableBinding) typeBinding;
		TypeBinding upperBound = typeVariableBinding.upperBound();
		if (upperBound != null && ((upperBound.tagBits & TagBits.ContainsNestedTypeReferences) != 0)) {
			recordNestedType(classFile, upperBound);
		}
		TypeBinding[] upperBounds = typeVariableBinding.otherUpperBounds();
		if (upperBounds != null) {
			for (int k = 0, max3 =  upperBounds.length; k < max3; k++) {
				TypeBinding otherUpperBound = upperBounds[k];
				if ((otherUpperBound.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
					recordNestedType(classFile, otherUpperBound);
				}
			}
		}
	} else if (typeBinding.isNestedType()) {
		classFile.recordInnerClasses(typeBinding);
	}
}
 
Example #28
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 */
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;
	}
}
 
Example #29
Source File: Clinit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Bytecode generation for a <clinit> method
 *
 * @param classScope org.eclipse.jdt.internal.compiler.lookup.ClassScope
 * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile
 */
public void generateCode(ClassScope classScope, ClassFile classFile) {

	int clinitOffset = 0;
	if (this.ignoreFurtherInvestigation) {
		// should never have to add any <clinit> problem method
		return;
	}
	boolean restart = false;
	do {
		try {
			clinitOffset = classFile.contentsOffset;
			this.generateCode(classScope, classFile, clinitOffset);
			restart = false;
		} 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.
				classFile.contentsOffset = clinitOffset;
				classFile.methodCount--;
				classFile.codeStream.resetInWideMode(); // request wide mode
				// restart method generation
				restart = true;
			} 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;
			}
		}
	} while (restart);
}
 
Example #30
Source File: IRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.ICodeSnippetRequestor
 */
boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName);