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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.AllocationExpression. 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 FieldDeclaration addInstanceVar(ConstructorDeclaration constructor, TypeReference typeReference, TypeDeclaration innerClass) {
    FieldDeclaration field = new FieldDeclaration();
    field.modifiers = AccPrivate | AccStatic | AccFinal;
    field.name = "INSTANCE".toCharArray();

    field.type = typeReference;

    AllocationExpression exp = new AllocationExpression();
    exp.type = typeReference;
    exp.binding = constructor.binding;
    exp.sourceStart = innerClass.sourceStart;
    exp.sourceEnd = innerClass.sourceEnd;

    field.initialization = exp;
    return field;
}
 
Example #2
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 #3
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 #4
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static boolean filterField(FieldDeclaration declaration, boolean skipStatic) {
	// Skip the fake fields that represent enum constants.
	if (declaration.initialization instanceof AllocationExpression &&
			((AllocationExpression)declaration.initialization).enumConstant != null) return false;
	
	if (declaration.type == null) return false;
	
	// Skip fields that start with $
	if (declaration.name.length > 0 && declaration.name[0] == '$') return false;
	
	// Skip static fields.
	if (skipStatic && (declaration.modifiers & ClassFileConstants.AccStatic) != 0) return false;
	
	return true;
}
 
Example #5
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
IMethodBinding resolveConstructor(EnumConstantDeclaration enumConstantDeclaration) {
	org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(enumConstantDeclaration);
	if (node instanceof org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) {
		org.eclipse.jdt.internal.compiler.ast.FieldDeclaration fieldDeclaration = (org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) node;
		if (fieldDeclaration.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT && fieldDeclaration.initialization != null) {
			AllocationExpression allocationExpression = (AllocationExpression) fieldDeclaration.initialization;
			return getMethodBinding(allocationExpression.binding);
		}
	}
	return null;
}
 
Example #6
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
synchronized IMethodBinding resolveConstructor(ClassInstanceCreation expression) {
	org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
	if (node != null && (node.bits & org.eclipse.jdt.internal.compiler.ast.ASTNode.IsAnonymousType) != 0) {
		org.eclipse.jdt.internal.compiler.ast.TypeDeclaration anonymousLocalTypeDeclaration = (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) node;
		return getMethodBinding(anonymousLocalTypeDeclaration.allocation.binding);
	} else if (node instanceof AllocationExpression) {
		return getMethodBinding(((AllocationExpression)node).binding);
	}
	return null;
}
 
Example #7
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
boolean isResolvedTypeInferredFromExpectedType(ClassInstanceCreation classInstanceCreation) {
	Object oldNode = this.newAstToOldAst.get(classInstanceCreation);
	if (oldNode instanceof AllocationExpression) {
		AllocationExpression allocationExpression = (AllocationExpression) oldNode;
		return allocationExpression.inferredReturnType;
	}
	return false;
}
 
Example #8
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void consumeClassInstanceCreationExpressionWithTypeArguments() {
	// ClassInstanceCreationExpression ::= 'new' TypeArguments ClassType '(' ArgumentListopt ')' ClassBodyopt
	AllocationExpression alloc;
	int length;
	if (((length = this.astLengthStack[this.astLengthPtr]) == 1)
		&& (this.astStack[this.astPtr] == null)) {

		if (this.indexOfAssistIdentifier() < 0) {
			super.consumeClassInstanceCreationExpressionWithTypeArguments();
			return;
		}

		//NO ClassBody
		this.astPtr--;
		this.astLengthPtr--;
		alloc = new SelectionOnQualifiedAllocationExpression();
		alloc.sourceEnd = this.endPosition; //the position has been stored explicitly

		if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
			this.expressionPtr -= length;
			System.arraycopy(
				this.expressionStack,
				this.expressionPtr + 1,
				alloc.arguments = new Expression[length],
				0,
				length);
		}

		// trick to avoid creating a selection on type reference
		char [] oldIdent = assistIdentifier();
		setAssistIdentifier(null);
		alloc.type = getTypeReference(0);
		checkForDiamond(alloc.type);

		setAssistIdentifier(oldIdent);

		length = this.genericsLengthStack[this.genericsLengthPtr--];
		this.genericsPtr -= length;
		System.arraycopy(this.genericsStack, this.genericsPtr + 1, alloc.typeArguments = new TypeReference[length], 0, length);
		this.intPtr--; // remove the position of the '<'

		//the default constructor with the correct number of argument
		//will be created and added by the TC (see createsInternalConstructorWithBinding)
		alloc.sourceStart = this.intStack[this.intPtr--];
		pushOnExpressionStack(alloc);

		this.assistNode = alloc;
		this.lastCheckPoint = alloc.sourceEnd + 1;
		if (!this.diet){
			this.restartRecovery	= true;	// force to restart in recovery mode
			this.lastIgnoredToken = -1;
		}
		this.isOrphanCompletionNode = true;
	} else {
		super.consumeClassInstanceCreationExpressionWithTypeArguments();
	}
}
 
