org.eclipse.jdt.internal.compiler.ast.Statement Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.Statement. 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: SingletonEclipseHandler.java    From tutorials with MIT License 6 votes vote down vote up
private void addFactoryMethod(EclipseNode singletonClass, TypeDeclaration astNode, TypeReference typeReference, TypeDeclaration innerClass, FieldDeclaration field) {
    MethodDeclaration factoryMethod = new MethodDeclaration(astNode.compilationResult);
    factoryMethod.modifiers = AccStatic | ClassFileConstants.AccPublic;
    factoryMethod.returnType = typeReference;
    factoryMethod.sourceStart = astNode.sourceStart;
    factoryMethod.sourceEnd = astNode.sourceEnd;
    factoryMethod.selector = "getInstance".toCharArray();
    factoryMethod.bits = ECLIPSE_DO_NOT_TOUCH_FLAG;

    long pS = factoryMethod.sourceStart;
    long pE = factoryMethod.sourceEnd;
    long p = (long) pS << 32 | pE;

    FieldReference ref = new FieldReference(field.name, p);
    ref.receiver = new SingleNameReference(innerClass.name, p);

    ReturnStatement statement = new ReturnStatement(ref, astNode.sourceStart, astNode.sourceEnd);

    factoryMethod.statements = new Statement[]{statement};

    EclipseHandlerUtil.injectMethod(singletonClass, factoryMethod);
}
 
Example #2
Source File: RecoveredBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public RecoveredElement add(Statement stmt, int bracketBalanceValue, boolean delegatedByParent) {
	
	if (stmt instanceof LambdaExpression) // lambdas are recovered up to the containing statement anyways.
		return this;
	
	resetPendingModifiers();

	/* do not consider a nested block starting passed the block end (if set)
		it must be belonging to an enclosing block */
	if (this.blockDeclaration.sourceEnd != 0
			&& stmt.sourceStart > this.blockDeclaration.sourceEnd){
		if (delegatedByParent) return this; //ignore
		return this.parent.add(stmt, bracketBalanceValue);
	}

	RecoveredStatement element = new RecoveredStatement(stmt, this, bracketBalanceValue);
	attach(element);
	if (stmt.sourceEnd == 0) return element;
	return this;
}
 
Example #3
Source File: EclipseAST.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected EclipseNode buildTree(ASTNode node, Kind kind) {
	switch (kind) {
	case COMPILATION_UNIT:
		return buildCompilationUnit((CompilationUnitDeclaration) node);
	case TYPE:
		return buildType((TypeDeclaration) node);
	case FIELD:
		return buildField((FieldDeclaration) node);
	case INITIALIZER:
		return buildInitializer((Initializer) node);
	case METHOD:
		return buildMethod((AbstractMethodDeclaration) node);
	case ARGUMENT:
		return buildLocal((Argument) node, kind);
	case LOCAL:
		return buildLocal((LocalDeclaration) node, kind);
	case STATEMENT:
		return buildStatement((Statement) node);
	case ANNOTATION:
		return buildAnnotation((Annotation) node, false);
	default:
		throw new AssertionError("Did not expect to arrive here: " + kind);
	}
}
 
Example #4
Source File: HandleBuilder.java    From EasyMPermission with MIT License 6 votes vote down vote up
private MethodDeclaration generateCleanMethod(List<BuilderFieldData> builderFields, EclipseNode builderType, ASTNode source) {
	List<Statement> statements = new ArrayList<Statement>();
	
	for (BuilderFieldData bfd : builderFields) {
		if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
			bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, builderType, statements);
		}
	}
	
	FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0);
	thisUnclean.receiver = new ThisReference(0, 0);
	statements.add(new Assignment(thisUnclean, new FalseLiteral(0, 0), 0));
	MethodDeclaration decl = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	decl.selector = CLEAN_METHOD_NAME;
	decl.modifiers = ClassFileConstants.AccPrivate;
	decl.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	decl.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
	decl.statements = statements.toArray(new Statement[0]);
	decl.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
	return decl;
}
 
