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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.MethodDeclaration. 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: RecoveredMethod.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
void attach(TypeParameter[] parameters, int startPos) {
	if(this.methodDeclaration.modifiers != ClassFileConstants.AccDefault) return;

	int lastParameterEnd = parameters[parameters.length - 1].sourceEnd;

	Parser parser = parser();
	Scanner scanner = parser.scanner;
	if(Util.getLineNumber(this.methodDeclaration.declarationSourceStart, scanner.lineEnds, 0, scanner.linePtr)
			!= Util.getLineNumber(lastParameterEnd, scanner.lineEnds, 0, scanner.linePtr)) return;

	if(parser.modifiersSourceStart > lastParameterEnd
			&& parser.modifiersSourceStart < this.methodDeclaration.declarationSourceStart) return;

	if (this.methodDeclaration instanceof MethodDeclaration) {
		((MethodDeclaration)this.methodDeclaration).typeParameters = parameters;
		this.methodDeclaration.declarationSourceStart = startPos;
	} else if (this.methodDeclaration instanceof ConstructorDeclaration){
		((ConstructorDeclaration)this.methodDeclaration).typeParameters = parameters;
		this.methodDeclaration.declarationSourceStart = startPos;
	}
}
 
Example #3
Source File: HandleBuilder.java    From EasyMPermission with MIT License 6 votes vote down vote up
private void makeSimpleSetterMethodForBuilder(EclipseNode builderType, EclipseNode fieldNode, EclipseNode sourceNode, boolean fluent, boolean chain) {
	TypeDeclaration td = (TypeDeclaration) builderType.get();
	AbstractMethodDeclaration[] existing = td.methods;
	if (existing == null) existing = EMPTY;
	int len = existing.length;
	FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
	char[] name = fd.name;
	
	for (int i = 0; i < len; i++) {
		if (!(existing[i] instanceof MethodDeclaration)) continue;
		char[] existingName = existing[i].selector;
		if (Arrays.equals(name, existingName)) return;
	}
	
	String setterName = fluent ? fieldNode.getName() : HandlerUtil.buildAccessorName("set", fieldNode.getName());
	
	MethodDeclaration setter = HandleSetter.createSetter(td, fieldNode, setterName, chain, ClassFileConstants.AccPublic,
			sourceNode, Collections.<Annotation>emptyList(), Collections.<Annotation>emptyList());
	injectMethod(builderType, setter);
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
	Annotation[] annotations = methodDeclaration.annotations;
	if (annotations != null) {
		MethodBinding methodBinding = methodDeclaration.binding;
		if (methodBinding == null) {
			return false;
		}
		((SourceTypeBinding) methodBinding.declaringClass).resolveTypesFor(methodBinding);
		this.resolveAnnotations(
				methodDeclaration.scope,
				annotations,
				methodBinding);
	}
	
	TypeParameter[] typeParameters = methodDeclaration.typeParameters;
	if (typeParameters != null) {
		int typeParametersLength = typeParameters.length;
		for (int i = 0; i < typeParametersLength; i++) {
			typeParameters[i].traverse(this, methodDeclaration.scope);
		}
	}
	
	Argument[] arguments = methodDeclaration.arguments;
	if (arguments != null) {
		int argumentLength = arguments.length;
		for (int i = 0; i < argumentLength; i++) {
			arguments[i].traverse(this, methodDeclaration.scope);
		}
	}
	return false;
}
 
Example #10
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void find(
		char[] startWith,
		Initializer initializer,
		ClassScope scope,
		int from,
		char[][] discouragedNames,
		UnresolvedReferenceNameRequestor nameRequestor) {
	MethodDeclaration fakeMethod =
		this.findAfter(startWith, scope, from, initializer.bodyEnd, MAX_LINE_COUNT, false, discouragedNames, nameRequestor);
	if (fakeMethod != null) fakeMethod.traverse(this, scope);
}
 
Example #11
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void find(
		char[] startWith,
		AbstractMethodDeclaration methodDeclaration,
		int from,
		char[][] discouragedNames,
		UnresolvedReferenceNameRequestor nameRequestor) {
	MethodDeclaration fakeMethod =
		this.findAfter(startWith, methodDeclaration.scope, from, methodDeclaration.bodyEnd, MAX_LINE_COUNT, false, discouragedNames, nameRequestor);
	if (fakeMethod != null) fakeMethod.traverse(this, methodDeclaration.scope.classScope());
}
 
