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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall. 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: 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 #3
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 #4
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
synchronized IMethodBinding resolveConstructor(ConstructorInvocation expression) {
	org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
	if (node instanceof ExplicitConstructorCall) {
		ExplicitConstructorCall explicitConstructorCall = (ExplicitConstructorCall) node;
		return getMethodBinding(explicitConstructorCall.binding);
	}
	return null;
}
 
Example #5
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
synchronized IMethodBinding resolveConstructor(SuperConstructorInvocation expression) {
	org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression);
	if (node instanceof ExplicitConstructorCall) {
		ExplicitConstructorCall explicitConstructorCall = (ExplicitConstructorCall) node;
		return getMethodBinding(explicitConstructorCall.binding);
	}
	return null;
}
 
Example #6
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 #7
Source File: HandleConstructor.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static ConstructorDeclaration createConstructor(
		AccessLevel level, EclipseNode type, Collection<EclipseNode> fields,
		Boolean suppressConstructorProperties, EclipseNode sourceNode, List<Annotation> onConstructor) {
	
	ASTNode source = sourceNode.get();
	TypeDeclaration typeDeclaration = ((TypeDeclaration)type.get());
	long p = (long)source.sourceStart << 32 | source.sourceEnd;
	
	boolean isEnum = (((TypeDeclaration)type.get()).modifiers & ClassFileConstants.AccEnum) != 0;
	
	if (isEnum) level = AccessLevel.PRIVATE;
	
	if (suppressConstructorProperties == null) {
		if (fields.isEmpty()) {
			suppressConstructorProperties = false;
		} else {
			suppressConstructorProperties = Boolean.TRUE.equals(type.getAst().readConfiguration(ConfigurationKeys.ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES));
		}
	}
	
	ConstructorDeclaration constructor = new ConstructorDeclaration(
			((CompilationUnitDeclaration) type.top().get()).compilationResult);
	
	constructor.modifiers = toEclipseModifier(level);
	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;
	
	List<Argument> params = new ArrayList<Argument>();
	List<Statement> assigns = new ArrayList<Statement>();
	List<Statement> nullChecks = new ArrayList<Statement>();
	
	for (EclipseNode fieldNode : fields) {
		FieldDeclaration field = (FieldDeclaration) fieldNode.get();
		char[] rawName = field.name;
		char[] fieldName = removePrefixFromField(fieldNode);
		FieldReference thisX = new FieldReference(rawName, p);
		thisX.receiver = new ThisReference((int)(p >> 32), (int)p);
		
		SingleNameReference assignmentNameRef = new SingleNameReference(fieldName, p);
		Assignment assignment = new Assignment(thisX, assignmentNameRef, (int)p);
		assignment.sourceStart = (int)(p >> 32); assignment.sourceEnd = assignment.statementEnd = (int)(p >> 32);
		assigns.add(assignment);
		long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd;
		Argument parameter = new Argument(fieldName, fieldPos, copyType(field.type, source), Modifier.FINAL);
		Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
		Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
		if (nonNulls.length != 0) {
			Statement nullCheck = generateNullCheck(field, sourceNode);
			if (nullCheck != null) nullChecks.add(nullCheck);
		}
		parameter.annotations = copyAnnotations(source, nonNulls, nullables);
		params.add(parameter);
	}
	
	nullChecks.addAll(assigns);
	constructor.statements = nullChecks.isEmpty() ? null : nullChecks.toArray(new Statement[nullChecks.size()]);
	constructor.arguments = params.isEmpty() ? null : params.toArray(new Argument[params.size()]);
	
	/* Generate annotations that must  be put on the generated method, and attach them. */ {
		Annotation[] constructorProperties = null;
		if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && level != AccessLevel.PACKAGE && !isLocalType(type)) {
			constructorProperties = createConstructorProperties(source, fields);
		}
		
		constructor.annotations = copyAnnotations(source,
				onConstructor.toArray(new Annotation[0]),
				constructorProperties);
	}
	
	constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope);
	return constructor;
}
 
Example #8
Source File: SetGeneratedByVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public boolean visit(ExplicitConstructorCall node, BlockScope scope) {
	fixPositions(setGeneratedBy(node, source));
	return super.visit(node, scope);
}
 