Example #9
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
synchronized ITypeBinding resolveExpressionType(Expression expression) {
	try {
		switch(expression.getNodeType()) {
			case ASTNode.CLASS_INSTANCE_CREATION :
				org.eclipse.jdt.internal.compiler.ast.ASTNode astNode = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
				if (astNode instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) {
					// anonymous type case
					org.eclipse.jdt.internal.compiler.ast.TypeDeclaration typeDeclaration = (org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) astNode;
					ITypeBinding typeBinding = this.getTypeBinding(typeDeclaration.binding);
					if (typeBinding != null) {
						return typeBinding;
					}
				} else if (astNode instanceof AllocationExpression) {
					// should be an AllocationExpression
					AllocationExpression allocationExpression = (AllocationExpression) astNode;
					return this.getTypeBinding(allocationExpression.resolvedType);
				}
				break;
			case ASTNode.SIMPLE_NAME :
			case ASTNode.QUALIFIED_NAME :
				return resolveTypeBindingForName((Name) expression);
			case ASTNode.ARRAY_INITIALIZER :
			case ASTNode.ARRAY_CREATION :
			case ASTNode.ASSIGNMENT :
			case ASTNode.POSTFIX_EXPRESSION :
			case ASTNode.PREFIX_EXPRESSION :
			case ASTNode.CAST_EXPRESSION :
			case ASTNode.TYPE_LITERAL :
			case ASTNode.INFIX_EXPRESSION :
			case ASTNode.INSTANCEOF_EXPRESSION :
			case ASTNode.LAMBDA_EXPRESSION:
			case ASTNode.CREATION_REFERENCE:
			case ASTNode.EXPRESSION_METHOD_REFERENCE:
			case ASTNode.TYPE_METHOD_REFERENCE:
			case ASTNode.SUPER_METHOD_REFERENCE :
			case ASTNode.FIELD_ACCESS :
			case ASTNode.SUPER_FIELD_ACCESS :
			case ASTNode.ARRAY_ACCESS :
			case ASTNode.METHOD_INVOCATION :
			case ASTNode.SUPER_METHOD_INVOCATION :
			case ASTNode.CONDITIONAL_EXPRESSION :
			case ASTNode.MARKER_ANNOTATION :
			case ASTNode.NORMAL_ANNOTATION :
			case ASTNode.SINGLE_MEMBER_ANNOTATION :
				org.eclipse.jdt.internal.compiler.ast.Expression compilerExpression = (org.eclipse.jdt.internal.compiler.ast.Expression) this.newAstToOldAst.get(expression);
				if (compilerExpression != null) {
					return this.getTypeBinding(compilerExpression.resolvedType);
				}
				break;
			case ASTNode.STRING_LITERAL :
				if (this.scope != null) {
					return this.getTypeBinding(this.scope.getJavaLangString());
				}
				break;
			case ASTNode.BOOLEAN_LITERAL :
			case ASTNode.NULL_LITERAL :
			case ASTNode.CHARACTER_LITERAL :
			case ASTNode.NUMBER_LITERAL :
				Literal literal = (Literal) this.newAstToOldAst.get(expression);
				if (literal != null) {
					return this.getTypeBinding(literal.literalType(null));
				}
				break;
			case ASTNode.THIS_EXPRESSION :
				ThisReference thisReference = (ThisReference) this.newAstToOldAst.get(expression);
				BlockScope blockScope = (BlockScope) this.astNodesToBlockScope.get(expression);
				if (blockScope != null) {
					return this.getTypeBinding(thisReference.resolveType(blockScope));
				}
				break;
			case ASTNode.PARENTHESIZED_EXPRESSION :
				ParenthesizedExpression parenthesizedExpression = (ParenthesizedExpression) expression;
				return resolveExpressionType(parenthesizedExpression.getExpression());
			case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
				VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression) expression;
				Type type = variableDeclarationExpression.getType();
				if (type != null) {
					return type.resolveBinding();
				}
				break;
		}
	} catch (AbortCompilation e) {
		// handle missing types
	}
	return null;
}
 
