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

The following examples show how to use org.eclipse.jdt.internal.compiler.ast.SingleNameReference. 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: PatchExtensionMethod.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static NameReference createNameRef(TypeBinding typeBinding, ASTNode source) {
	long p = ((long) source.sourceStart << 32) | source.sourceEnd;
	char[] pkg = typeBinding.qualifiedPackageName();
	char[] basename = typeBinding.qualifiedSourceName();
	
	StringBuilder sb = new StringBuilder();
	if (pkg != null) sb.append(pkg);
	if (sb.length() > 0) sb.append(".");
	sb.append(basename);
	
	String tName = sb.toString();
	
	if (tName.indexOf('.') == -1) {
		return new SingleNameReference(basename, p);
	} else {
		char[][] sources;
		String[] in = tName.split("\\.");
		sources = new char[in.length][];
		for (int i = 0; i < in.length; i++) sources[i] = in[i].toCharArray();
		long[] poss = new long[in.length];
		Arrays.fill(poss, p);
		return new QualifiedNameReference(sources, poss, source.sourceStart, source.sourceEnd);
	}
}
 
Example #2
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 #3
Source File: HandleNonNull.java    From EasyMPermission with MIT License 6 votes vote down vote up
public char[] returnVarNameIfNullCheck(Statement stat) {
	if (!(stat instanceof IfStatement)) return null;
	
	/* Check that the if's statement is a throw statement, possibly in a block. */ {
		Statement then = ((IfStatement) stat).thenStatement;
		if (then instanceof Block) {
			Statement[] blockStatements = ((Block) then).statements;
			if (blockStatements == null || blockStatements.length == 0) return null;
			then = blockStatements[0];
		}
		
		if (!(then instanceof ThrowStatement)) return null;
	}
	
	/* Check that the if's conditional is like 'x == null'. Return from this method (don't generate
	   a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ {
		Expression cond = ((IfStatement) stat).condition;
		if (!(cond instanceof EqualExpression)) return null;
		EqualExpression bin = (EqualExpression) cond;
		int operatorId = ((bin.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT);
		if (operatorId != OperatorIds.EQUAL_EQUAL) return null;
		if (!(bin.left instanceof SingleNameReference)) return null;
		if (!(bin.right instanceof NullLiteral)) return null;
		return ((SingleNameReference) bin.left).token;
	}
}
 
Example #4
Source File: Eclipse.java    From EasyMPermission with MIT License 5 votes vote down vote up
/**
 * Returns the actual value of the given Literal or Literal-like node.
 */
public static Object calculateValue(Expression e) {
	if (e instanceof Literal) {
		((Literal)e).computeConstant();
		switch (e.constant.typeID()) {
		case TypeIds.T_int: return e.constant.intValue();
		case TypeIds.T_byte: return e.constant.byteValue();
		case TypeIds.T_short: return e.constant.shortValue();
		case TypeIds.T_char: return e.constant.charValue();
		case TypeIds.T_float: return e.constant.floatValue();
		case TypeIds.T_double: return e.constant.doubleValue();
		case TypeIds.T_boolean: return e.constant.booleanValue();
		case TypeIds.T_long: return e.constant.longValue();
		case TypeIds.T_JavaLangString: return e.constant.stringValue();
		default: return null;
		}
	} else if (e instanceof ClassLiteralAccess) {
		return Eclipse.toQualifiedName(((ClassLiteralAccess)e).type.getTypeName());
	} else if (e instanceof SingleNameReference) {
		return new String(((SingleNameReference)e).token);
	} else if (e instanceof QualifiedNameReference) {
		String qName = Eclipse.toQualifiedName(((QualifiedNameReference)e).tokens);
		int idx = qName.lastIndexOf('.');
		return idx == -1 ? qName : qName.substring(idx+1);
	}
	
	return null;
}
 
Example #5
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
static Expression createFieldAccessor(EclipseNode field, FieldAccess fieldAccess, ASTNode source) {
	int pS = source == null ? 0 : source.sourceStart, pE = source == null ? 0 : source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	boolean lookForGetter = lookForGetter(field, fieldAccess);
	
	GetterMethod getter = lookForGetter ? findGetter(field) : null;
	
	if (getter == null) {
		FieldDeclaration fieldDecl = (FieldDeclaration)field.get();
		FieldReference ref = new FieldReference(fieldDecl.name, p);
		if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0) {
			EclipseNode containerNode = field.up();
			if (containerNode != null && containerNode.get() instanceof TypeDeclaration) {
				ref.receiver = new SingleNameReference(((TypeDeclaration)containerNode.get()).name, p);
			} else {
				Expression smallRef = new FieldReference(field.getName().toCharArray(), p);
				if (source != null) setGeneratedBy(smallRef, source);
				return smallRef;
			}
		} else {
			ref.receiver = new ThisReference(pS, pE);
		}
		
		if (source != null) {
			setGeneratedBy(ref, source);
			setGeneratedBy(ref.receiver, source);
		}
		return ref;
	}
	
	MessageSend call = new MessageSend();
	setGeneratedBy(call, source);
	call.sourceStart = pS; call.statementEnd = call.sourceEnd = pE;
	call.receiver = new ThisReference(pS, pE);
	setGeneratedBy(call.receiver, source);
	call.selector = getter.name;
	return call;
}
 