Example #5
Source File: HandleNonNull.java    From EasyMPermission with MIT License 6 votes vote down vote up
public char[] returnVarNameIfNullCheck(Statement stat) {
	if (!(stat instanceof IfStatement)) return null;
	
	/* Check that the if's statement is a throw statement, possibly in a block. */ {
		Statement then = ((IfStatement) stat).thenStatement;
		if (then instanceof Block) {
			Statement[] blockStatements = ((Block) then).statements;
			if (blockStatements == null || blockStatements.length == 0) return null;
			then = blockStatements[0];
		}
		
		if (!(then instanceof ThrowStatement)) return null;
	}
	
	/* Check that the if's conditional is like 'x == null'. Return from this method (don't generate
	   a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ {
		Expression cond = ((IfStatement) stat).condition;
		if (!(cond instanceof EqualExpression)) return null;
		EqualExpression bin = (EqualExpression) cond;
		int operatorId = ((bin.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT);
		if (operatorId != OperatorIds.EQUAL_EQUAL) return null;
		if (!(bin.left instanceof SingleNameReference)) return null;
		if (!(bin.right instanceof NullLiteral)) return null;
		return ((SingleNameReference) bin.left).token;
	}
}
 
Example #6
Source File: RecoveredType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Statement updatedStatement(int depth, Set knownTypes){

	// ignore closed anonymous type
	if ((this.typeDeclaration.bits & ASTNode.IsAnonymousType) != 0 && !this.preserveContent){
		return null;
	}

	TypeDeclaration updatedType = updatedTypeDeclaration(depth + 1, knownTypes);
	if (updatedType != null && (updatedType.bits & ASTNode.IsAnonymousType) != 0){
		/* in presence of an anonymous type, we want the full allocation expression */
		QualifiedAllocationExpression allocation = updatedType.allocation;

		if (allocation.statementEnd == -1) {
			allocation.statementEnd = updatedType.declarationSourceEnd;
		}
		return allocation;
	}
	return updatedType;
}
 
Example #7
Source File: HandleBuilder.java    From EasyMPermission with MIT License 6 votes vote down vote up
public MethodDeclaration generateBuilderMethod(String builderMethodName, String builderClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long) pS << 32 | pE;
	
	MethodDeclaration out = new MethodDeclaration(
			((CompilationUnitDeclaration) type.top().get()).compilationResult);
	out.selector = builderMethodName.toCharArray();
	out.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic;
	out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	out.returnType = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
	out.typeParameters = copyTypeParams(typeParams, source);
	AllocationExpression invoke = new AllocationExpression();
	invoke.type = namePlusTypeParamsToTypeReference(builderClassName.toCharArray(), typeParams, p);
	out.statements = new Statement[] {new ReturnStatement(invoke, pS, pE)};
	
	out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
	return out;
}
 