Example #12
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void findAfter(
		char[] startWith,
		Scope scope,
		ClassScope classScope,
		int from,
		int to,
		char[][] discouragedNames,
		UnresolvedReferenceNameRequestor nameRequestor) {
	MethodDeclaration fakeMethod =
		this.findAfter(startWith, scope, from, to, MAX_LINE_COUNT / 2, true, discouragedNames, nameRequestor);
	if (fakeMethod != null) fakeMethod.traverse(this, classScope);
}
 
Example #13
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void findBefore(
		char[] startWith,
		Scope scope,
		ClassScope classScope,
		int from,
		int recordTo,
		int parseTo,
		char[][] discouragedNames,
		UnresolvedReferenceNameRequestor nameRequestor) {
	MethodDeclaration fakeMethod =
		this.findBefore(startWith, scope, from, recordTo, parseTo, MAX_LINE_COUNT / 2, discouragedNames, nameRequestor);
	if (fakeMethod != null) fakeMethod.traverse(this, classScope);
}
 
Example #14
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean visit(MethodDeclaration methodDeclaration, ClassScope classScope) {
	removeLocals(
			methodDeclaration.arguments,
			methodDeclaration.declarationSourceStart,
			methodDeclaration.declarationSourceEnd);
	removeLocals(
			methodDeclaration.statements,
			methodDeclaration.declarationSourceStart,
			methodDeclaration.declarationSourceEnd);
	pushParent(methodDeclaration);
	return true;
}
 
Example #15
Source File: AssistParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parse the block statements inside the given method declaration and try to complete at the
 * cursor location.
 */
public void parseBlockStatements(AbstractMethodDeclaration md, CompilationUnitDeclaration unit) {
	if (md instanceof MethodDeclaration) {
		parseBlockStatements((MethodDeclaration) md, unit);
	} else if (md instanceof ConstructorDeclaration) {
		parseBlockStatements((ConstructorDeclaration) md, unit);
	}
}
 
Example #16
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(MethodDeclaration 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 #17
Source File: AndLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(MethodDeclaration 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 #18
Source File: NodeSearcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean visit(
	MethodDeclaration methodDeclaration,
	ClassScope scope) {

	if (methodDeclaration.declarationSourceStart <= this.position
		&& this.position <= methodDeclaration.declarationSourceEnd) {
			this.found = methodDeclaration;
			return false;
	}
	return true;
}
 
Example #19
Source File: HandleSynchronized.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void preHandle(AnnotationValues<Synchronized> annotation, Annotation source, EclipseNode annotationNode) {
	EclipseNode methodNode = annotationNode.up();
	if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof MethodDeclaration)) return;
	MethodDeclaration method = (MethodDeclaration)methodNode.get();
	if (method.isAbstract()) return;
	
	createLockField(annotation, annotationNode, method.isStatic(), false);
}
 
Example #20
Source File: PatchDelegate.java    From EasyMPermission with MIT License 5 votes vote down vote up
private static void generateDelegateMethods(EclipseNode typeNode, List<BindingTuple> methods, DelegateReceiver delegateReceiver) {
	CompilationUnitDeclaration top = (CompilationUnitDeclaration) typeNode.top().get();
	for (BindingTuple pair : methods) {
		EclipseNode annNode = typeNode.getAst().get(pair.responsible);
		MethodDeclaration method = createDelegateMethod(pair.fieldName, typeNode, pair, top.compilationResult, annNode, delegateReceiver);
		if (method != null) { 
			SetGeneratedByVisitor visitor = new SetGeneratedByVisitor(annNode.get());
			method.traverse(visitor, ((TypeDeclaration)typeNode.get()).scope);
			injectMethod(typeNode, method);
		}
	}
}
 
