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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration. 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: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
    Annotation[] annotations = constructorDeclaration.annotations;
    if (hasRelevantAnnotations(annotations)) {
        MethodBinding constructorBinding = constructorDeclaration.binding;
        if (constructorBinding == null) {
            return false;
        }

        String fqn = getFqn(scope);
        ClassKind kind = ClassKind.forType(scope.referenceContext);
        Item item = MethodItem.create(fqn, kind, constructorDeclaration, constructorBinding);
        if (item != null) {
            addItem(fqn, item);
            addAnnotations(annotations, item);
        }
    }

    Argument[] arguments = constructorDeclaration.arguments;
    if (arguments != null) {
        for (Argument argument : arguments) {
            argument.traverse(this, constructorDeclaration.scope);
        }
    }
    return false;
}
 
Example #2
Source File: SingletonEclipseHandler.java    From tutorials with MIT License 6 votes vote down vote up
private ConstructorDeclaration addConstructor(EclipseNode singletonClass, TypeDeclaration astNode) {
    ConstructorDeclaration constructor = new ConstructorDeclaration(astNode.compilationResult);
    constructor.modifiers = AccPrivate;
    constructor.selector = astNode.name;
    constructor.sourceStart = astNode.sourceStart;
    constructor.sourceEnd = astNode.sourceEnd;
    constructor.thrownExceptions = null;
    constructor.typeParameters = null;
    constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = astNode.sourceStart;
    constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = astNode.sourceEnd;
    constructor.arguments = null;

    EclipseHandlerUtil.injectMethod(singletonClass, constructor);
    return constructor;
}
 
Example #3
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 #4
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 #5
Source File: SourceElementNotifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void visitIfNeeded(AbstractMethodDeclaration method) {
	if (this.localDeclarationVisitor != null
		&& (method.bits & ASTNode.HasLocalType) != 0) {
			if (method instanceof ConstructorDeclaration) {
				ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) method;
				if (constructorDeclaration.constructorCall != null) {
					constructorDeclaration.constructorCall.traverse(this.localDeclarationVisitor, method.scope);
				}
			}
			if (method.statements != null) {
				int statementsLength = method.statements.length;
				for (int i = 0; i < statementsLength; i++)
					method.statements[i].traverse(this.localDeclarationVisitor, method.scope);
			}
	}
}
 
Example #6
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * Checks if there is a (non-default) constructor. In case of multiple constructors (overloading), only
 * the first constructor decides if EXISTS_BY_USER or EXISTS_BY_LOMBOK is returned.
 * 
 * @param node Any node that represents the Type (TypeDeclaration) to look in, or any child node thereof.
 */
public static MemberExistsResult constructorExists(EclipseNode node) {
	while (node != null && !(node.get() instanceof TypeDeclaration)) {
		node = node.up();
	}
	
	if (node != null && node.get() instanceof TypeDeclaration) {
		TypeDeclaration typeDecl = (TypeDeclaration)node.get();
		if (typeDecl.methods != null) top: for (AbstractMethodDeclaration def : typeDecl.methods) {
			if (def instanceof ConstructorDeclaration) {
				if ((def.bits & ASTNode.IsDefaultConstructor) != 0) continue;
				
				if (def.annotations != null) for (Annotation anno : def.annotations) {
					if (typeMatches(Tolerate.class, node, anno.type)) continue top;
				}
				
				return getGeneratedBy(def) == null ? MemberExistsResult.EXISTS_BY_USER : MemberExistsResult.EXISTS_BY_LOMBOK;
			}
		}
	}
	
	return MemberExistsResult.NOT_EXISTS;
}
 
Example #7
Source File: EclipseASTVisitor.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void visitMethod(EclipseNode node, AbstractMethodDeclaration method) {
	String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD";
	print("<%s %s: %s%s%s>", type, str(method.selector), method.statements != null ? "filled" : "blank",
			isGenerated(method) ? " (GENERATED)" : "", position(node));
	indent++;
	if (printContent) {
		if (method.statements != null) print("%s", method);
		disablePrinting++;
	}
}
 