Example #8
Source File: RecoveredElement.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public RecoveredElement add(Statement statement, int bracketBalanceValue) {

	/* default behavior is to delegate recording to parent if any */
	resetPendingModifiers();
	if (this.parent == null) return this; // ignore
	if (this instanceof RecoveredType) {
		TypeDeclaration typeDeclaration = ((RecoveredType) this).typeDeclaration;
		if (typeDeclaration != null && (typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { 
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=291040, new X(<SelectOnMessageSend:zoo()>) { ???
			if (statement.sourceStart > typeDeclaration.sourceStart && statement.sourceEnd < typeDeclaration.sourceEnd) {
				return this;
			}
		}
	}
	this.updateSourceEndIfNecessary(previousAvailableLineEnd(statement.sourceStart - 1));
	return this.parent.add(statement, bracketBalanceValue);
}
 
Example #9
Source File: RecoveredInitializer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public RecoveredElement add(Statement statement, int bracketBalanceValue) {

	/* do not consider a statement starting passed the initializer end (if set)
		it must be belonging to an enclosing type */
	if (this.fieldDeclaration.declarationSourceEnd != 0
			&& statement.sourceStart > this.fieldDeclaration.declarationSourceEnd){
		resetPendingModifiers();
		if (this.parent == null) return this; // ignore
		return this.parent.add(statement, bracketBalanceValue);
	}
	/* initializer body should have been created */
	Block block = new Block(0);
	block.sourceStart = ((Initializer)this.fieldDeclaration).sourceStart;
	RecoveredElement element = this.add(block, 1);

	if (this.initializerBody != null) {
		this.initializerBody.attachPendingModifiers(
				this.pendingAnnotations,
				this.pendingAnnotationCount,
				this.pendingModifiers,
				this.pendingModifersSourceStart);
	}
	resetPendingModifiers();

	return element.add(statement, bracketBalanceValue);
}
 
Example #10
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void removeLocals(Statement[] statements, int start, int end) {
	if (statements != null) {
		for (int i = 0; i < statements.length; i++) {
			if (statements[i] instanceof LocalDeclaration) {
				LocalDeclaration localDeclaration = (LocalDeclaration) statements[i];
				int j = indexOfFisrtNameAfter(start);
				done : while (j != -1) {
					int nameStart = this.potentialVariableNameStarts[j];
					if (start <= nameStart && nameStart <= end) {
						if (CharOperation.equals(this.potentialVariableNames[j], localDeclaration.name, false)) {
							removeNameAt(j);
						}
					}

					if (end < nameStart) break done;
					j = indexOfNextName(j);
				}
			}
		}

	}
}
 
Example #11
Source File: EclipseJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void generateMethods(SingularData data, EclipseNode builderType, boolean fluent, boolean chain) {
	if (useGuavaInstead(builderType)) {
		guavaListSetSingularizer.generateMethods(data, builderType, fluent, chain);
		return;
	}
	
	TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generateSingularMethod(returnType, returnStatement, data, builderType, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generatePluralMethod(returnType, returnStatement, data, builderType, fluent);
}
 
Example #12
Source File: EclipseJavaUtilSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, EclipseNode builderType, List<Statement> statements, char[] targetVariableName) {
	if (useGuavaInstead(builderType)) {
		guavaListSetSingularizer.appendBuildCode(data, builderType, statements, targetVariableName);
		return;
	}
	
	if (data.getTargetFqn().equals("java.util.Set")) {
		statements.addAll(createJavaUtilSetMapInitialCapacitySwitchStatements(data, builderType, false, "emptySet", "singleton", "LinkedHashSet"));
	} else {
		statements.addAll(createJavaUtilSimpleCreationAndFillStatements(data, builderType, false, true, false, true, "TreeSet"));
	}
}
 
Example #13
Source File: EclipseGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected Statement createConstructBuilderVarIfNeeded(SingularData data, EclipseNode builderType) {
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	FieldReference thisDotField2 = new FieldReference(data.getPluralName(), 0L);
	thisDotField2.receiver = new ThisReference(0, 0);
	Expression cond = new EqualExpression(thisDotField, new NullLiteral(0, 0), OperatorIds.EQUAL_EQUAL);
	
	MessageSend createBuilderInvoke = new MessageSend();
	char[][] tokenizedName = makeGuavaTypeName(getSimpleTargetTypeName(data), false);
	createBuilderInvoke.receiver = new QualifiedNameReference(tokenizedName, NULL_POSS, 0, 0);
	createBuilderInvoke.selector = getBuilderMethodName(data);
	return new IfStatement(cond, new Assignment(thisDotField2, createBuilderInvoke, 0), 0, 0);
}
 
Example #14
Source File: EclipseGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generatePluralMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	boolean mapMode = isMap();
	
	MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	md.modifiers = ClassFileConstants.AccPublic;
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType));
	
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	MessageSend thisDotFieldDotAddAll = new MessageSend();
	thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)};
	thisDotFieldDotAddAll.receiver = thisDotField;
	thisDotFieldDotAddAll.selector = (mapMode ? "putAll" : "addAll").toCharArray();
	statements.add(thisDotFieldDotAddAll);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	TypeReference paramType;
	if (mapMode) {
		paramType = new QualifiedTypeReference(JAVA_UTIL_MAP, NULL_POSS);
		paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs());
	} else {
		paramType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_ITERABLE, NULL_POSS);
		paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs());
	}
	Argument param = new Argument(data.getPluralName(), 0, paramType, 0);
	md.arguments = new Argument[] {param};
	md.returnType = returnType;
	md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName(mapMode ? "putAll" : "addAll", new String(data.getPluralName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #15
Source File: EclipseGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void generateMethods(SingularData data, EclipseNode builderType, boolean fluent, boolean chain) {
	TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generateSingularMethod(returnType, returnStatement, data, builderType, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generatePluralMethod(returnType, returnStatement, data, builderType, fluent);
}
 
Example #16
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void handleMethod(EclipseNode annotation, AbstractMethodDeclaration method, List<DeclaredException> exceptions) {
	if (method.isAbstract()) {
		annotation.addError("@SneakyThrows can only be used on concrete methods.");
		return;
	}
	
	if (method.statements == null || method.statements.length == 0) {
		boolean hasConstructorCall = false;
		if (method instanceof ConstructorDeclaration) {
			ExplicitConstructorCall constructorCall = ((ConstructorDeclaration) method).constructorCall;
			hasConstructorCall = constructorCall != null && !constructorCall.isImplicitSuper() && !constructorCall.isImplicitThis();
		}
		
		if (hasConstructorCall) {
			annotation.addWarning("Calls to sibling / super constructors are always excluded from @SneakyThrows; @SneakyThrows has been ignored because there is no other code in this constructor.");
		} else {
			annotation.addWarning("This method or constructor is empty; @SneakyThrows has been ignored.");
		}
		
		return;
	}
	
	Statement[] contents = method.statements;
	
	for (DeclaredException exception : exceptions) {
		contents = new Statement[] { buildTryCatchBlock(contents, exception, exception.node, method) };
	}
	
	method.statements = contents;
	annotation.up().rebuild();
}
 
Example #17
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void createPrivateDefaultConstructor(EclipseNode typeNode, EclipseNode sourceNode) {
	ASTNode source = sourceNode.get();
	
	TypeDeclaration typeDeclaration = ((TypeDeclaration) typeNode.get());
	long p = (long) source.sourceStart << 32 | source.sourceEnd;
	
	ConstructorDeclaration constructor = new ConstructorDeclaration(((CompilationUnitDeclaration) typeNode.top().get()).compilationResult);
	
	constructor.modifiers = ClassFileConstants.AccPrivate;
	constructor.selector = typeDeclaration.name;
	constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
	constructor.constructorCall.sourceStart = source.sourceStart;
	constructor.constructorCall.sourceEnd = source.sourceEnd;
	constructor.thrownExceptions = null;
	constructor.typeParameters = null;
	constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
	constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;
	constructor.arguments = null;
	
	AllocationExpression exception = new AllocationExpression();
	setGeneratedBy(exception, source);
	long[] ps = new long[JAVA_LANG_UNSUPPORTED_OPERATION_EXCEPTION.length];
	Arrays.fill(ps, p);
	exception.type = new QualifiedTypeReference(JAVA_LANG_UNSUPPORTED_OPERATION_EXCEPTION, ps);
	setGeneratedBy(exception.type, source);
	exception.arguments = new Expression[] {
			new StringLiteral(UNSUPPORTED_MESSAGE, source.sourceStart, source.sourceEnd, 0)
	};
	setGeneratedBy(exception.arguments[0], source);
	ThrowStatement throwStatement = new ThrowStatement(exception, source.sourceStart, source.sourceEnd);
	setGeneratedBy(throwStatement, source);
	
	constructor.statements = new Statement[] {throwStatement};
	
	injectMethod(typeNode, constructor);
}
 
Example #18
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void doAssignmentCheck0(EclipseNode node, Statement statement, char[] varName) {
	if (statement instanceof Assignment)
		doAssignmentCheck0(node, ((Assignment)statement).expression, varName);
	else if (statement instanceof LocalDeclaration)
		doAssignmentCheck0(node, ((LocalDeclaration)statement).initialization, varName);
	else if (statement instanceof CastExpression)
		doAssignmentCheck0(node, ((CastExpression)statement).expression, varName);
	else if (statement instanceof SingleNameReference) {
		if (Arrays.equals(((SingleNameReference)statement).token, varName)) {
			EclipseNode problemNode = node.getNodeFor(statement);
			if (problemNode != null) problemNode.addWarning(
					"You're assigning an auto-cleanup variable to something else. This is a bad idea.");
		}
	}
}
 
Example #19
Source File: EclipseJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generatePluralMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	md.modifiers = ClassFileConstants.AccPublic;
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType, false));
	
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	MessageSend thisDotFieldDotAddAll = new MessageSend();
	thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)};
	thisDotFieldDotAddAll.receiver = thisDotField;
	thisDotFieldDotAddAll.selector = "addAll".toCharArray();
	statements.add(thisDotFieldDotAddAll);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	TypeReference paramType = new QualifiedTypeReference(TypeConstants.JAVA_UTIL_COLLECTION, NULL_POSS);
	paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs());
	Argument param = new Argument(data.getPluralName(), 0, paramType, 0);
	md.arguments = new Argument[] {param};
	md.returnType = returnType;
	md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName("addAll", new String(data.getPluralName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #20
Source File: EclipseJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void generateMethods(SingularData data, EclipseNode builderType, boolean fluent, boolean chain) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.generateMethods(data, builderType, fluent, chain);
		return;
	}
	
	TypeReference returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	Statement returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generateSingularMethod(returnType, returnStatement, data, builderType, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : TypeReference.baseTypeReference(TypeIds.T_void, 0);
	returnStatement = chain ? new ReturnStatement(new ThisReference(0, 0), 0, 0) : null;
	generatePluralMethod(returnType, returnStatement, data, builderType, fluent);
}
 
Example #21
Source File: EclipseJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, EclipseNode builderType, List<Statement> statements, char[] targetVariableName) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.appendBuildCode(data, builderType, statements, targetVariableName);
		return;
	}
	
	if (data.getTargetFqn().equals("java.util.Map")) {
		statements.addAll(createJavaUtilSetMapInitialCapacitySwitchStatements(data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap"));
	} else {
		statements.addAll(createJavaUtilSimpleCreationAndFillStatements(data, builderType, true, true, false, true, "TreeMap"));
	}
}
 
Example #22
Source File: EclipseJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generateSingularMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	md.modifiers = ClassFileConstants.AccPublic;
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType, false));
	
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	MessageSend thisDotFieldDotAdd = new MessageSend();
	thisDotFieldDotAdd.arguments = new Expression[] {new SingleNameReference(data.getSingularName(), 0L)};
	thisDotFieldDotAdd.receiver = thisDotField;
	thisDotFieldDotAdd.selector = "add".toCharArray();
	statements.add(thisDotFieldDotAdd);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	TypeReference paramType = cloneParamType(0, data.getTypeArgs(), builderType);
	Argument param = new Argument(data.getSingularName(), 0, paramType, 0);
	md.arguments = new Argument[] {param};
	md.returnType = returnType;
	md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName("add", new String(data.getSingularName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #23
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void attachOrphanCompletionNode(){
	if (this.isOrphanCompletionNode){
		ASTNode orphan = this.assistNode;
		this.isOrphanCompletionNode = false;


		/* if in context of a type, then persists the identifier into a fake field return type */
		if (this.currentElement instanceof RecoveredType){
			RecoveredType recoveredType = (RecoveredType)this.currentElement;
			/* filter out cases where scanner is still inside type header */
			if (recoveredType.foundOpeningBrace) {
				/* generate a pseudo field with a completion on type reference */
				if (orphan instanceof TypeReference){
					this.currentElement = this.currentElement.add(new SelectionOnFieldType((TypeReference)orphan), 0);
					return;
				}
			}
		}

		if (orphan instanceof Expression) {
			buildMoreCompletionContext((Expression)orphan);
		} else {
			if (lastIndexOfElement(K_LAMBDA_EXPRESSION_DELIMITER) < 0) { // lambdas are recovered up to the containing expression statement and will carry along the assist node anyways.
				Statement statement = (Statement) orphan;
				this.currentElement = this.currentElement.add(statement, 0);
			}
		}
		if (!isIndirectlyInsideLambdaExpression())
			this.currentToken = 0; // given we are not on an eof, we do not want side effects caused by looked-ahead token
	}
}
 
Example #24
Source File: AssistParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void consumeFieldDeclaration() {
	super.consumeFieldDeclaration();
	if (triggerRecoveryUponLambdaClosure((Statement) this.astStack[this.astPtr], true)) {
		if (this.currentElement instanceof RecoveredType)
			popUntilElement(K_TYPE_DELIMITER);
	}
}
 
Example #25
Source File: RecoveredField.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public RecoveredElement add(Statement statement, int bracketBalanceValue) {

	if (this.alreadyCompletedFieldInitialization || !(statement instanceof Expression)) {
		return super.add(statement, bracketBalanceValue);
	} else {
		if (statement.sourceEnd > 0)
				this.alreadyCompletedFieldInitialization = true;
		// else we may still be inside the initialization, having parsed only a part of it yet
		this.fieldDeclaration.initialization = (Expression)statement;
		this.fieldDeclaration.declarationSourceEnd = statement.sourceEnd;
		this.fieldDeclaration.declarationEnd = statement.sourceEnd;
		return this;
	}
}
 
Example #26
Source File: RecoveredMethod.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public RecoveredElement add(Statement statement, int bracketBalanceValue) {
	resetPendingModifiers();

	/* do not consider a type starting passed the type end (if set)
		it must be belonging to an enclosing type */
	if (this.methodDeclaration.declarationSourceEnd != 0
		&& statement.sourceStart > this.methodDeclaration.declarationSourceEnd){

		if (this.parent == null) {
			return this; // ignore
		} else {
			return this.parent.add(statement, bracketBalanceValue);
		}
	}
	if (this.methodBody == null){
		Block block = new Block(0);
		block.sourceStart = this.methodDeclaration.bodyStart;
		RecoveredElement currentBlock = this.add(block, 1);
		if (this.bracketBalance > 0){
			for (int i = 0; i < this.bracketBalance - 1; i++){
				currentBlock = currentBlock.add(new Block(0), 1);
			}
			this.bracketBalance = 1;
		}
		return currentBlock.add(statement, bracketBalanceValue);
	}
	return this.methodBody.add(statement, bracketBalanceValue, true);
}
 
Example #27
Source File: RecoveredLocalVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public RecoveredElement add(Statement stmt, int bracketBalanceValue) {

	if (this.alreadyCompletedLocalInitialization || !(stmt instanceof Expression)) {
		return super.add(stmt, bracketBalanceValue);
	} else {
		this.alreadyCompletedLocalInitialization = true;
		this.localDeclaration.initialization = (Expression)stmt;
		this.localDeclaration.declarationSourceEnd = stmt.sourceEnd;
		this.localDeclaration.declarationEnd = stmt.sourceEnd;
		return this;
	}
}
 
Example #28
Source File: RecoveredLocalVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Statement updatedStatement(int depth, Set knownTypes){
	/* update annotations */
	if (this.modifiers != 0) {
		this.localDeclaration.modifiers |= this.modifiers;
		if (this.modifiersStart < this.localDeclaration.declarationSourceStart) {
			this.localDeclaration.declarationSourceStart = this.modifiersStart;
		}
	}
	/* update annotations */
	if (this.annotationCount > 0){
		int existingCount = this.localDeclaration.annotations == null ? 0 : this.localDeclaration.annotations.length;
		Annotation[] annotationReferences = new Annotation[existingCount + this.annotationCount];
		if (existingCount > 0){
			System.arraycopy(this.localDeclaration.annotations, 0, annotationReferences, this.annotationCount, existingCount);
		}
		for (int i = 0; i < this.annotationCount; i++){
			annotationReferences[i] = this.annotations[i].updatedAnnotationReference();
		}
		this.localDeclaration.annotations = annotationReferences;

		int start = this.annotations[0].annotation.sourceStart;
		if (start < this.localDeclaration.declarationSourceStart) {
			this.localDeclaration.declarationSourceStart = start;
		}
	}
	return this.localDeclaration;
}
 
Example #29
Source File: RecoveredBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Statement updateStatement(int depth, Set knownTypes){

	// if block was closed or empty, then ignore it
	if (this.blockDeclaration.sourceEnd != 0 || this.statementCount == 0) return null;
	
	/* If this block stands for the lambda body, trash the contents. Lambda expressions are recovered as part of the enclosing statement.
	   We still have left in a block here to make sure that contained elements can be trapped and tossed out.
	*/
	if (this.blockDeclaration.lambdaBody) return null; 

	Statement[] updatedStatements = new Statement[this.statementCount];
	int updatedCount = 0;

	// only collect the non-null updated statements
	for (int i = 0; i < this.statementCount; i++){
		Statement updatedStatement = this.statements[i].updatedStatement(depth, knownTypes);
		if (updatedStatement != null){
			updatedStatements[updatedCount++] = updatedStatement;
		}
	}
	if (updatedCount == 0) return null; // not interesting block

	// resize statement collection if necessary
	if (updatedCount != this.statementCount){
		this.blockDeclaration.statements = new Statement[updatedCount];
		System.arraycopy(updatedStatements, 0, this.blockDeclaration.statements, 0, updatedCount);
	} else {
		this.blockDeclaration.statements = updatedStatements;
	}

	return this.blockDeclaration;
}
 
Example #30
Source File: EclipseASTAdapter.java    From EasyMPermission with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void endVisitStatement(EclipseNode statementNode, Statement statement) {}