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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.Expression. 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: AssistParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * If the given ast node is inside an explicit constructor call
 * then wrap it with a fake constructor call.
 * Returns the wrapped completion node or the completion node itself.
 */
protected ASTNode wrapWithExplicitConstructorCallIfNeeded(ASTNode ast) {
	int selector;
	if (ast != null && topKnownElementKind(ASSIST_PARSER) == K_SELECTOR && ast instanceof Expression &&
			(((selector = topKnownElementInfo(ASSIST_PARSER)) == THIS_CONSTRUCTOR) ||
			(selector == SUPER_CONSTRUCTOR))) {
		ExplicitConstructorCall call = new ExplicitConstructorCall(
			(selector == THIS_CONSTRUCTOR) ?
				ExplicitConstructorCall.This :
				ExplicitConstructorCall.Super
		);
		call.arguments = new Expression[] {(Expression)ast};
		call.sourceStart = ast.sourceStart;
		call.sourceEnd = ast.sourceEnd;
		return call;
	} else {
		return ast;
	}
}
 
Example #2
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 #3
Source File: EclipseSingularsRecipes.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** Generates 'this.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */
protected Expression getSize(EclipseNode builderType, char[] name, boolean nullGuard) {
	MessageSend invoke = new MessageSend();
	ThisReference thisRef = new ThisReference(0, 0);
	FieldReference thisDotName = new FieldReference(name, 0L);
	thisDotName.receiver = thisRef;
	invoke.receiver = thisDotName;
	invoke.selector = SIZE_TEXT;
	if (!nullGuard) return invoke;
	
	ThisReference cdnThisRef = new ThisReference(0, 0);
	FieldReference cdnThisDotName = new FieldReference(name, 0L);
	cdnThisDotName.receiver = cdnThisRef;
	NullLiteral nullLiteral = new NullLiteral(0, 0);
	EqualExpression isNull = new EqualExpression(cdnThisDotName, nullLiteral, OperatorIds.EQUAL_EQUAL);
	IntLiteral zeroLiteral = makeIntLiteral(new char[] {'0'}, null);
	ConditionalExpression conditional = new ConditionalExpression(isNull, zeroLiteral, invoke);
	return conditional;
}
 
Example #4
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** Give 2 clones! */
public Expression longToIntForHashCode(Expression ref1, Expression ref2, ASTNode source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	/* (int)(ref >>> 32 ^ ref) */
	IntLiteral int32 = makeIntLiteral("32".toCharArray(), source);
	BinaryExpression higherBits = new BinaryExpression(ref1, int32, OperatorIds.UNSIGNED_RIGHT_SHIFT);
	setGeneratedBy(higherBits, source);
	BinaryExpression xorParts = new BinaryExpression(ref2, higherBits, OperatorIds.XOR);
	setGeneratedBy(xorParts, source);
	TypeReference intRef = TypeReference.baseTypeReference(TypeIds.T_int, 0);
	intRef.sourceStart = pS; intRef.sourceEnd = pE;
	setGeneratedBy(intRef, source);
	CastExpression expr = makeCastExpression(xorParts, intRef, source);
	expr.sourceStart = pS; expr.sourceEnd = pE;
	return expr;
}
 
Example #5
Source File: FlowContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/** During deferred checking re-visit a previously recording unboxing situation. */
protected void checkUnboxing(Scope scope, Expression expression, FlowInfo flowInfo) {
	int status = expression.nullStatus(flowInfo, this);
	if ((status & FlowInfo.NULL) != 0) {
		scope.problemReporter().nullUnboxing(expression, expression.resolvedType);
		return;
	} else if ((status & FlowInfo.POTENTIALLY_NULL) != 0) {
		scope.problemReporter().potentialNullUnboxing(expression, expression.resolvedType);
		return;
	} else if ((status & FlowInfo.NON_NULL) != 0) {
		return;
	}
	// not handled, perhaps our parent will eventually have something to say?
	if (this.parent != null) {
		this.parent.recordUnboxing(scope, expression, FlowInfo.UNKNOWN, flowInfo);
	}
}
 