Example #8
Source File: NodeSearcher.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean visit(
	ConstructorDeclaration constructorDeclaration,
	ClassScope scope) {

	if (constructorDeclaration.declarationSourceStart <= this.position
		&& this.position <= constructorDeclaration.declarationSourceEnd) {
			this.found = constructorDeclaration;
			return false;
	}
	return true;
}
 
Example #9
Source File: AndLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(ConstructorDeclaration 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 #10
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int match(ConstructorDeclaration 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 #11
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit internalFormatStatements(String source, int indentationLevel, String lineSeparator, ConstructorDeclaration constructorDeclaration, 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);

	return this.newCodeFormatter.format(source, constructorDeclaration);
}
 
Example #12
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit formatStatements(String source, int indentationLevel, String lineSeparator, IRegion[] regions, boolean includeComments) {
	ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false);

	if (constructorDeclaration.statements == null) {
		// a problem occured while parsing the source
		return null;
	}
	return internalFormatStatements(source, indentationLevel, lineSeparator, constructorDeclaration, regions, includeComments);
}
 
Example #13
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 #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(ConstructorDeclaration constructorDeclaration, ClassScope classScope) {
	if (((constructorDeclaration.bits & ASTNode.IsDefaultConstructor) == 0) && !constructorDeclaration.isClinit()) {
		removeLocals(
				constructorDeclaration.arguments,
				constructorDeclaration.declarationSourceStart,
				constructorDeclaration.declarationSourceEnd);
		removeLocals(
				constructorDeclaration.statements,
				constructorDeclaration.declarationSourceStart,
				constructorDeclaration.declarationSourceEnd);
	}
	pushParent(constructorDeclaration);
	return true;
}
 
Example #15
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(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
	Annotation[] annotations = constructorDeclaration.annotations;
	if (annotations != null) {
		MethodBinding constructorBinding = constructorDeclaration.binding;
		if (constructorBinding == null) {
			return false;
		}
		((SourceTypeBinding) constructorBinding.declaringClass).resolveTypesFor(constructorBinding);
		this.resolveAnnotations(
				constructorDeclaration.scope,
				annotations,
				constructorBinding);
	}
	
	TypeParameter[] typeParameters = constructorDeclaration.typeParameters;
	if (typeParameters != null) {
		int typeParametersLength = typeParameters.length;
		for (int i = 0; i < typeParametersLength; i++) {
			typeParameters[i].traverse(this, constructorDeclaration.scope);
		}
	}
	
	Argument[] arguments = constructorDeclaration.arguments;
	if (arguments != null) {
		int argumentLength = arguments.length;
		for (int i = 0; i < argumentLength; i++) {
			arguments[i].traverse(this, constructorDeclaration.scope);
		}
	}
	return false;
}
 
Example #16
Source File: EclipseAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
private EclipseNode buildMethod(AbstractMethodDeclaration method) {
	if (setAndGetAsHandled(method)) return null;
	List<EclipseNode> childNodes = new ArrayList<EclipseNode>();
	childNodes.addAll(buildArguments(method.arguments));
	if (method instanceof ConstructorDeclaration) {
		ConstructorDeclaration constructor = (ConstructorDeclaration) method;
		addIfNotNull(childNodes, buildStatement(constructor.constructorCall));
	}
	childNodes.addAll(buildStatements(method.statements));
	childNodes.addAll(buildAnnotations(method.annotations, false));
	return putInMap(new EclipseNode(this, method, childNodes, Kind.METHOD));
}
 
Example #17
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
/**
 * Inserts a method into an existing type. The type must represent a {@code TypeDeclaration}.
 */