Example #10
Source File: SourceElementNotifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void notifySourceElementRequestor(FieldDeclaration fieldDeclaration, TypeDeclaration declaringType) {

	// range check
	boolean isInRange =
				this.initialPosition <= fieldDeclaration.declarationSourceStart
				&& this.eofPosition >= fieldDeclaration.declarationSourceEnd;

	switch(fieldDeclaration.getKind()) {
		case AbstractVariableDeclaration.ENUM_CONSTANT:
			if (this.reportReferenceInfo) {
				// accept constructor reference for enum constant
				if (fieldDeclaration.initialization instanceof AllocationExpression) {
					AllocationExpression alloc = (AllocationExpression) fieldDeclaration.initialization;
					this.requestor.acceptConstructorReference(
						declaringType.name,
						alloc.arguments == null ? 0 : alloc.arguments.length,
						alloc.sourceStart);
				}
			}
			// $FALL-THROUGH$
		case AbstractVariableDeclaration.FIELD:
			int fieldEndPosition = this.sourceEnds.get(fieldDeclaration);
			if (fieldEndPosition == -1) {
				// use the declaration source end by default
				fieldEndPosition = fieldDeclaration.declarationSourceEnd;
			}
			if (isInRange) {
				int currentModifiers = fieldDeclaration.modifiers;

				// remember deprecation so as to not lose it below
				boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0 || hasDeprecatedAnnotation(fieldDeclaration.annotations);

				char[] typeName = null;
				if (fieldDeclaration.type == null) {
					// enum constant
					typeName = declaringType.name;
					currentModifiers |= ClassFileConstants.AccEnum;
				} else {
					// regular field
					typeName = CharOperation.concatWith(fieldDeclaration.type.getParameterizedTypeName(), '.');
				}
				ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo();
				fieldInfo.typeAnnotated = ((fieldDeclaration.bits & ASTNode.HasTypeAnnotations) != 0);
				fieldInfo.declarationStart = fieldDeclaration.declarationSourceStart;
				fieldInfo.name = fieldDeclaration.name;
				fieldInfo.modifiers = deprecated ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
				fieldInfo.type = typeName;
				fieldInfo.nameSourceStart = fieldDeclaration.sourceStart;
				fieldInfo.nameSourceEnd = fieldDeclaration.sourceEnd;
				fieldInfo.categories = (char[][]) this.nodesToCategories.get(fieldDeclaration);
				fieldInfo.annotations = fieldDeclaration.annotations;
				fieldInfo.node = fieldDeclaration;
				this.requestor.enterField(fieldInfo);
			}
			this.visitIfNeeded(fieldDeclaration, declaringType);
			if (isInRange){
				this.requestor.exitField(
					// filter out initializations that are not a constant (simple check)
					(fieldDeclaration.initialization == null
							|| fieldDeclaration.initialization instanceof ArrayInitializer
							|| fieldDeclaration.initialization instanceof AllocationExpression
							|| fieldDeclaration.initialization instanceof ArrayAllocationExpression
							|| fieldDeclaration.initialization instanceof Assignment
							|| fieldDeclaration.initialization instanceof ClassLiteralAccess
							|| fieldDeclaration.initialization instanceof MessageSend
							|| fieldDeclaration.initialization instanceof ArrayReference
							|| fieldDeclaration.initialization instanceof ThisReference) ?
						-1 :
						fieldDeclaration.initialization.sourceStart,
					fieldEndPosition,
					fieldDeclaration.declarationSourceEnd);
			}
			break;
		case AbstractVariableDeclaration.INITIALIZER:
			if (isInRange){
				this.requestor.enterInitializer(
					fieldDeclaration.declarationSourceStart,
					fieldDeclaration.modifiers);
			}
			this.visitIfNeeded((Initializer)fieldDeclaration);
			if (isInRange){
				this.requestor.exitInitializer(fieldDeclaration.declarationSourceEnd);
			}
			break;
	}
}
 