Example #6
Source File: HandleLog.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public Expression createFactoryParameter(ClassLiteralAccess type, Annotation source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	MessageSend factoryParameterCall = new MessageSend();
	setGeneratedBy(factoryParameterCall, source);
	
	factoryParameterCall.receiver = super.createFactoryParameter(type, source);
	factoryParameterCall.selector = "getName".toCharArray();
	
	factoryParameterCall.nameSourcePosition = p;
	factoryParameterCall.sourceStart = pS;
	factoryParameterCall.sourceEnd = factoryParameterCall.statementEnd = pE;
	
	return factoryParameterCall;
}
 
Example #7
Source File: FlowContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Record that a nullity mismatch was detected against an annotated type reference.
 * @param currentScope scope for error reporting
 * @param expression the expression violating the specification
 * @param providedType the type of the provided value, i.e., either expression or an element thereof (in ForeachStatements)
 * @param expectedType the declared type of the spec'ed variable, for error reporting.
 * @param nullStatus the null status of expression at the current location
 */
public void recordNullityMismatch(BlockScope currentScope, Expression expression, TypeBinding providedType, TypeBinding expectedType, int nullStatus) {
	if (providedType == null) {
		return; // assume type error was already reported
	}
	if (expression.localVariableBinding() != null) { // flowContext cannot yet handle non-localvar expressions (e.g., fields)
		// find the inner-most flowContext that might need deferred handling:
		FlowContext currentContext = this;
		while (currentContext != null) {
			// some flow contexts implement deferred checking, should we participate in that?
			int isInsideAssert = 0x0;
			if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) != 0) {
				isInsideAssert = FlowContext.HIDE_NULL_COMPARISON_WARNING;
			}
			if (currentContext.internalRecordNullityMismatch(expression, providedType, nullStatus, expectedType, ASSIGN_TO_NONNULL | isInsideAssert))
				return;
			currentContext = currentContext.parent;
		}
	}
	// no reason to defer, so report now:
	char[][] annotationName = currentScope.environment().getNonNullAnnotationName();
	currentScope.problemReporter().nullityMismatch(expression, providedType, expectedType, nullStatus, annotationName);
}
 
Example #8
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public IfStatement generateCompareFloatOrDouble(Expression thisRef, Expression otherRef, char[] floatOrDouble, ASTNode source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	/* if (Float.compare(fieldName, other.fieldName) != 0) return false */
	MessageSend floatCompare = new MessageSend();
	floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE;
	setGeneratedBy(floatCompare, source);
	floatCompare.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble);
	floatCompare.selector = "compare".toCharArray();
	floatCompare.arguments = new Expression[] {thisRef, otherRef};
	IntLiteral int0 = makeIntLiteral("0".toCharArray(), source);
	EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, int0, OperatorIds.NOT_EQUAL);
	ifFloatCompareIsNot0.sourceStart = pS; ifFloatCompareIsNot0.sourceEnd = pE;
	setGeneratedBy(ifFloatCompareIsNot0, source);
	FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
	setGeneratedBy(falseLiteral, source);
	ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE);
	setGeneratedBy(returnFalse, source);
	IfStatement ifStatement = new IfStatement(ifFloatCompareIsNot0, returnFalse, pS, pE);
	setGeneratedBy(ifStatement, source);
	return ifStatement;
}
 
Example #9
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void consumeMemberValuePair() {
	if (this.indexOfAssistIdentifier() < 0) {
		super.consumeMemberValuePair();
		return;
	}

	char[] simpleName = this.identifierStack[this.identifierPtr];
	long position = this.identifierPositionStack[this.identifierPtr--];
	this.identifierLengthPtr--;
	int end = (int) position;
	int start = (int) (position >>> 32);
	Expression value = this.expressionStack[this.expressionPtr--];
	this.expressionLengthPtr--;
	MemberValuePair memberValuePair = new SelectionOnNameOfMemberValuePair(simpleName, start, end, value);
	pushOnAstStack(memberValuePair);

	this.assistNode = memberValuePair;
	this.lastCheckPoint = memberValuePair.sourceEnd + 1;


}
 