Example #6
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
static Expression createFieldAccessor(EclipseNode field, FieldAccess fieldAccess, ASTNode source, char[] receiver) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	boolean lookForGetter = lookForGetter(field, fieldAccess);
	
	GetterMethod getter = lookForGetter ? findGetter(field) : null;
	
	if (getter == null) {
		NameReference ref;
		
		char[][] tokens = new char[2][];
		tokens[0] = receiver;
		tokens[1] = field.getName().toCharArray();
		long[] poss = {p, p};
		
		ref = new QualifiedNameReference(tokens, poss, pS, pE);
		setGeneratedBy(ref, source);
		return ref;
	}
	
	MessageSend call = new MessageSend();
	setGeneratedBy(call, source);
	call.sourceStart = pS; call.statementEnd = call.sourceEnd = pE;
	call.receiver = new SingleNameReference(receiver, p);
	setGeneratedBy(call.receiver, source);
	call.selector = getter.name;
	return call;
}
 
Example #7
Source File: IndexingParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected SingleNameReference newSingleNameReference(char[] source, long positions) {
	SingleNameReference ref = this.singleNameReference;
	ref.token = source;
	ref.sourceStart = (int) (positions >>> 32);
	ref.sourceEnd = (int) positions;
	return ref;
}
 
Example #8
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void doAssignmentCheck0(EclipseNode node, Statement statement, char[] varName) {
	if (statement instanceof Assignment)
		doAssignmentCheck0(node, ((Assignment)statement).expression, varName);
	else if (statement instanceof LocalDeclaration)
		doAssignmentCheck0(node, ((LocalDeclaration)statement).initialization, varName);
	else if (statement instanceof CastExpression)
		doAssignmentCheck0(node, ((CastExpression)statement).expression, varName);
	else if (statement instanceof SingleNameReference) {
		if (Arrays.equals(((SingleNameReference)statement).token, varName)) {
			EclipseNode problemNode = node.getNodeFor(statement);
			if (problemNode != null) problemNode.addWarning(
					"You're assigning an auto-cleanup variable to something else. This is a bad idea.");
		}
	}
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: LocalVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Object getAnnotationMemberValue(MemberValuePair memberValuePair, Expression expression, JavaElement parentElement) {
	if (expression instanceof NullLiteral) {
		return null;
	} else if (expression instanceof Literal) {
		((Literal) expression).computeConstant();
		return Util.getAnnotationMemberValue(memberValuePair, expression.constant);
	} else if (expression instanceof org.eclipse.jdt.internal.compiler.ast.Annotation) {
		memberValuePair.valueKind = IMemberValuePair.K_ANNOTATION;
		return getAnnotation((org.eclipse.jdt.internal.compiler.ast.Annotation) expression, parentElement);
	} else if (expression instanceof ClassLiteralAccess) {
		ClassLiteralAccess classLiteral = (ClassLiteralAccess) expression;
		char[] typeName = CharOperation.concatWith(classLiteral.type.getTypeName(), '.');
		memberValuePair.valueKind = IMemberValuePair.K_CLASS;
		return new String(typeName);
	} else if (expression instanceof QualifiedNameReference) {
		char[] qualifiedName = CharOperation.concatWith(((QualifiedNameReference) expression).tokens, '.');
		memberValuePair.valueKind = IMemberValuePair.K_QUALIFIED_NAME;
		return new String(qualifiedName);
	} else if (expression instanceof SingleNameReference) {
		char[] simpleName = ((SingleNameReference) expression).token;
		if (simpleName == RecoveryScanner.FAKE_IDENTIFIER) {
			memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
			return null;
		}
		memberValuePair.valueKind = IMemberValuePair.K_SIMPLE_NAME;
		return new String(simpleName);
	} else if (expression instanceof ArrayInitializer) {
		memberValuePair.valueKind = -1; // modified below by the first call to getMemberValue(...)
		Expression[] expressions = ((ArrayInitializer) expression).expressions;
		int length = expressions == null ? 0 : expressions.length;
		Object[] values = new Object[length];
		for (int i = 0; i < length; i++) {
			int previousValueKind = memberValuePair.valueKind;
			Object value = getAnnotationMemberValue(memberValuePair, expressions[i], parentElement);
			if (previousValueKind != -1 && memberValuePair.valueKind != previousValueKind) {
				// values are heterogeneous, value kind is thus unknown
				memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
			}
			values[i] = value;
		}
		if (memberValuePair.valueKind == -1)
			memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return values;
	} else if (expression instanceof UnaryExpression) {			//to deal with negative numerals (see bug - 248312)
		UnaryExpression unaryExpression = (UnaryExpression) expression;
		if ((unaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT == OperatorIds.MINUS) {
			if (unaryExpression.expression instanceof Literal) {
				Literal subExpression = (Literal) unaryExpression.expression;
				subExpression.computeConstant();
				return Util.getNegativeAnnotationMemberValue(memberValuePair, subExpression.constant);
			}
		}
		memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return null;
	} else {
		memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return null;
	}
}
 
Example #14
Source File: CompilationUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected Object getMemberValue(org.eclipse.jdt.internal.core.MemberValuePair memberValuePair, Expression expression) {
	if (expression instanceof NullLiteral) {
		return null;
	} else if (expression instanceof Literal) {
		((Literal) expression).computeConstant();
		return Util.getAnnotationMemberValue(memberValuePair, expression.constant);
	} else if (expression instanceof org.eclipse.jdt.internal.compiler.ast.Annotation) {
		org.eclipse.jdt.internal.compiler.ast.Annotation annotation = (org.eclipse.jdt.internal.compiler.ast.Annotation) expression;
		Object handle = acceptAnnotation(annotation, null, (JavaElement) this.handleStack.peek());
		memberValuePair.valueKind = IMemberValuePair.K_ANNOTATION;
		return handle;
	} else if (expression instanceof ClassLiteralAccess) {
		ClassLiteralAccess classLiteral = (ClassLiteralAccess) expression;
		char[] name = CharOperation.concatWith(classLiteral.type.getTypeName(), '.');
		memberValuePair.valueKind = IMemberValuePair.K_CLASS;
		return new String(name);
	} else if (expression instanceof QualifiedNameReference) {
		char[] qualifiedName = CharOperation.concatWith(((QualifiedNameReference) expression).tokens, '.');
		memberValuePair.valueKind = IMemberValuePair.K_QUALIFIED_NAME;
		return new String(qualifiedName);
	} else if (expression instanceof SingleNameReference) {
		char[] simpleName = ((SingleNameReference) expression).token;
		if (simpleName == RecoveryScanner.FAKE_IDENTIFIER) {
			memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
			return null;
		}
		memberValuePair.valueKind = IMemberValuePair.K_SIMPLE_NAME;
		return new String(simpleName);
	} else if (expression instanceof ArrayInitializer) {
		memberValuePair.valueKind = -1; // modified below by the first call to getMemberValue(...)
		Expression[] expressions = ((ArrayInitializer) expression).expressions;
		int length = expressions == null ? 0 : expressions.length;
		Object[] values = new Object[length];
		for (int i = 0; i < length; i++) {
			int previousValueKind = memberValuePair.valueKind;
			Object value = getMemberValue(memberValuePair, expressions[i]);
			if (previousValueKind != -1 && memberValuePair.valueKind != previousValueKind) {
				// values are heterogeneous, value kind is thus unknown
				memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
			}
			values[i] = value;
		}
		if (memberValuePair.valueKind == -1)
			memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return values;
	} else if (expression instanceof UnaryExpression) {			// to deal with negative numerals (see bug - 248312)
		UnaryExpression unaryExpression = (UnaryExpression) expression;
		if ((unaryExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT == OperatorIds.MINUS) {
			if (unaryExpression.expression instanceof Literal) {
				Literal subExpression = (Literal) unaryExpression.expression;
				subExpression.computeConstant();
				return Util.getNegativeAnnotationMemberValue(memberValuePair, subExpression.constant);
			}
		}
		memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return null;
	} else {
		memberValuePair.valueKind = IMemberValuePair.K_UNKNOWN;
		return null;
	}
}
 
Example #15
Source File: BinaryExpressionFragmentBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean visit(
	SingleNameReference singleNameReference,
	BlockScope scope) {
		addRealFragment(singleNameReference);
		return false;
}
 
Example #16
Source File: SelectionParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected NameReference getUnspecifiedReference(boolean rejectTypeAnnotations) {
	/* build a (unspecified) NameReference which may be qualified*/

	int completionIndex;

	/* no need to take action if not inside completed identifiers */
	if ((completionIndex = indexOfAssistIdentifier()) < 0) {
		return super.getUnspecifiedReference(rejectTypeAnnotations);
	}

	if (rejectTypeAnnotations) {
		consumeNonTypeUseName();
	}
	int length = this.identifierLengthStack[this.identifierLengthPtr];
	if (CharOperation.equals(assistIdentifier(), SUPER)){
		Reference reference;
		if (completionIndex > 0){ // qualified super
			// discard 'super' from identifier stacks
			// There is some voodoo going on here in combination with SelectionScanne#scanIdentifierOrKeyword, do in Rome as Romans do and leave the stacks at the right depth.
			this.identifierLengthStack[this.identifierLengthPtr] = completionIndex;
			int ptr = this.identifierPtr -= (length - completionIndex);
			pushOnGenericsLengthStack(0);
			pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]);
			for (int i = 0; i < completionIndex; i++) {
				pushOnTypeAnnotationLengthStack(0);
			}
			reference =
				new SelectionOnQualifiedSuperReference(
					getTypeReference(0),
					(int)(this.identifierPositionStack[ptr+1] >>> 32),
					(int) this.identifierPositionStack[ptr+1]);
		} else { // standard super
			this.identifierPtr -= length;
			this.identifierLengthPtr--;
			reference = new SelectionOnSuperReference((int)(this.identifierPositionStack[this.identifierPtr+1] >>> 32), (int) this.identifierPositionStack[this.identifierPtr+1]);
		}
		pushOnAstStack(reference);
		this.assistNode = reference;
		this.lastCheckPoint = reference.sourceEnd + 1;
		if (!this.diet || this.dietInt != 0){
			this.restartRecovery	= true;	// force to restart in recovery mode
			this.lastIgnoredToken = -1;
		}
		this.isOrphanCompletionNode = true;
		return new SingleNameReference(CharOperation.NO_CHAR, 0); // dummy reference
	}
	NameReference nameReference;
	/* retrieve identifiers subset and whole positions, the completion node positions
		should include the entire replaced source. */
	char[][] subset = identifierSubSet(completionIndex);
	this.identifierLengthPtr--;
	this.identifierPtr -= length;
	long[] positions = new long[length];
	System.arraycopy(
		this.identifierPositionStack,
		this.identifierPtr + 1,
		positions,
		0,
		length);
	/* build specific completion on name reference */
	if (completionIndex == 0) {
		/* completion inside first identifier */
		nameReference = createSingleAssistNameReference(assistIdentifier(), positions[0]);
	} else {
		/* completion inside subsequent identifier */
		nameReference = createQualifiedAssistNameReference(subset, assistIdentifier(), positions);
	}
	this.assistNode = nameReference;
	this.lastCheckPoint = nameReference.sourceEnd + 1;
	if (!this.diet){
		this.restartRecovery	= true;	// force to restart in recovery mode
		this.lastIgnoredToken = -1;
	}
	this.isOrphanCompletionNode = true;
	return nameReference;
}
 
Example #17
Source File: EclipseJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 4 votes vote down vote up
private 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;
	
	String pN = new String(data.getPluralName());
	char[] keyFieldName = (pN + "$key").toCharArray();
	char[] valueFieldName = (pN + "$value").toCharArray();
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType, true));
	
	char[] entryName = "$lombokEntry".toCharArray();
	
	TypeReference forEachType = new QualifiedTypeReference(JAVA_UTIL_MAP_ENTRY, NULL_POSS);
	forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs());
	
	MessageSend keyArg = new MessageSend();
	keyArg.receiver = new SingleNameReference(entryName, 0L);
	keyArg.selector = "getKey".toCharArray();
	MessageSend addKey = new MessageSend();
	FieldReference thisDotKeyField = new FieldReference(keyFieldName, 0L);
	thisDotKeyField.receiver = new ThisReference(0, 0);
	addKey.receiver = thisDotKeyField;
	addKey.selector = new char[] {'a', 'd', 'd'};
	addKey.arguments = new Expression[] {keyArg};
	
	MessageSend valueArg = new MessageSend();
	valueArg.receiver = new SingleNameReference(entryName, 0L);
	valueArg.selector = "getValue".toCharArray();
	MessageSend addValue = new MessageSend();
	FieldReference thisDotValueField = new FieldReference(valueFieldName, 0L);
	thisDotValueField.receiver = new ThisReference(0, 0);
	addValue.receiver = thisDotValueField;
	addValue.selector = new char[] {'a', 'd', 'd'};
	addValue.arguments = new Expression[] {valueArg};
	
	LocalDeclaration elementVariable = new LocalDeclaration(entryName, 0, 0);
	elementVariable.type = forEachType;
	ForeachStatement forEach = new ForeachStatement(elementVariable, 0);
	MessageSend invokeEntrySet = new MessageSend();
	invokeEntrySet.selector = new char[] { 'e', 'n', 't', 'r', 'y', 'S', 'e', 't'};
	invokeEntrySet.receiver = new SingleNameReference(data.getPluralName(), 0L);
	forEach.collection = invokeEntrySet;
	Block forEachContent = new Block(0);
	forEachContent.statements = new Statement[] {addKey, addValue};
	forEach.action = forEachContent;
	statements.add(forEach);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	TypeReference paramType = new QualifiedTypeReference(JAVA_UTIL_MAP, NULL_POSS);
	paramType = addTypeArgs(2, 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("putAll", new String(data.getPluralName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #18
Source File: EclipseJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 4 votes vote down vote up
private 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, true));
	
	String sN = new String(data.getSingularName());
	String pN = new String(data.getPluralName());
	char[] keyParamName = (sN + "Key").toCharArray();
	char[] valueParamName = (sN + "Value").toCharArray();
	char[] keyFieldName = (pN + "$key").toCharArray();
	char[] valueFieldName = (pN + "$value").toCharArray();
	
	/* this.pluralname$key.add(singularnameKey); */ {
		FieldReference thisDotKeyField = new FieldReference(keyFieldName, 0L);
		thisDotKeyField.receiver = new ThisReference(0, 0);
		MessageSend thisDotKeyFieldDotAdd = new MessageSend();
		thisDotKeyFieldDotAdd.arguments = new Expression[] {new SingleNameReference(keyParamName, 0L)};
		thisDotKeyFieldDotAdd.receiver = thisDotKeyField;
		thisDotKeyFieldDotAdd.selector = "add".toCharArray();
		statements.add(thisDotKeyFieldDotAdd);
	}
	
	/* this.pluralname$value.add(singularnameValue); */ {
		FieldReference thisDotValueField = new FieldReference(valueFieldName, 0L);
		thisDotValueField.receiver = new ThisReference(0, 0);
		MessageSend thisDotValueFieldDotAdd = new MessageSend();
		thisDotValueFieldDotAdd.arguments = new Expression[] {new SingleNameReference(valueParamName, 0L)};
		thisDotValueFieldDotAdd.receiver = thisDotValueField;
		thisDotValueFieldDotAdd.selector = "add".toCharArray();
		statements.add(thisDotValueFieldDotAdd);
	}
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	TypeReference keyParamType = cloneParamType(0, data.getTypeArgs(), builderType);
	Argument keyParam = new Argument(keyParamName, 0, keyParamType, 0);
	TypeReference valueParamType = cloneParamType(1, data.getTypeArgs(), builderType);
	Argument valueParam = new Argument(valueParamName, 0, valueParamType, 0);
	md.arguments = new Argument[] {keyParam, valueParam};
	md.returnType = returnType;
	md.selector = fluent ? data.getSingularName() : HandlerUtil.buildAccessorName("put", new String(data.getSingularName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #19
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 #20
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 #21
Source File: SetGeneratedByVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public boolean visit(SingleNameReference node, ClassScope scope) {
	fixPositions(setGeneratedBy(node, source));
	return super.visit(node, scope);
}
 
Example #22
Source File: SetGeneratedByVisitor.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public boolean visit(SingleNameReference node, BlockScope scope) {
	fixPositions(setGeneratedBy(node, source));
	return super.visit(node, scope);
}
 
Example #23
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 4 votes vote down vote up
public MethodDeclaration createCanEqual(EclipseNode type, ASTNode source, List<Annotation> onParam) {
	/* public boolean canEqual(final java.lang.Object other) {
	 *     return other instanceof Outer.Inner.MyType;
	 * }
	 */
	int pS = source.sourceStart; int pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	char[] otherName = "other".toCharArray();
	
	MethodDeclaration method = new MethodDeclaration(
			((CompilationUnitDeclaration) type.top().get()).compilationResult);
	setGeneratedBy(method, source);
	method.modifiers = toEclipseModifier(AccessLevel.PROTECTED);
	method.returnType = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
	method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE;
	setGeneratedBy(method.returnType, source);
	method.selector = "canEqual".toCharArray();
	method.thrownExceptions = null;
	method.typeParameters = null;
	method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
	method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
	method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
	TypeReference objectRef = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { p, p, p });
	setGeneratedBy(objectRef, source);
	method.arguments = new Argument[] {new Argument(otherName, 0, objectRef, Modifier.FINAL)};
	method.arguments[0].sourceStart = pS; method.arguments[0].sourceEnd = pE;
	if (!onParam.isEmpty()) method.arguments[0].annotations = onParam.toArray(new Annotation[0]);
	setGeneratedBy(method.arguments[0], source);
	
	SingleNameReference otherRef = new SingleNameReference(otherName, p);
	setGeneratedBy(otherRef, source);
	
	TypeReference typeReference = createTypeReference(type, p);
	setGeneratedBy(typeReference, source);
	
	InstanceOfExpression instanceOf = new InstanceOfExpression(otherRef, typeReference);
	instanceOf.sourceStart = pS; instanceOf.sourceEnd = pE;
	setGeneratedBy(instanceOf, source);
	
	ReturnStatement returnStatement = new ReturnStatement(instanceOf, pS, pE);
	setGeneratedBy(returnStatement, source);
	
	method.statements = new Statement[] {returnStatement};
	return method;
}
 
Example #24
Source File: HandleWither.java    From EasyMPermission with MIT License 4 votes vote down vote up
public MethodDeclaration createWither(TypeDeclaration parent, EclipseNode fieldNode, String name, int modifier, EclipseNode sourceNode, List<Annotation> onMethod, List<Annotation> onParam) {
	ASTNode source = sourceNode.get();
	if (name == null) return null;
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	MethodDeclaration method = new MethodDeclaration(parent.compilationResult);
	method.modifiers = modifier;
	method.returnType = cloneSelfType(fieldNode, source);
	if (method.returnType == null) return null;
	
	Annotation[] deprecated = null;
	if (isFieldDeprecated(fieldNode)) {
		deprecated = new Annotation[] { generateDeprecatedAnnotation(source) };
	}
	method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated);
	Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL);
	param.sourceStart = pS; param.sourceEnd = pE;
	method.arguments = new Argument[] { param };
	method.selector = name.toCharArray();
	method.binding = null;
	method.thrownExceptions = null;
	method.typeParameters = null;
	method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	
	List<Expression> args = new ArrayList<Expression>();
	for (EclipseNode child : fieldNode.up().down()) {
		if (child.getKind() != Kind.FIELD) continue;
		FieldDeclaration childDecl = (FieldDeclaration) child.get();
		// Skip fields that start with $
		if (childDecl.name != null && childDecl.name.length > 0 && childDecl.name[0] == '$') continue;
		long fieldFlags = childDecl.modifiers;
		// Skip static fields.
		if ((fieldFlags & ClassFileConstants.AccStatic) != 0) continue;
		// Skip initialized final fields.
		if (((fieldFlags & ClassFileConstants.AccFinal) != 0) && childDecl.initialization != null) continue;
		if (child.get() == fieldNode.get()) {
			args.add(new SingleNameReference(field.name, p));
		} else {
			args.add(createFieldAccessor(child, FieldAccess.ALWAYS_FIELD, source));
		}
	}
	
	AllocationExpression constructorCall = new AllocationExpression();
	constructorCall.arguments = args.toArray(new Expression[0]);
	constructorCall.type = cloneSelfType(fieldNode, source);
	
	Expression identityCheck = new EqualExpression(
			createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source),
			new SingleNameReference(field.name, p),
			OperatorIds.EQUAL_EQUAL);
	ThisReference thisRef = new ThisReference(pS, pE);
	Expression conditional = new ConditionalExpression(identityCheck, thisRef, constructorCall);
	Statement returnStatement = new ReturnStatement(conditional, pS, pE);
	method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
	method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
	
	Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
	List<Statement> statements = new ArrayList<Statement>(5);
	if (nonNulls.length > 0) {
		Statement nullCheck = generateNullCheck(field, sourceNode);
		if (nullCheck != null) statements.add(nullCheck);
	}
	statements.add(returnStatement);
	
	method.statements = statements.toArray(new Statement[0]);
	
	param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0]));
	
	method.traverse(new SetGeneratedByVisitor(source), parent.scope);
	return method;
}
 