Example #11
Source File: BinaryExpressionFragmentBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean visit(
	AllocationExpression allocationExpression,
	BlockScope scope) {
		addRealFragment(allocationExpression);
		return false;
}
 
Example #12
Source File: ThrownExceptionFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void endVisit(AllocationExpression allocationExpression, BlockScope scope) {
	if (allocationExpression.binding != null) {
		endVisitMethodInvocation(allocationExpression.binding);
	}
	super.endVisit(allocationExpression, scope);
}
 
Example #13
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
public ResolvedNode resolve(@NonNull JavaContext context, @NonNull Node node) {
    Object nativeNode = getNativeNode(node);
    if (nativeNode == null) {
        return null;
    }

    if (nativeNode instanceof NameReference) {
        return resolve(((NameReference) nativeNode).binding);
    } else if (nativeNode instanceof TypeReference) {
        return resolve(((TypeReference) nativeNode).resolvedType);
    } else if (nativeNode instanceof MessageSend) {
        return resolve(((MessageSend) nativeNode).binding);
    } else if (nativeNode instanceof AllocationExpression) {
        return resolve(((AllocationExpression) nativeNode).binding);
    } else if (nativeNode instanceof TypeDeclaration) {
        return resolve(((TypeDeclaration) nativeNode).binding);
    } else if (nativeNode instanceof ExplicitConstructorCall) {
        return resolve(((ExplicitConstructorCall) nativeNode).binding);
    } else if (nativeNode instanceof Annotation) {
        AnnotationBinding compilerAnnotation =
                ((Annotation) nativeNode).getCompilerAnnotation();
        if (compilerAnnotation != null) {
            return new EcjResolvedAnnotation(compilerAnnotation);
        }
        return resolve(((Annotation) nativeNode).resolvedType);
    } else if (nativeNode instanceof AbstractMethodDeclaration) {
        return resolve(((AbstractMethodDeclaration) nativeNode).binding);
    } else if (nativeNode instanceof AbstractVariableDeclaration) {
        if (nativeNode instanceof LocalDeclaration) {
            return resolve(((LocalDeclaration) nativeNode).binding);
        } else if (nativeNode instanceof FieldDeclaration) {
            FieldDeclaration fieldDeclaration = (FieldDeclaration) nativeNode;
            if (fieldDeclaration.initialization instanceof AllocationExpression) {
                AllocationExpression allocation =
                        (AllocationExpression)fieldDeclaration.initialization;
                if (allocation.binding != null) {
                    // Field constructor call: this is an enum constant.
                    return new EcjResolvedMethod(allocation.binding);
                }
            }
            return resolve(fieldDeclaration.binding);
        }
    }

    // TODO: Handle org.eclipse.jdt.internal.compiler.ast.SuperReference. It
    // doesn't contain an actual method binding; the parent node call should contain
    // it, but is missing a native node reference; investigate the ECJ bridge's super
    // handling.

    return null;
}
 