Example #10
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected MessageSend newMessageSendWithTypeArguments() {
	char[] selector = this.identifierStack[this.identifierPtr];
	if (selector != assistIdentifier()){
		return super.newMessageSendWithTypeArguments();
	}
	MessageSend messageSend = new SelectionOnMessageSend();
	int length;
	if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
		this.expressionPtr -= length;
		System.arraycopy(
			this.expressionStack,
			this.expressionPtr + 1,
			messageSend.arguments = new Expression[length],
			0,
			length);
	}
	this.assistNode = messageSend;
	if (!this.diet){
		this.restartRecovery	= true;	// force to restart in recovery mode
		this.lastIgnoredToken = -1;
	}

	this.isOrphanCompletionNode = true;
	return messageSend;
}
 
Example #11
Source File: PatchDelegate.java    From EasyMPermission with MIT License 5 votes vote down vote up
public Expression get(final ASTNode source, char[] name) {
	FieldReference fieldRef = new FieldReference(name, pos(source));
	setGeneratedBy(fieldRef, source);
	fieldRef.receiver = new ThisReference(source.sourceStart, source.sourceEnd);
	setGeneratedBy(fieldRef.receiver, source);
	return fieldRef;
}
 
Example #12
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<SneakyThrows> annotation, Annotation source, EclipseNode annotationNode) {
		handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows");
		
		List<String> exceptionNames = annotation.getRawExpressions("value");
		List<DeclaredException> exceptions = new ArrayList<DeclaredException>();
		
		MemberValuePair[] memberValuePairs = source.memberValuePairs();
		if (memberValuePairs == null || memberValuePairs.length == 0) {
			exceptions.add(new DeclaredException("java.lang.Throwable", source));
		} else {
			Expression arrayOrSingle = memberValuePairs[0].value;
			final Expression[] exceptionNameNodes;
			if (arrayOrSingle instanceof ArrayInitializer) {
				exceptionNameNodes = ((ArrayInitializer)arrayOrSingle).expressions;
			} else exceptionNameNodes = new Expression[] { arrayOrSingle };
			
			if (exceptionNames.size() != exceptionNameNodes.length) {
				annotationNode.addError(
						"LOMBOK BUG: The number of exception classes in the annotation isn't the same pre- and post- guessing.");
			}
			
			int idx = 0;
			for (String exceptionName : exceptionNames) {
				if (exceptionName.endsWith(".class")) exceptionName = exceptionName.substring(0, exceptionName.length() - 6);
				exceptions.add(new DeclaredException(exceptionName, exceptionNameNodes[idx++]));
			}
		}
		
		
		EclipseNode owner = annotationNode.up();
		switch (owner.getKind()) {
//		case FIELD:
//			return handleField(annotationNode, (FieldDeclaration)owner.get(), exceptions);
		case METHOD:
			handleMethod(annotationNode, (AbstractMethodDeclaration)owner.get(), exceptions);
			break;
		default:
			annotationNode.addError("@SneakyThrows is legal only on methods and constructors.");
		}
	}
 
Example #13
Source File: PatchVal.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static TypeBinding skipResolveInitializerIfAlreadyCalled2(Expression expr, BlockScope scope, LocalDeclaration decl) {
	if (decl != null && LocalDeclaration.class.equals(decl.getClass()) && expr.resolvedType != null) return expr.resolvedType;
	try {
		return expr.resolveType(scope);
	} catch (NullPointerException e) {
		return null;
	}
}
 
Example #14
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 #15
Source File: ConstraintExpressionFormula.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean canBePolyExpression(Expression expr) {
	// when inferring compatibility against a right type, the check isPolyExpression 
	// must assume that expr occurs in s.t. like an assignment context:
	ExpressionContext previousExpressionContext = expr.getExpressionContext();
	if (previousExpressionContext == ExpressionContext.VANILLA_CONTEXT)
		this.left.setExpressionContext(ExpressionContext.ASSIGNMENT_CONTEXT);
	try {
		return expr.isPolyExpression();
	} finally {
		expr.setExpressionContext(previousExpressionContext);
	}
}
 