Example #21
Source File: HandleSetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public void createSetterForField(
		AccessLevel level, EclipseNode fieldNode, EclipseNode sourceNode,
		boolean whineIfExists, List<Annotation> onMethod,
		List<Annotation> onParam) {
	
	ASTNode source = sourceNode.get();
	if (fieldNode.getKind() != Kind.FIELD) {
		sourceNode.addError("@Setter is only supported on a class or a field.");
		return;
	}
	
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	TypeReference fieldType = copyType(field.type, source);
	boolean isBoolean = isBoolean(fieldType);
	String setterName = toSetterName(fieldNode, isBoolean);
	boolean shouldReturnThis = shouldReturnThis(fieldNode);
	
	if (setterName == null) {
		fieldNode.addWarning("Not generating setter for this field: It does not fit your @Accessors prefix list.");
		return;
	}
	
	int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic);
	
	for (String altName : toAllSetterNames(fieldNode, isBoolean)) {
		switch (methodExists(altName, fieldNode, false, 1)) {
		case EXISTS_BY_LOMBOK:
			return;
		case EXISTS_BY_USER:
			if (whineIfExists) {
				String altNameExpl = "";
				if (!altName.equals(setterName)) altNameExpl = String.format(" (%s)", altName);
				fieldNode.addWarning(
					String.format("Not generating %s(): A method with that name already exists%s", setterName, altNameExpl));
			}
			return;
		default:
		case NOT_EXISTS:
			//continue scanning the other alt names.
		}
	}
	
	MethodDeclaration method = createSetter((TypeDeclaration) fieldNode.up().get(), fieldNode, setterName, shouldReturnThis, modifier, sourceNode, onMethod, onParam);
	injectMethod(fieldNode.up(), method);
}
 