Example #14
Source File: SetGeneratedByVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public boolean visit(AllocationExpression node, BlockScope scope) {
	fixPositions(setGeneratedBy(node, source));
	return super.visit(node, scope);
}
 
Example #15
Source File: HandleWither.java    From EasyMPermission with MIT License 4 votes vote down vote up
public MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, EclipseNode sourceNode, List<Annotation> onMethod, List<Annotation> onParam) {
	ASTNode source = sourceNode.get();
	if (name == null) return null;
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	MethodDeclaration method = new MethodDeclaration(parent.compilationResult);
	method.modifiers = modifier;
	method.returnType = cloneSelfType(fieldNode, source);
	if (method.returnType == null) return null;
	
	Annotation[] deprecated = null;
	if (isFieldDeprecated(fieldNode)) {
		deprecated = new Annotation[] { generateDeprecatedAnnotation(source) };
	}
	method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated);
	Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL);
	param.sourceStart = pS; param.sourceEnd = pE;
	method.arguments = new Argument[] { param };
	method.selector = name.toCharArray();
	method.binding = null;
	method.thrownExceptions = null;
	method.typeParameters = null;
	method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	
	List<Expression> args = new ArrayList<Expression>();
	for (EclipseNode child : fieldNode.up().down()) {
		if (child.getKind() != Kind.FIELD) continue;
		FieldDeclaration childDecl = (FieldDeclaration) child.get();
		// Skip fields that start with $
		if (childDecl.name != null && childDecl.name.length > 0 && childDecl.name[0] == '$') continue;
		long fieldFlags = childDecl.modifiers;
		// Skip static fields.
		if ((fieldFlags & ClassFileConstants.AccStatic) != 0) continue;
		// Skip initialized final fields.
		if (((fieldFlags & ClassFileConstants.AccFinal) != 0) && childDecl.initialization != null) continue;
		if (child.get() == fieldNode.get()) {
			args.add(new SingleNameReference(field.name, p));
		} else {
			args.add(createFieldAccessor(child, FieldAccess.ALWAYS_FIELD, source));
		}
	}
	
	AllocationExpression constructorCall = new AllocationExpression();
	constructorCall.arguments = args.toArray(new Expression[0]);
	constructorCall.type = cloneSelfType(fieldNode, source);
	
	Expression identityCheck = new EqualExpression(
			createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source),
			new SingleNameReference(field.name, p),
			OperatorIds.EQUAL_EQUAL);
	ThisReference thisRef = new ThisReference(pS, pE);
	Expression conditional = new ConditionalExpression(identityCheck, thisRef, constructorCall);
	Statement returnStatement = new ReturnStatement(conditional, pS, pE);
	method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
	method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
	
	Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
	List<Statement> statements = new ArrayList<Statement>(5);
	if (nonNulls.length > 0) {
		Statement nullCheck = generateNullCheck(field, sourceNode);
		if (nullCheck != null) statements.add(nullCheck);
	}
	statements.add(returnStatement);
	
	method.statements = statements.toArray(new Statement[0]);
	
	param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0]));
	
	method.traverse(new SetGeneratedByVisitor(source), parent.scope);
	return method;
}
 
Example #16
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 4 votes vote down vote up
/**
 * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the
 * variable name as message.
 * 
 * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}.
 */