Example #16
Source File: BinaryExpressionFragmentBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean buildFragments(Expression expression) {
	if (((expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT) != 0) {
		addRealFragment(expression);
		return false;
	}
	return true;
}
 
Example #17
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 5 votes vote down vote up
public LocalDeclaration createLocalDeclaration(ASTNode source, char[] dollarFieldName, TypeReference type, Expression initializer) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	LocalDeclaration tempVar = new LocalDeclaration(dollarFieldName, pS, pE);
	setGeneratedBy(tempVar, source);
	tempVar.initialization = initializer;
	tempVar.type = type;
	tempVar.type.sourceStart = pS; tempVar.type.sourceEnd = pE;
	setGeneratedBy(tempVar.type, source);
	tempVar.modifiers = Modifier.FINAL;
	return tempVar;
}
 
Example #18
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 #19
Source File: InferenceContext18.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 18.5.4 More Specific Method Inference
 */
public boolean isMoreSpecificThan(MethodBinding m1, MethodBinding m2, boolean isVarArgs, boolean isVarArgs2) {
	// TODO: we don't yet distinguish vararg-with-passthrough from vararg-with-exactly-one-vararg-arg
	if (isVarArgs != isVarArgs2) {
		return isVarArgs2;
	}
	Expression[] arguments = this.invocationArguments;
	int numInvocArgs = arguments == null ? 0 : arguments.length;
	TypeVariableBinding[] p = m2.typeVariables();
	TypeBinding[] s = m1.parameters;
	TypeBinding[] t = new TypeBinding[m2.parameters.length];
	createInitialBoundSet(p);
	for (int i = 0; i < t.length; i++)
		t[i] = substitute(m2.parameters[i]);

	try {
		for (int i = 0; i < numInvocArgs; i++) {
			TypeBinding si = getParameter(s, i, isVarArgs);
			TypeBinding ti = getParameter(t, i, isVarArgs);
			Boolean result = moreSpecificMain(si, ti, this.invocationArguments[i]);
			if (result == Boolean.FALSE)
				return false;
			if (result == null)
				if (!reduceAndIncorporate(ConstraintTypeFormula.create(si, ti, ReductionResult.SUBTYPE)))
					return false;
		}
		if (t.length == numInvocArgs + 1) {
			TypeBinding skplus1 = getParameter(s, numInvocArgs, true);
			TypeBinding tkplus1 = getParameter(t, numInvocArgs, true);
			if (!reduceAndIncorporate(ConstraintTypeFormula.create(skplus1, tkplus1, ReductionResult.SUBTYPE)))
				return false;
		}
		return solve() != null;
	} catch (InferenceFailureException e) {
		return false;
	}
}
 
Example #20
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 #21
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 #22
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 #23
Source File: Extractor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
static boolean hasSourceRetention(@NonNull Annotation[] annotations) {
    for (Annotation annotation : annotations) {
        String typeName = Extractor.getFqn(annotation);
        if ("java.lang.annotation.Retention".equals(typeName)) {
            MemberValuePair[] pairs = annotation.memberValuePairs();
            if (pairs == null || pairs.length != 1) {
                warning("Expected exactly one parameter passed to @Retention");
                return false;
            }
            MemberValuePair pair = pairs[0];
            Expression value = pair.value;
            if (value instanceof NameReference) {
                NameReference reference = (NameReference) value;
                Binding binding = reference.binding;
                if (binding != null) {
                    if (binding instanceof FieldBinding) {
                        FieldBinding fb = (FieldBinding) binding;
                        if ("SOURCE".equals(new String(fb.name)) &&
                                "java.lang.annotation.RetentionPolicy".equals(
                                        new String(fb.declaringClass.readableName()))) {
                            return true;
                        }
                    }
                }
            }
        }
    }

    return false;
}
 