Example #22
Source File: EclipseGuavaSingularizer.java    From EasyMPermission with MIT License 4 votes vote down vote up
void generateSingularMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	boolean mapMode = isMap();
	char[] keyName = !mapMode ? data.getSingularName() : (new String(data.getSingularName()) + "$key").toCharArray();
	char[] valueName = !mapMode ? null : (new String(data.getSingularName()) + "$value").toCharArray();
	
	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 thisDotFieldDotAdd = new MessageSend();
	if (mapMode) {
		thisDotFieldDotAdd.arguments = new Expression[] {
				new SingleNameReference(keyName, 0L),
				new SingleNameReference(valueName, 0L)};
	} else {
		thisDotFieldDotAdd.arguments = new Expression[] {new SingleNameReference(keyName, 0L)};
	}
	thisDotFieldDotAdd.receiver = thisDotField;
	thisDotFieldDotAdd.selector = (mapMode ? "put" : "add").toCharArray();
	statements.add(thisDotFieldDotAdd);
	if (returnStatement != null) statements.add(returnStatement);
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	if (mapMode) {
		TypeReference keyType = cloneParamType(0, data.getTypeArgs(), builderType);
		Argument keyParam = new Argument(keyName, 0, keyType, 0);
		TypeReference valueType = cloneParamType(1, data.getTypeArgs(), builderType);
		Argument valueParam = new Argument(valueName, 0, valueType, 0);
		md.arguments = new Argument[] {keyParam, valueParam};
	} else {
		TypeReference paramType = cloneParamType(0, data.getTypeArgs(), builderType);
		Argument param = new Argument(keyName, 0, paramType, 0);
		md.arguments = new Argument[] {param};
	}
	md.returnType = returnType;
	md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName(mapMode ? "put" : "add", new String(data.getSingularName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #23
Source File: MethodVerifier15.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void reportRawReferences(MethodBinding currentMethod, MethodBinding inheritedMethod) {
CompilerOptions compilerOptions = this.type.scope.compilerOptions();
if (compilerOptions.sourceLevel < ClassFileConstants.JDK1_5 // shouldn't whine at all
		|| compilerOptions.reportUnavoidableGenericTypeProblems) { // must have already whined 
	return;
}
AbstractMethodDeclaration methodDecl = currentMethod.sourceMethod();
if (methodDecl == null) return;
TypeBinding [] parameterTypes = currentMethod.parameters;
TypeBinding [] inheritedParameterTypes = inheritedMethod.parameters;
Argument[] arguments = methodDecl.arguments;
for (int j = 0, size = currentMethod.parameters.length; j < size; j++) {
	TypeBinding parameterType = parameterTypes[j];
	TypeBinding inheritedParameterType = inheritedParameterTypes[j];
	Argument arg = arguments[j];
	if (parameterType.leafComponentType().isRawType()) {
		if (inheritedParameterType.leafComponentType().isRawType()) {
			arg.binding.tagBits |= TagBits.ForcedToBeRawType;
		} else {
			if (compilerOptions.getSeverity(CompilerOptions.RawTypeReference) != ProblemSeverities.Ignore
					&& (arg.type.bits & ASTNode.IgnoreRawTypeCheck) == 0) {
				methodDecl.scope.problemReporter().rawTypeReference(arg.type, parameterType);
			}
		}
   	}
   }
TypeReference returnType = null;
if (!methodDecl.isConstructor() && methodDecl instanceof MethodDeclaration && (returnType = ((MethodDeclaration) methodDecl).returnType) != null) {
	final TypeBinding inheritedMethodType = inheritedMethod.returnType;
	final TypeBinding methodType = currentMethod.returnType;
	if (methodType.leafComponentType().isRawType()) {
		if (inheritedMethodType.leafComponentType().isRawType()) {
			// 
		} else {
			if ((returnType.bits & ASTNode.IgnoreRawTypeCheck) == 0
					&& compilerOptions.getSeverity(CompilerOptions.RawTypeReference) != ProblemSeverities.Ignore) {
				methodDecl.scope.problemReporter().rawTypeReference(returnType, methodType);
			}
		}
	}
}
}
 
Example #24
Source File: MethodVerifier15.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
void reportRawReferences() {
	CompilerOptions compilerOptions = this.type.scope.compilerOptions();
	if (compilerOptions.sourceLevel < ClassFileConstants.JDK1_5 // shouldn't whine at all
			|| compilerOptions.reportUnavoidableGenericTypeProblems) { // must have already whined 
		return;
	}
	/* Code below is only for a method that does not override/implement a super type method. If it were to,
	   it would have been handled in checkAgainstInheritedMethods.
	*/
	Object [] methodArray = this.currentMethods.valueTable;
	for (int s = methodArray.length; --s >= 0;) {
		if (methodArray[s] == null) continue;
		MethodBinding[] current = (MethodBinding[]) methodArray[s];
		for (int i = 0, length = current.length; i < length; i++) {
			MethodBinding currentMethod = current[i];
			if ((currentMethod.modifiers & (ExtraCompilerModifiers.AccImplementing | ExtraCompilerModifiers.AccOverriding)) == 0) {
				AbstractMethodDeclaration methodDecl = currentMethod.sourceMethod();
				if (methodDecl == null) return;
				TypeBinding [] parameterTypes = currentMethod.parameters;
				Argument[] arguments = methodDecl.arguments;
				for (int j = 0, size = currentMethod.parameters.length; j < size; j++) {
					TypeBinding parameterType = parameterTypes[j];
					Argument arg = arguments[j];
					if (parameterType.leafComponentType().isRawType()
						&& compilerOptions.getSeverity(CompilerOptions.RawTypeReference) != ProblemSeverities.Ignore
			      		&& (arg.type.bits & ASTNode.IgnoreRawTypeCheck) == 0) {
						methodDecl.scope.problemReporter().rawTypeReference(arg.type, parameterType);
			    	}
				}
				if (!methodDecl.isConstructor() && methodDecl instanceof MethodDeclaration) {
					TypeReference returnType = ((MethodDeclaration) methodDecl).returnType;
					TypeBinding methodType = currentMethod.returnType;
					if (returnType != null) {
						if (methodType.leafComponentType().isRawType()
								&& compilerOptions.getSeverity(CompilerOptions.RawTypeReference) != ProblemSeverities.Ignore
								&& (returnType.bits & ASTNode.IgnoreRawTypeCheck) == 0) {
							methodDecl.scope.problemReporter().rawTypeReference(returnType, methodType);
						}
					}
				}
			}
		}
	}
}
 
Example #25
Source File: HandleConstructor.java    From EasyMPermission with MIT License 4 votes vote down vote up
public void generateConstructor(
		EclipseNode typeNode, AccessLevel level, List<EclipseNode> fields, String staticName, SkipIfConstructorExists skipIfConstructorExists,
		Boolean suppressConstructorProperties, List<Annotation> onConstructor, EclipseNode sourceNode) {
	
	ASTNode source = sourceNode.get();
	boolean staticConstrRequired = staticName != null && !staticName.equals("");
	
	if (skipIfConstructorExists != SkipIfConstructorExists.NO && constructorExists(typeNode) != MemberExistsResult.NOT_EXISTS) return;
	if (skipIfConstructorExists != SkipIfConstructorExists.NO) {
		for (EclipseNode child : typeNode.down()) {
			if (child.getKind() == Kind.ANNOTATION) {
				boolean skipGeneration = (annotationTypeMatches(NoArgsConstructor.class, child) ||
						annotationTypeMatches(AllArgsConstructor.class, child) ||
						annotationTypeMatches(RequiredArgsConstructor.class, child));
				
				if (!skipGeneration && skipIfConstructorExists == SkipIfConstructorExists.YES) {
					skipGeneration = annotationTypeMatches(Builder.class, child);
				}
				
				if (skipGeneration) {
					if (staticConstrRequired) {
						// @Data has asked us to generate a constructor, but we're going to skip this instruction, as an explicit 'make a constructor' annotation
						// will take care of it. However, @Data also wants a specific static name; this will be ignored; the appropriate way to do this is to use
						// the 'staticName' parameter of the @XArgsConstructor you've stuck on your type.
						// We should warn that we're ignoring @Data's 'staticConstructor' param.
						typeNode.addWarning(
								"Ignoring static constructor name: explicit @XxxArgsConstructor annotation present; its `staticName` parameter will be used.",
								source.sourceStart, source.sourceEnd);
					}
					return;
				}
			}
		}
	}
	
	ConstructorDeclaration constr = createConstructor(
			staticConstrRequired ? AccessLevel.PRIVATE : level, typeNode, fields,
			suppressConstructorProperties, sourceNode, onConstructor);
	injectMethod(typeNode, constr);
	if (staticConstrRequired) {
		MethodDeclaration staticConstr = createStaticConstructor(level, staticName, typeNode, fields, source);
		injectMethod(typeNode, staticConstr);
	}
}
 
Example #26
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;
}
 
Example #27
Source File: HandleGetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public void createGetterForField(AccessLevel level,
		EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists, boolean lazy, List<Annotation> onMethod) {
	if (fieldNode.getKind() != Kind.FIELD) {
		errorNode.addError("@Getter is only supported on a class or a field.");
		return;
	}
	
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	if (lazy) {
		if ((field.modifiers & ClassFileConstants.AccPrivate) == 0 || (field.modifiers & ClassFileConstants.AccFinal) == 0) {
			errorNode.addError("'lazy' requires the field to be private and final.");
			return;
		}
		if (field.initialization == null) {
			errorNode.addError("'lazy' requires field initialization.");
			return;
		}
	}
	
	TypeReference fieldType = copyType(field.type, source);
	boolean isBoolean = isBoolean(fieldType);
	String getterName = toGetterName(fieldNode, isBoolean);
	
	if (getterName == null) {
		errorNode.addWarning("Not generating getter for this field: It does not fit your @Accessors prefix list.");
		return;
	}
	
	int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic);
	
	for (String altName : toAllGetterNames(fieldNode, isBoolean)) {
		switch (methodExists(altName, fieldNode, false, 0)) {
		case EXISTS_BY_LOMBOK:
			return;
		case EXISTS_BY_USER:
			if (whineIfExists) {
				String altNameExpl = "";
				if (!altName.equals(getterName)) altNameExpl = String.format(" (%s)", altName);
				errorNode.addWarning(
					String.format("Not generating %s(): A method with that name already exists%s", getterName, altNameExpl));
			}
			return;
		default:
		case NOT_EXISTS:
			//continue scanning the other alt names.
		}
	}
	
	MethodDeclaration method = createGetter((TypeDeclaration) fieldNode.up().get(), fieldNode, getterName, modifier, source, lazy, onMethod);
	
	injectMethod(fieldNode.up(), method);
}
 