Example #25
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 4 votes vote down vote up
/**
 * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the
 * variable name as message.
 * 
 * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}.
 */
public static Statement generateNullCheck(AbstractVariableDeclaration variable, EclipseNode sourceNode) {
	NullCheckExceptionType exceptionType = sourceNode.getAst().readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE);
	if (exceptionType == null) exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION;
	
	ASTNode source = sourceNode.get();
	
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	
	if (isPrimitive(variable.type)) return null;
	AllocationExpression exception = new AllocationExpression();
	setGeneratedBy(exception, source);
	int partCount = 1;
	String exceptionTypeStr = exceptionType.getExceptionType();
	for (int i = 0; i < exceptionTypeStr.length(); i++) if (exceptionTypeStr.charAt(i) == '.') partCount++;
	long[] ps = new long[partCount];
	Arrays.fill(ps, 0L);
	exception.type = new QualifiedTypeReference(fromQualifiedName(exceptionTypeStr), ps);
	setGeneratedBy(exception.type, source);
	exception.arguments = new Expression[] {
			new StringLiteral(exceptionType.toExceptionMessage(new String(variable.name)).toCharArray(), pS, pE, 0)
	};
	setGeneratedBy(exception.arguments[0], source);
	ThrowStatement throwStatement = new ThrowStatement(exception, pS, pE);
	setGeneratedBy(throwStatement, source);
	
	SingleNameReference varName = new SingleNameReference(variable.name, p);
	setGeneratedBy(varName, source);
	NullLiteral nullLiteral = new NullLiteral(pS, pE);
	setGeneratedBy(nullLiteral, source);
	EqualExpression equalExpression = new EqualExpression(varName, nullLiteral, OperatorIds.EQUAL_EQUAL);
	equalExpression.sourceStart = pS; equalExpression.statementEnd = equalExpression.sourceEnd = pE;
	setGeneratedBy(equalExpression, source);
	Block throwBlock = new Block(0);
	throwBlock.statements = new Statement[] {throwStatement};
	throwBlock.sourceStart = pS; throwBlock.sourceEnd = pE;
	setGeneratedBy(throwBlock, source);
	IfStatement ifStatement = new IfStatement(equalExpression, throwBlock, 0, 0);
	setGeneratedBy(ifStatement, source);
	return ifStatement;
}
 