public static EclipseNode injectMethod(EclipseNode type, AbstractMethodDeclaration method) {
	method.annotations = addSuppressWarningsAll(type, method, method.annotations);
	method.annotations = addGenerated(type, method, method.annotations);
	TypeDeclaration parent = (TypeDeclaration) type.get();
	
	if (parent.methods == null) {
		parent.methods = new AbstractMethodDeclaration[1];
		parent.methods[0] = method;
	} else {
		if (method instanceof ConstructorDeclaration) {
			for (int i = 0 ; i < parent.methods.length ; i++) {
				if (parent.methods[i] instanceof ConstructorDeclaration &&
						(parent.methods[i].bits & ASTNode.IsDefaultConstructor) != 0) {
					EclipseNode tossMe = type.getNodeFor(parent.methods[i]);
					
					AbstractMethodDeclaration[] withoutGeneratedConstructor = new AbstractMethodDeclaration[parent.methods.length - 1];
					
					System.arraycopy(parent.methods, 0, withoutGeneratedConstructor, 0, i);
					System.arraycopy(parent.methods, i + 1, withoutGeneratedConstructor, i, parent.methods.length - i - 1);
					
					parent.methods = withoutGeneratedConstructor;
					if (tossMe != null) tossMe.up().removeChild(tossMe);
					break;
				}
			}
		}
		//We insert the method in the last position of the methods registered to the type
		//When changing this behavior, this may trigger issue #155 and #377
		AbstractMethodDeclaration[] newArray = new AbstractMethodDeclaration[parent.methods.length + 1];
		System.arraycopy(parent.methods, 0, newArray, 0, parent.methods.length);
		newArray[parent.methods.length] = method;
		parent.methods = newArray;
	}
	
	return type.add(method, Kind.METHOD);
}
 
Example #18
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 #19
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 #20
Source File: EclipseASTVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
public void endVisitMethod(EclipseNode node, AbstractMethodDeclaration method) {
	if (printContent) disablePrinting--;
	String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD";
	indent--;
	print("</%s %s>", type, str(method.selector));
}
 
Example #21
Source File: SelectionOnQualifiedAllocationExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public TypeBinding resolveType(BlockScope scope) {
	super.resolveType(scope);

	if (this.binding == null) {
		throw new SelectionNodeFound();
	}

	// tolerate some error cases
	if (!this.binding.isValidBinding()) {
		switch (this.binding.problemId()) {
			case ProblemReasons.NotVisible:
				// visibility is ignored
				break;
			case ProblemReasons.NotFound:
				if (this.resolvedType != null && this.resolvedType.isValidBinding()) {
					throw new SelectionNodeFound(this.resolvedType);
				}
				throw new SelectionNodeFound();
			default:
				throw new SelectionNodeFound();
		}
	}

	if (this.anonymousType == null)
		throw new SelectionNodeFound(this.binding);

	// if selecting a type for an anonymous type creation, we have to
	// find its target super constructor (if extending a class) or its target
	// super interface (if extending an interface)
	if (this.anonymousType.binding != null) {
		LocalTypeBinding localType = (LocalTypeBinding) this.anonymousType.binding;
		if (localType.superInterfaces == Binding.NO_SUPERINTERFACES) {
			// find the constructor binding inside the super constructor call
			ConstructorDeclaration constructor = (ConstructorDeclaration) this.anonymousType.declarationOf(this.binding.original());
			if (constructor != null) {
				throw new SelectionNodeFound(constructor.constructorCall.binding);
			}
			throw new SelectionNodeFound(this.binding);
		}
		// open on the only super interface
		throw new SelectionNodeFound(localType.superInterfaces[0]);
	} else {
		if (this.resolvedType.isInterface()) {
			throw new SelectionNodeFound(this.resolvedType);
		}
		throw new SelectionNodeFound(this.binding);
	}
}
 
Example #22
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 #23
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 #24
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();
}
 
Example #25
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ConstructorDeclaration parseStatements(
		char[] source,
		int offset,
		int length,
		Map settings,
		boolean recordParsingInformation,
		boolean enabledStatementRecovery) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	// in this case we don't want to ignore method bodies since we are parsing only statements
	final ProblemReporter problemReporter = new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault()));
	CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
	parser.setMethodsFullRecovery(false);
	parser.setStatementsRecovery(enabledStatementRecovery);

	ICompilationUnit sourceUnit =
		new CompilationUnit(
			source,
			"", //$NON-NLS-1$
			compilerOptions.defaultEncoding);

	final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length);

	ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult);
	constructorDeclaration.sourceEnd  = -1;
	constructorDeclaration.declarationSourceEnd = offset + length - 1;
	constructorDeclaration.bodyStart = offset;
	constructorDeclaration.bodyEnd = offset + length - 1;

	parser.scanner.setSource(compilationResult);
	parser.scanner.resetTo(offset, offset + length);
	parser.parse(constructorDeclaration, compilationUnitDeclaration, true);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}
	return constructorDeclaration;
}
 