Example #28
Source File: HandleGetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public MethodDeclaration createGetter(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, ASTNode source, boolean lazy, List<Annotation> onMethod) {
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	
	// Remember the type; lazy will change it;
	TypeReference returnType = copyType(((FieldDeclaration) fieldNode.get()).type, source);
	
	Statement[] statements;
	if (lazy) {
		statements = createLazyGetterBody(source, fieldNode);
	} else {
		statements = createSimpleGetterBody(source, fieldNode);
	}
	
	MethodDeclaration method = new MethodDeclaration(parent.compilationResult);
	method.modifiers = modifier;
	method.returnType = returnType;
	method.annotations = null;
	method.arguments = null;
	method.selector = name.toCharArray();
	method.binding = null;
	method.thrownExceptions = null;
	method.typeParameters = null;
	method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
	method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
	method.statements = statements;
	
	EclipseHandlerUtil.registerCreatedLazyGetter((FieldDeclaration) fieldNode.get(), method.selector, returnType);
	
	/* Generate annotations that must  be put on the generated method, and attach them. */ {
		Annotation[] deprecated = null;
		if (isFieldDeprecated(fieldNode)) {
			deprecated = new Annotation[] { generateDeprecatedAnnotation(source) };
		}
		
		method.annotations = copyAnnotations(source,
				onMethod.toArray(new Annotation[0]),
				findAnnotations(field, NON_NULL_PATTERN),
				findAnnotations(field, NULLABLE_PATTERN),
				findDelegatesAndMarkAsHandled(fieldNode),
				deprecated);
	}
	
	method.traverse(new SetGeneratedByVisitor(source), parent.scope);
	return method;
}
 