Example #26
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 4 votes vote down vote up
public Statement buildTryCatchBlock(Statement[] contents, DeclaredException exception, ASTNode source, AbstractMethodDeclaration method) {
	int methodStart = method.bodyStart;
	int methodEnd = method.bodyEnd;
	long methodPosEnd = ((long) methodEnd) << 32 | (methodEnd & 0xFFFFFFFFL);
	
	TryStatement tryStatement = new TryStatement();
	setGeneratedBy(tryStatement, source);
	tryStatement.tryBlock = new Block(0);
	
	// Positions for in-method generated nodes are special
	tryStatement.tryBlock.sourceStart = methodStart; tryStatement.tryBlock.sourceEnd = methodEnd;
	
	setGeneratedBy(tryStatement.tryBlock, source);
	tryStatement.tryBlock.statements = contents;
	TypeReference typeReference;
	if (exception.exceptionName.indexOf('.') == -1) {
		typeReference = new SingleTypeReference(exception.exceptionName.toCharArray(), methodPosEnd);
		typeReference.statementEnd = methodEnd;
	} else {
		String[] x = exception.exceptionName.split("\\.");
		char[][] elems = new char[x.length][];
		long[] poss = new long[x.length];
		Arrays.fill(poss, methodPosEnd);
		for (int i = 0; i < x.length; i++) {
			elems[i] = x[i].trim().toCharArray();
		}
		typeReference = new QualifiedTypeReference(elems, poss);
	}
	setGeneratedBy(typeReference, source);
	
	Argument catchArg = new Argument("$ex".toCharArray(), methodPosEnd, typeReference, Modifier.FINAL);
	setGeneratedBy(catchArg, source);
	catchArg.declarationSourceEnd = catchArg.declarationEnd = catchArg.sourceEnd = methodEnd;
	catchArg.declarationSourceStart = catchArg.modifiersSourceStart = catchArg.sourceStart = methodEnd;
	
	tryStatement.catchArguments = new Argument[] { catchArg };
	
	MessageSend sneakyThrowStatement = new MessageSend();
	setGeneratedBy(sneakyThrowStatement, source);
	sneakyThrowStatement.receiver = new QualifiedNameReference(new char[][] { "lombok".toCharArray(), "Lombok".toCharArray() }, new long[2], methodEnd, methodEnd);
	setGeneratedBy(sneakyThrowStatement.receiver, source);
	sneakyThrowStatement.receiver.statementEnd = methodEnd;
	sneakyThrowStatement.selector = "sneakyThrow".toCharArray();
	SingleNameReference exRef = new SingleNameReference("$ex".toCharArray(), methodPosEnd);
	setGeneratedBy(exRef, source);
	exRef.statementEnd = methodEnd;
	sneakyThrowStatement.arguments = new Expression[] { exRef };
	
	// This is the magic fix for rendering issues
	// In org.eclipse.jdt.core.dom.ASTConverter#convert(org.eclipse.jdt.internal.compiler.ast.MessageSend)
	// a new SimpleName is created and the setSourceRange should receive -1, 0. That's why we provide -2L :-)
	sneakyThrowStatement.nameSourcePosition = -2L;
	
	sneakyThrowStatement.sourceStart = methodEnd;
	sneakyThrowStatement.sourceEnd = sneakyThrowStatement.statementEnd = methodEnd;
	
	Statement rethrowStatement = new ThrowStatement(sneakyThrowStatement, methodEnd, methodEnd);
	setGeneratedBy(rethrowStatement, source);
	
	Block block = new Block(0);
	block.sourceStart = methodEnd;
	block.sourceEnd = methodEnd;
	setGeneratedBy(block, source);
	block.statements = new Statement[] { rethrowStatement };
	
	tryStatement.catchBlocks = new Block[] { block };
	
	// Positions for in-method generated nodes are special
	tryStatement.sourceStart = method.bodyStart;
	tryStatement.sourceEnd = method.bodyEnd;
	
	return tryStatement;
}
 