Example #24
Source File: InferenceContext18.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void acceptPendingPolyArguments(BoundSet acceptedResult, TypeBinding[] parameterTypes, boolean isVarArgs) {
	if (acceptedResult == null || this.invocationArguments == null) return;
	Substitution substitution = getResultSubstitution(acceptedResult);
	for (int i = 0; i < this.invocationArguments.length; i++) {
		TypeBinding targetType = getParameter(parameterTypes, i, isVarArgs);
		if (!targetType.isProperType(true))
			targetType = Scope.substitute(substitution, targetType);
		Expression expression = this.invocationArguments[i];
		if (expression instanceof Invocation) {
			Invocation invocation = (Invocation) expression;
			if (!this.innerPolies.contains(invocation)) {
				MethodBinding method = invocation.binding(targetType, true, this.scope);
				if (method instanceof ParameterizedGenericMethodBinding) {
					ParameterizedGenericMethodBinding previousBinding = (ParameterizedGenericMethodBinding) method;
					InferenceContext18 innerCtx = invocation.getInferenceContext(previousBinding);
					if (innerCtx != null) {
						// we have a non-poly generic invocation, which needs inference but is not connected via innerPolis.
						// Finish that inner inference now (incl. binding updates):
						MethodBinding innerBinding = innerCtx.inferInvocationType(invocation, previousBinding);
						if (!innerBinding.isValidBinding()) {
							innerCtx.reportInvalidInvocation(invocation, innerBinding);
						}
						if (invocation.updateBindings(innerBinding, targetType)) { // only if we are actually improving anything
							ASTNode.resolvePolyExpressionArguments(invocation, innerBinding, this.scope);
						}
					}
				} else if(method instanceof ParameterizedMethodBinding){
					expression.checkAgainstFinalTargetType(targetType, this.scope);
				}
			} else {
				expression.setExpectedType(targetType);
			}
		} else {
			expression.checkAgainstFinalTargetType(targetType, this.scope);
		}
	}
}
 
Example #25
Source File: AndLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(Expression node, MatchingNodeSet nodeSet) {
	int level = IMPOSSIBLE_MATCH;
	for (int i = 0, length = this.patternLocators.length; i < length; i++) {
		int newLevel = this.patternLocators[i].match(node, nodeSet);
		if (newLevel > level) {
			if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
			level = newLevel;
		}
	}
	return level;
}
 
Example #26
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(Expression node, MatchingNodeSet nodeSet) {
	int level = IMPOSSIBLE_MATCH;
	for (int i = 0, length = this.patternLocators.length; i < length; i++) {
		int newLevel = this.patternLocators[i].match(node, nodeSet);
		if (newLevel > level) {
			if (newLevel == ACCURATE_MATCH) return ACCURATE_MATCH;
			level = newLevel;
		}
	}
	return level;
}
 
Example #27
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit internalFormatExpression(String source, int indentationLevel, String lineSeparator, Expression expression, IRegion[] regions, boolean includeComments) {
	if (lineSeparator != null) {
		this.preferences.line_separator = lineSeparator;
	} else {
		this.preferences.line_separator = Util.LINE_SEPARATOR;
	}
	this.preferences.initial_indentation_level = indentationLevel;

	this.newCodeFormatter = new CodeFormatterVisitor(this.preferences, this.options, regions, this.codeSnippetParsingUtil, includeComments);

	TextEdit textEdit = this.newCodeFormatter.format(source, expression);
	return textEdit;
}
 
Example #28
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected MessageSend newMessageSend() {
	// '(' ArgumentListopt ')'
	// the arguments are on the expression stack

	char[] selector = this.identifierStack[this.identifierPtr];
	if (selector != assistIdentifier()){
		return super.newMessageSend();
	}
	MessageSend messageSend = new SelectionOnMessageSend();
	int length;
	if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
		this.expressionPtr -= length;
		System.arraycopy(
			this.expressionStack,
			this.expressionPtr + 1,
			messageSend.arguments = new Expression[length],
			0,
			length);
	}
	this.assistNode = messageSend;
	if (!this.diet){
		this.restartRecovery	= true;	// force to restart in recovery mode
		this.lastIgnoredToken = -1;
	}

	this.isOrphanCompletionNode = true;
	return messageSend;
}
 
Example #29
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit formatExpression(String source, int indentationLevel, String lineSeparator, IRegion[] regions, boolean includeComments) {
	Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true);

	if (expression == null) {
		// a problem occurred while parsing the source
		return null;
	}
	return internalFormatExpression(source, indentationLevel, lineSeparator, expression, regions, includeComments);
}
 
Example #30
Source File: CompletionOnJavadocFieldReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CompletionOnJavadocFieldReference(Expression receiver, int tag, int position, int separatorPos, char[] name) {
	super(null, (((long)position)<<32)+position-1);
	this.receiver = receiver;
	this.tagSourceStart = position;
	this.tagSourceEnd = position;
	this.tagValue = tag;
	this.separatorPosition = separatorPos;
}