Example #29
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 method declaration and try to complete at the
 * cursor location.
 */
public void parseBlockStatements(MethodDeclaration md, CompilationUnitDeclaration unit) {
	//only parse the method body of md
	//fill out method statements

	//convert bugs into parse error

	if (md.isAbstract())
		return;
	if (md.isNative())
		return;
	if ((md.modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0)
		return;

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

	this.referenceContext = md;
	this.compilationUnit = unit;

	this.scanner.resetTo(md.bodyStart, bodyEnd(md)); // reset the scanner to parser from { down to the cursor location
	consumeNestedMethod();
	try {
		parse();
	} catch (AbortCompilation ex) {
		this.lastAct = ERROR_ACTION;
	} finally {
		this.nestedMethod[this.nestedType]--;
	}

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

	// attach the statements as we might be searching for a reference to a local type
	md.explicitDeclarations = this.realBlockStack[this.realBlockPtr--];
	int length;
	if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) {
		System.arraycopy(
			this.astStack,
			(this.astPtr -= length) + 1,
			md.statements = new Statement[length],
			0,
			length);
	} else {
		if (!containsComment(md.bodyStart, md.bodyEnd)) {
			md.bits |= ASTNode.UndocumentedEmptyBlock;
		}
	}

}
 
Example #30
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 4 votes vote down vote up
private void changeModifiersAndGenerateConstructor(EclipseNode typeNode, EclipseNode annotationNode) {
	TypeDeclaration classDecl = (TypeDeclaration) typeNode.get();
	
	boolean makeConstructor = true;
	
	classDecl.modifiers |= ClassFileConstants.AccFinal;
	
	boolean markStatic = true;
	boolean requiresClInit = false;
	boolean alreadyHasClinit = false;
	
	if (typeNode.up().getKind() == Kind.COMPILATION_UNIT) markStatic = false;
	if (markStatic && typeNode.up().getKind() == Kind.TYPE) {
		TypeDeclaration typeDecl = (TypeDeclaration) typeNode.up().get();
		if ((typeDecl.modifiers & ClassFileConstants.AccInterface) != 0) markStatic = false;
	}
	
	if (markStatic) classDecl.modifiers |= ClassFileConstants.AccStatic;
	
	for (EclipseNode element : typeNode.down()) {
		if (element.getKind() == Kind.FIELD) {
			FieldDeclaration fieldDecl = (FieldDeclaration) element.get();
			if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) == 0) {
				requiresClInit = true;
				fieldDecl.modifiers |= ClassFileConstants.AccStatic;
			}
		} else if (element.getKind() == Kind.METHOD) {
			AbstractMethodDeclaration amd = (AbstractMethodDeclaration) element.get();
			if (amd instanceof ConstructorDeclaration) {
				ConstructorDeclaration constrDecl = (ConstructorDeclaration) element.get();
				if (getGeneratedBy(constrDecl) == null && (constrDecl.bits & ASTNode.IsDefaultConstructor) == 0) {
					element.addError("@UtilityClasses cannot have declared constructors.");
					makeConstructor = false;
					continue;
				}
			} else if (amd instanceof MethodDeclaration) {
				amd.modifiers |= ClassFileConstants.AccStatic;
			} else if (amd instanceof Clinit) {
				alreadyHasClinit = true;
			}
		} else if (element.getKind() == Kind.TYPE) {
			((TypeDeclaration) element.get()).modifiers |= ClassFileConstants.AccStatic;
		}
	}
	
	if (makeConstructor) createPrivateDefaultConstructor(typeNode, annotationNode);
	if (requiresClInit && !alreadyHasClinit) classDecl.addClinit();
}