Example #27
Source File: HandleSetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
static MethodDeclaration createSetter(TypeDeclaration parent, EclipseNode fieldNode, String name, boolean shouldReturnThis, int modifier, EclipseNode sourceNode, List<Annotation> onMethod, List<Annotation> onParam) {
	FieldDeclaration field = (FieldDeclaration) fieldNode.get();
	ASTNode source = sourceNode.get();
	int pS = source.sourceStart, pE = source.sourceEnd;
	long p = (long)pS << 32 | pE;
	MethodDeclaration method = new MethodDeclaration(parent.compilationResult);
	method.modifiers = modifier;
	if (shouldReturnThis) {
		method.returnType = cloneSelfType(fieldNode, source);
	}
	
	if (method.returnType == null) {
		method.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
		method.returnType.sourceStart = pS; method.returnType.sourceEnd = pE;
		shouldReturnThis = false;
	}
	Annotation[] deprecated = null;
	if (isFieldDeprecated(fieldNode)) {
		deprecated = new Annotation[] { generateDeprecatedAnnotation(source) };
	}
	method.annotations = copyAnnotations(source, onMethod.toArray(new Annotation[0]), deprecated);
	Argument param = new Argument(field.name, p, copyType(field.type, source), Modifier.FINAL);
	param.sourceStart = pS; param.sourceEnd = pE;
	method.arguments = new Argument[] { param };
	method.selector = name.toCharArray();
	method.binding = null;
	method.thrownExceptions = null;
	method.typeParameters = null;
	method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
	NameReference fieldNameRef = new SingleNameReference(field.name, p);
	Assignment assignment = new Assignment(fieldRef, fieldNameRef, (int)p);
	assignment.sourceStart = pS; assignment.sourceEnd = assignment.statementEnd = pE;
	method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
	method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
	
	Annotation[] nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	Annotation[] nullables = findAnnotations(field, NULLABLE_PATTERN);
	List<Statement> statements = new ArrayList<Statement>(5);
	if (nonNulls.length == 0) {
		statements.add(assignment);
	} else {
		Statement nullCheck = generateNullCheck(field, sourceNode);
		if (nullCheck != null) statements.add(nullCheck);
		statements.add(assignment);
	}
	
	if (shouldReturnThis) {
		ThisReference thisRef = new ThisReference(pS, pE);
		ReturnStatement returnThis = new ReturnStatement(thisRef, pS, pE);
		statements.add(returnThis);
	}
	method.statements = statements.toArray(new Statement[0]);
	param.annotations = copyAnnotations(source, nonNulls, nullables, onParam.toArray(new Annotation[0]));
	
	method.traverse(new SetGeneratedByVisitor(source), parent.scope);
	return method;
}