Example #26
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ConstructorDeclaration parseStatements(char[] source, Map settings, boolean recordParsingInformation, boolean enabledStatementRecovery) {
	return parseStatements(source, 0, source.length, settings, recordParsingInformation, enabledStatementRecovery);
}
 
Example #27
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private TextEdit probeFormatting(String source, int indentationLevel, String lineSeparator, IRegion[] regions, boolean includeComments) {
	if (PROBING_SCANNER == null) {
		// scanner use to check if the kind could be K_JAVA_DOC, K_MULTI_LINE_COMMENT or K_SINGLE_LINE_COMMENT
		// do not tokenize white spaces to get single comments even with spaces before...
		PROBING_SCANNER = new Scanner(true, false/*do not tokenize whitespaces*/, false/*nls*/, ClassFileConstants.JDK1_6, ClassFileConstants.JDK1_6, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/);
	}
	PROBING_SCANNER.setSource(source.toCharArray());

	IRegion coveredRegion = getCoveredRegion(regions);
	int offset = coveredRegion.getOffset();
	int length = coveredRegion.getLength();

	PROBING_SCANNER.resetTo(offset, offset + length - 1);
	try {
		int kind = -1;
		switch(PROBING_SCANNER.getNextToken()) {
			case ITerminalSymbols.TokenNameCOMMENT_BLOCK :
				if (PROBING_SCANNER.getNextToken() == TerminalTokens.TokenNameEOF) {
					kind = K_MULTI_LINE_COMMENT;
				}
				break;
			case ITerminalSymbols.TokenNameCOMMENT_LINE :
				if (PROBING_SCANNER.getNextToken() == TerminalTokens.TokenNameEOF) {
					kind = K_SINGLE_LINE_COMMENT;
				}
				break;
			case ITerminalSymbols.TokenNameCOMMENT_JAVADOC :
				if (PROBING_SCANNER.getNextToken() == TerminalTokens.TokenNameEOF) {
					kind = K_JAVA_DOC;
				}
				break;
		}
		if (kind != -1) {
			return formatComment(kind, source, indentationLevel, lineSeparator, regions);
		}
	} catch (InvalidInputException e) {
		// ignore
	}
	PROBING_SCANNER.setSource((char[]) null);

	// probe for expression
	Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true);
	if (expression != null) {
		return internalFormatExpression(source, indentationLevel, lineSeparator, expression, regions, includeComments);
	}

	// probe for body declarations (fields, methods, constructors)
	ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true);
	if (bodyDeclarations != null) {
		return internalFormatClassBodyDeclarations(source, indentationLevel, lineSeparator, bodyDeclarations, regions, includeComments);
	}

	// probe for statements
	ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false);
	if (constructorDeclaration.statements != null) {
		return internalFormatStatements(source, indentationLevel, lineSeparator, constructorDeclaration, regions, includeComments);
	}

	// this has to be a compilation unit
	return formatCompilationUnit(source, indentationLevel, lineSeparator, regions, includeComments);
}
 
Example #28
Source File: SetGeneratedByVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public boolean visit(ConstructorDeclaration node, ClassScope scope) {
	fixPositions(setGeneratedBy(node, source));
	return super.visit(node, scope);
}
 
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 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;
	}
}
 
Example #30
Source File: UnresolvedReferenceNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) {
	if (((constructorDeclaration.bits & ASTNode.IsDefaultConstructor) == 0) && !constructorDeclaration.isClinit()) {
		endVisitPreserved(constructorDeclaration.bodyStart, constructorDeclaration.bodyEnd);
	}
	popParent();
}