Example #9
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void consumeMethodInvocationName() {
	// MethodInvocation ::= Name '(' ArgumentListopt ')'

	// when the name is only an identifier...we have a message send to "this" (implicit)

	char[] selector = this.identifierStack[this.identifierPtr];
	int accessMode;
	if(selector == assistIdentifier()) {
		if(CharOperation.equals(selector, SUPER)) {
			accessMode = ExplicitConstructorCall.Super;
		} else if(CharOperation.equals(selector, THIS)) {
			accessMode = ExplicitConstructorCall.This;
		} else {
			super.consumeMethodInvocationName();
			return;
		}
	} else {
		super.consumeMethodInvocationName();
		return;
	}

	final ExplicitConstructorCall constructorCall = new SelectionOnExplicitConstructorCall(accessMode);
	constructorCall.sourceEnd = this.rParenPos;
	constructorCall.sourceStart = (int) (this.identifierPositionStack[this.identifierPtr] >>> 32);
	int length;
	if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
		this.expressionPtr -= length;
		System.arraycopy(this.expressionStack, this.expressionPtr + 1, constructorCall.arguments = new Expression[length], 0, length);
	}

	if (!this.diet){
		pushOnAstStack(constructorCall);
		this.restartRecovery	= true;	// force to restart in recovery mode
		this.lastIgnoredToken = -1;
	} else {
		pushOnExpressionStack(new Expression(){
			public TypeBinding resolveType(BlockScope scope) {
				constructorCall.resolve(scope);
				return null;
			}
			public StringBuffer printExpression(int indent, StringBuffer output) {
				return output;
			}
		});
	}
	this.assistNode = constructorCall;
	this.lastCheckPoint = constructorCall.sourceEnd + 1;
	this.isOrphanCompletionNode = true;
}
 
Example #10
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void consumeMethodInvocationPrimary() {
	//optimize the push/pop
	//MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')'

	char[] selector = this.identifierStack[this.identifierPtr];
	int accessMode;
	if(selector == assistIdentifier()) {
		if(CharOperation.equals(selector, SUPER)) {
			accessMode = ExplicitConstructorCall.Super;
		} else if(CharOperation.equals(selector, THIS)) {
			accessMode = ExplicitConstructorCall.This;
		} else {
			super.consumeMethodInvocationPrimary();
			return;
		}
	} else {
		super.consumeMethodInvocationPrimary();
		return;
	}

	final ExplicitConstructorCall constructorCall = new SelectionOnExplicitConstructorCall(accessMode);
	constructorCall.sourceEnd = this.rParenPos;
	int length;
	if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
		this.expressionPtr -= length;
		System.arraycopy(this.expressionStack, this.expressionPtr + 1, constructorCall.arguments = new Expression[length], 0, length);
	}
	constructorCall.qualification = this.expressionStack[this.expressionPtr--];
	constructorCall.sourceStart = constructorCall.qualification.sourceStart;

	if (!this.diet){
		pushOnAstStack(constructorCall);
		this.restartRecovery	= true;	// force to restart in recovery mode
		this.lastIgnoredToken = -1;
	} else {
		pushOnExpressionStack(new Expression(){
			public TypeBinding resolveType(BlockScope scope) {
				constructorCall.resolve(scope);
				return null;
			}
			public StringBuffer printExpression(int indent, StringBuffer output) {
				return output;
			}
		});
	}

	this.assistNode = constructorCall;
	this.lastCheckPoint = constructorCall.sourceEnd + 1;
	this.isOrphanCompletionNode = true;
}
 
Example #11
Source File: AssistParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Parse the block statements inside the given constructor declaration and try to complete at the
 * cursor location.
 */
public void parseBlockStatements(ConstructorDeclaration cd, CompilationUnitDeclaration unit) {
	//only parse the method body of cd
	//fill out its statements

	//convert bugs into parse error

	initialize();
	// set the lastModifiers to reflect the modifiers of the constructor whose
	// block statements are being parsed
	// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=202634
	this.lastModifiers = cd.modifiers;
	this.lastModifiersStart = cd.modifiersSourceStart;
	// simulate goForConstructorBody except that we don't want to balance brackets because they are not going to be balanced
	goForBlockStatementsopt();

	this.referenceContext = cd;
	this.compilationUnit = unit;

	this.scanner.resetTo(cd.bodyStart, bodyEnd(cd));
	consumeNestedMethod();
	try {
		parse();
	} catch (AbortCompilation ex) {
		this.lastAct = ERROR_ACTION;
	}

	if (this.lastAct == ERROR_ACTION) {
		cd.bits |= ASTNode.HasSyntaxErrors;
		return;
	}

	// attach the statements as we might be searching for a reference to a local type
	cd.explicitDeclarations = this.realBlockStack[this.realBlockPtr--];
	int length;
	if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) {
		this.astPtr -= length;
		if (this.astStack[this.astPtr + 1] instanceof ExplicitConstructorCall)
			//avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ?
			{
			System.arraycopy(
				this.astStack,
				this.astPtr + 2,
				cd.statements = new Statement[length - 1],
				0,
				length - 1);
			cd.constructorCall = (ExplicitConstructorCall) this.astStack[this.astPtr + 1];
		} else { //need to add explicitly the super();
			System.arraycopy(
				this.astStack,
				this.astPtr + 1,
				cd.statements = new Statement[length],
				0,
				length);
			cd.constructorCall = SuperReference.implicitSuperConstructorCall();
		}
	} else {
		cd.constructorCall = SuperReference.implicitSuperConstructorCall();
		if (!containsComment(cd.bodyStart, cd.bodyEnd)) {
			cd.bits |= ASTNode.UndocumentedEmptyBlock;
		}
	}

	if (cd.constructorCall.sourceEnd == 0) {
		cd.constructorCall.sourceEnd = cd.sourceEnd;
		cd.constructorCall.sourceStart = cd.sourceStart;
	}
}