public static Statement generateNullCheck(AbstractVariableDeclaration variable, EclipseNode sourceNode) {
	NullCheckExceptionType exceptionType = sourceNode.getAst().readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE);
	if (exceptionType == null) exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION;
	
	ASTNode source = sourceNode.get();
	
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	if (isPrimitive(variable.type)) return null;
	AllocationExpression exception = new AllocationExpression();
	setGeneratedBy(exception, source);
	int partCount = 1;
	String exceptionTypeStr = exceptionType.getExceptionType();
	for (int i = 0; i < exceptionTypeStr.length(); i++) if (exceptionTypeStr.charAt(i) == '.') partCount++;
	long[] ps = new long[partCount];
	Arrays.fill(ps, 0L);
	exception.type = new QualifiedTypeReference(fromQualifiedName(exceptionTypeStr), ps);
	setGeneratedBy(exception.type, source);
	exception.arguments = new Expression[] {
			new StringLiteral(exceptionType.toExceptionMessage(new String(variable.name)).toCharArray(), pS, pE, 0)
	};
	setGeneratedBy(exception.arguments[0], source);
	ThrowStatement throwStatement = new ThrowStatement(exception, pS, pE);
	setGeneratedBy(throwStatement, source);
	
	SingleNameReference varName = new SingleNameReference(variable.name, p);
	setGeneratedBy(varName, source);
	NullLiteral nullLiteral = new NullLiteral(pS, pE);
	setGeneratedBy(nullLiteral, source);
	EqualExpression equalExpression = new EqualExpression(varName, nullLiteral, OperatorIds.EQUAL_EQUAL);
	equalExpression.sourceStart = pS; equalExpression.statementEnd = equalExpression.sourceEnd = pE;
	setGeneratedBy(equalExpression, source);
	Block throwBlock = new Block(0);
	throwBlock.statements = new Statement[] {throwStatement};
	throwBlock.sourceStart = pS; throwBlock.sourceEnd = pE;
	setGeneratedBy(throwBlock, source);
	IfStatement ifStatement = new IfStatement(equalExpression, throwBlock, 0, 0);
	setGeneratedBy(ifStatement, source);
	return ifStatement;
}
 
Example #17
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static boolean isEnumConstant(final FieldDeclaration field) {
	return ((field.initialization instanceof AllocationExpression) && (((AllocationExpression) field.initialization).enumConstant == field));
}
 
Example #18
Source File: HandleConstructor.java    From EasyMPermission with MIT License 4 votes vote down vote up
public MethodDeclaration createStaticConstructor(AccessLevel level, String name, EclipseNode type, Collection<EclipseNode> fields, ASTNode source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	MethodDeclaration constructor = new MethodDeclaration(
			((CompilationUnitDeclaration) type.top().get()).compilationResult);
	
	constructor.modifiers = toEclipseModifier(level) | ClassFileConstants.AccStatic;
	TypeDeclaration typeDecl = (TypeDeclaration) type.get();
	constructor.returnType = EclipseHandlerUtil.namePlusTypeParamsToTypeReference(typeDecl.name, typeDecl.typeParameters, p);
	constructor.annotations = null;
	constructor.selector = name.toCharArray();
	constructor.thrownExceptions = null;
	constructor.typeParameters = copyTypeParams(((TypeDeclaration)type.get()).typeParameters, source);
	constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
	constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;
	
	List<Argument> params = new ArrayList<Argument>();
	List<Expression> assigns = new ArrayList<Expression>();
	AllocationExpression statement = new AllocationExpression();
	statement.sourceStart = pS; statement.sourceEnd = pE;
	statement.type = copyType(constructor.returnType, source);
	
	for (EclipseNode fieldNode : fields) {
		FieldDeclaration field = (FieldDeclaration) fieldNode.get();
		long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd;
		SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos);
		assigns.add(nameRef);
		
		Argument parameter = new Argument(field.name, fieldPos, copyType(field.type, source), Modifier.FINAL);
		parameter.annotations = copyAnnotations(source, findAnnotations(field, NON_NULL_PATTERN), findAnnotations(field, NULLABLE_PATTERN));
		params.add(parameter);
	}
	
	statement.arguments = assigns.isEmpty() ? null : assigns.toArray(new Expression[assigns.size()]);
	constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]);
	constructor.statements = new Statement[] { new ReturnStatement(statement, (int)(p >> 32), (int)p) };
	
	constructor.traverse(new SetGeneratedByVisitor(source), typeDecl.scope);
	return constructor;
}