@Override public Expression createFactoryParameter(ClassLiteralAccess type, Annotation source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; MessageSend factoryParameterCall = new MessageSend(); setGeneratedBy(factoryParameterCall, source); factoryParameterCall.receiver = super.createFactoryParameter(type, source); factoryParameterCall.selector = "getName".toCharArray(); factoryParameterCall.nameSourcePosition = p; factoryParameterCall.sourceStart = pS; factoryParameterCall.sourceEnd = factoryParameterCall.statementEnd = pE; return factoryParameterCall; }
public IfStatement generateCompareFloatOrDouble(Expression thisRef, Expression otherRef, char[] floatOrDouble, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; /* if (Float.compare(fieldName, other.fieldName) != 0) return false */ MessageSend floatCompare = new MessageSend(); floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE; setGeneratedBy(floatCompare, source); floatCompare.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble); floatCompare.selector = "compare".toCharArray(); floatCompare.arguments = new Expression[] {thisRef, otherRef}; IntLiteral int0 = makeIntLiteral("0".toCharArray(), source); EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, int0, OperatorIds.NOT_EQUAL); ifFloatCompareIsNot0.sourceStart = pS; ifFloatCompareIsNot0.sourceEnd = pE; setGeneratedBy(ifFloatCompareIsNot0, source); FalseLiteral falseLiteral = new FalseLiteral(pS, pE); setGeneratedBy(falseLiteral, source); ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE); setGeneratedBy(returnFalse, source); IfStatement ifStatement = new IfStatement(ifFloatCompareIsNot0, returnFalse, pS, pE); setGeneratedBy(ifStatement, source); return ifStatement; }
/** Give 2 clones! */ public Expression longToIntForHashCode(Expression ref1, Expression ref2, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; /* (int)(ref >>> 32 ^ ref) */ IntLiteral int32 = makeIntLiteral("32".toCharArray(), source); BinaryExpression higherBits = new BinaryExpression(ref1, int32, OperatorIds.UNSIGNED_RIGHT_SHIFT); setGeneratedBy(higherBits, source); BinaryExpression xorParts = new BinaryExpression(ref2, higherBits, OperatorIds.XOR); setGeneratedBy(xorParts, source); TypeReference intRef = TypeReference.baseTypeReference(TypeIds.T_int, 0); intRef.sourceStart = pS; intRef.sourceEnd = pE; setGeneratedBy(intRef, source); CastExpression expr = makeCastExpression(xorParts, intRef, source); expr.sourceStart = pS; expr.sourceEnd = pE; return expr; }
/** Generates 'this.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */ protected Expression getSize(EclipseNode builderType, char[] name, boolean nullGuard) { MessageSend invoke = new MessageSend(); ThisReference thisRef = new ThisReference(0, 0); FieldReference thisDotName = new FieldReference(name, 0L); thisDotName.receiver = thisRef; invoke.receiver = thisDotName; invoke.selector = SIZE_TEXT; if (!nullGuard) return invoke; ThisReference cdnThisRef = new ThisReference(0, 0); FieldReference cdnThisDotName = new FieldReference(name, 0L); cdnThisDotName.receiver = cdnThisRef; NullLiteral nullLiteral = new NullLiteral(0, 0); EqualExpression isNull = new EqualExpression(cdnThisDotName, nullLiteral, OperatorIds.EQUAL_EQUAL); IntLiteral zeroLiteral = makeIntLiteral(new char[] {'0'}, null); ConditionalExpression conditional = new ConditionalExpression(isNull, zeroLiteral, invoke); return conditional; }
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; } }
protected void consumeMemberValuePair() { if (this.indexOfAssistIdentifier() < 0) { super.consumeMemberValuePair(); return; } char[] simpleName = this.identifierStack[this.identifierPtr]; long position = this.identifierPositionStack[this.identifierPtr--]; this.identifierLengthPtr--; int end = (int) position; int start = (int) (position >>> 32); Expression value = this.expressionStack[this.expressionPtr--]; this.expressionLengthPtr--; MemberValuePair memberValuePair = new SelectionOnNameOfMemberValuePair(simpleName, start, end, value); pushOnAstStack(memberValuePair); this.assistNode = memberValuePair; this.lastCheckPoint = memberValuePair.sourceEnd + 1; }
protected MessageSend newMessageSendWithTypeArguments() { char[] selector = this.identifierStack[this.identifierPtr]; if (selector != assistIdentifier()){ return super.newMessageSendWithTypeArguments(); } MessageSend messageSend = new SelectionOnMessageSend(); int length; if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { this.expressionPtr -= length; System.arraycopy( this.expressionStack, this.expressionPtr + 1, messageSend.arguments = new Expression[length], 0, length); } this.assistNode = messageSend; if (!this.diet){ this.restartRecovery = true; // force to restart in recovery mode this.lastIgnoredToken = -1; } this.isOrphanCompletionNode = true; return messageSend; }
/** * If the given ast node is inside an explicit constructor call * then wrap it with a fake constructor call. * Returns the wrapped completion node or the completion node itself. */ protected ASTNode wrapWithExplicitConstructorCallIfNeeded(ASTNode ast) { int selector; if (ast != null && topKnownElementKind(ASSIST_PARSER) == K_SELECTOR && ast instanceof Expression && (((selector = topKnownElementInfo(ASSIST_PARSER)) == THIS_CONSTRUCTOR) || (selector == SUPER_CONSTRUCTOR))) { ExplicitConstructorCall call = new ExplicitConstructorCall( (selector == THIS_CONSTRUCTOR) ? ExplicitConstructorCall.This : ExplicitConstructorCall.Super ); call.arguments = new Expression[] {(Expression)ast}; call.sourceStart = ast.sourceStart; call.sourceEnd = ast.sourceEnd; return call; } else { return ast; } }
/** * @see org.eclipse.jdt.internal.compiler.ASTVisitor#visit(org.eclipse.jdt.internal.compiler.ast.ReturnStatement, org.eclipse.jdt.internal.compiler.lookup.BlockScope) */ public boolean visit(ReturnStatement returnStatement, BlockScope scope) { this.scribe.printNextToken(TerminalTokens.TokenNamereturn); final Expression expression = returnStatement.expression; if (expression != null) { final int numberOfParens = (expression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT; if ((numberOfParens != 0 && this.preferences.insert_space_before_parenthesized_expression_in_return) || numberOfParens == 0) { this.scribe.space(); } expression.traverse(this, scope); } /* * Print the semi-colon */ this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); this.scribe.printComment(CodeFormatter.K_UNKNOWN, Scribe.BASIC_TRAILING_COMMENT); return false; }
public void nullityMismatch(Expression expression, TypeBinding providedType, TypeBinding requiredType, int nullStatus, char[][] annotationName) { if ((nullStatus & FlowInfo.NULL) != 0) { nullityMismatchIsNull(expression, requiredType, annotationName); return; } if ((nullStatus & FlowInfo.POTENTIALLY_NULL) != 0) { if (expression instanceof SingleNameReference) { SingleNameReference snr = (SingleNameReference) expression; if (snr.binding instanceof LocalVariableBinding) { if (((LocalVariableBinding)snr.binding).isNullable()) { nullityMismatchSpecdNullable(expression, requiredType, annotationName); return; } } } nullityMismatchPotentiallyNull(expression, requiredType, annotationName); return; } nullityMismatchIsUnknown(expression, providedType, requiredType, annotationName); }
/** * @see ISourceElementRequestor */ public void exitMethod(int declarationEnd, Expression defaultValue) { SourceMethod handle = (SourceMethod) this.handleStack.peek(); MethodInfo methodInfo = (MethodInfo) this.infoStack.peek(); SourceMethodElementInfo info = createMethodInfo(methodInfo, handle); info.setSourceRangeEnd(declarationEnd); // remember default value of annotation method if (info.isAnnotationMethod() && defaultValue != null) { SourceAnnotationMethodInfo annotationMethodInfo = (SourceAnnotationMethodInfo) info; annotationMethodInfo.defaultValueStart = defaultValue.sourceStart; annotationMethodInfo.defaultValueEnd = defaultValue.sourceEnd; JavaElement element = (JavaElement) this.handleStack.peek(); org.eclipse.jdt.internal.core.MemberValuePair defaultMemberValuePair = new org.eclipse.jdt.internal.core.MemberValuePair(element.getElementName()); defaultMemberValuePair.value = getMemberValue(defaultMemberValuePair, defaultValue); annotationMethodInfo.defaultValue = defaultMemberValuePair; } this.handleStack.pop(); this.infoStack.pop(); }
protected void consumeArrayAccess(boolean unspecifiedReference) { // ArrayAccess ::= Name '[' Expression ']' ==> true // ArrayAccess ::= PrimaryNoNewArray '[' Expression ']' ==> false //optimize push/pop Expression exp; if (unspecifiedReference) { exp = this.expressionStack[this.expressionPtr] = new ArrayReference( getUnspecifiedReferenceOptimized(), this.expressionStack[this.expressionPtr]); } else { this.expressionPtr--; this.expressionLengthPtr--; exp = this.expressionStack[this.expressionPtr] = new ArrayReference( this.expressionStack[this.expressionPtr], this.expressionStack[this.expressionPtr + 1]); } exp.sourceEnd = this.endStatementPosition; }
/** * The equivalent code performs a string conversion: * * @param blockScope the given blockScope * @param oper1 the first expression * @param oper2 the second expression */ public void generateStringConcatenationAppend(BlockScope blockScope, Expression oper1, Expression oper2) { int pc; if (oper1 == null) { /* Operand is already on the stack, and maybe nil: note type1 is always to java.lang.String here.*/ newStringContatenation(); dup_x1(); this.swap(); // If argument is reference type, need to transform it // into a string (handles null case) invokeStringValueOf(TypeIds.T_JavaLangObject); invokeStringConcatenationStringConstructor(); } else { pc = this.position; oper1.generateOptimizedStringConcatenationCreation(blockScope, this, oper1.implicitConversion & TypeIds.COMPILE_TYPE_MASK); this.recordPositionsFrom(pc, oper1.sourceStart); } pc = this.position; oper2.generateOptimizedStringConcatenation(blockScope, this, oper2.implicitConversion & TypeIds.COMPILE_TYPE_MASK); this.recordPositionsFrom(pc, oper2.sourceStart); invokeStringConcatenationToString(); }
private boolean addConstraintsToC_OneExpr(Expression expri, Set<ConstraintFormula> c, TypeBinding fsi, TypeBinding substF, MethodBinding method) { // For all i (1 ≤ i ≤ k), if ei is not pertinent to applicability, the set contains ⟨ei → θ Fi⟩. if (!expri.isPertinentToApplicability(fsi, method)) { c.add(new ConstraintExpressionFormula(expri, substF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT)); } if (expri instanceof FunctionalExpression) { c.add(new ConstraintExceptionFormula((FunctionalExpression) expri, substF)); } else if (expri instanceof Invocation && expri.isPolyExpression()) { Invocation invocation = (Invocation) expri; MethodBinding innerMethod = invocation.binding(null, false, null); if (innerMethod instanceof ParameterizedGenericMethodBinding) { InferenceContext18 innerCtx = invocation.getInferenceContext((ParameterizedMethodBinding) innerMethod); if (innerCtx != null) { // otherwise innerMethod does not participate in inference return addConstraintsToC(invocation.arguments(), c, innerMethod.genericMethod(), innerCtx.inferenceKind); } } } else if (expri instanceof ConditionalExpression) { ConditionalExpression ce = (ConditionalExpression) expri; return addConstraintsToC_OneExpr(ce.valueIfTrue, c, fsi, substF, method) && addConstraintsToC_OneExpr(ce.valueIfFalse, c, fsi, substF, method); } return true; }
public void annotationValueMustBeConstant(TypeBinding annotationType, char[] name, Expression value, boolean isEnum) { String str = new String(name); if (isEnum) { this.handle( IProblem.AnnotationValueMustBeAnEnumConstant, new String[] { new String(annotationType.readableName()), str }, new String[] { new String(annotationType.shortReadableName()), str}, value.sourceStart, value.sourceEnd); } else { this.handle( IProblem.AnnotationValueMustBeConstant, new String[] { new String(annotationType.readableName()), str }, new String[] { new String(annotationType.shortReadableName()), str}, value.sourceStart, value.sourceEnd); } }
/** * Record that a nullity mismatch was detected against an annotated type reference. * @param currentScope scope for error reporting * @param expression the expression violating the specification * @param providedType the type of the provided value, i.e., either expression or an element thereof (in ForeachStatements) * @param expectedType the declared type of the spec'ed variable, for error reporting. * @param nullStatus the null status of expression at the current location */ public void recordNullityMismatch(BlockScope currentScope, Expression expression, TypeBinding providedType, TypeBinding expectedType, int nullStatus) { if (providedType == null) { return; // assume type error was already reported } if (expression.localVariableBinding() != null) { // flowContext cannot yet handle non-localvar expressions (e.g., fields) // find the inner-most flowContext that might need deferred handling: FlowContext currentContext = this; while (currentContext != null) { // some flow contexts implement deferred checking, should we participate in that? int isInsideAssert = 0x0; if ((this.tagBits & FlowContext.HIDE_NULL_COMPARISON_WARNING) != 0) { isInsideAssert = FlowContext.HIDE_NULL_COMPARISON_WARNING; } if (currentContext.internalRecordNullityMismatch(expression, providedType, nullStatus, expectedType, ASSIGN_TO_NONNULL | isInsideAssert)) return; currentContext = currentContext.parent; } } // no reason to defer, so report now: char[][] annotationName = currentScope.environment().getNonNullAnnotationName(); currentScope.problemReporter().nullityMismatch(expression, providedType, expectedType, nullStatus, annotationName); }
protected void consumeEnhancedForStatementHeader(){ // EnhancedForStatementHeader ::= EnhancedForStatementHeaderInit ':' Expression ')' final ForeachStatement statement = (ForeachStatement) this.astStack[this.astPtr]; //updates are on the expression stack this.expressionLengthPtr--; final Expression collection = this.expressionStack[this.expressionPtr--]; statement.collection = collection; // https://bugs.eclipse.org/393719 - [compiler] inconsistent warnings on iteration variables // let declaration(Source)End include the collection to achieve that @SuppressWarnings affects this part, too: statement.elementVariable.declarationSourceEnd = collection.sourceEnd; statement.elementVariable.declarationEnd = collection.sourceEnd; statement.sourceEnd = this.rParenPos; if(!this.statementRecoveryActivated && this.options.sourceLevel < ClassFileConstants.JDK1_5 && this.lastErrorEndPositionBeforeRecovery < this.scanner.currentPosition) { problemReporter().invalidUsageOfForeachStatements(statement.elementVariable, collection); } }
protected void consumeInstanceOfExpression() { // RelationalExpression ::= RelationalExpression 'instanceof' ReferenceType //optimize the push/pop //by construction, no base type may be used in getTypeReference Expression exp; this.expressionStack[this.expressionPtr] = exp = new InstanceOfExpression( this.expressionStack[this.expressionPtr], getTypeReference(this.intStack[this.intPtr--])); if (exp.sourceEnd == 0) { //array on base type.... exp.sourceEnd = this.scanner.startPosition - 1; } //the scanner is on the next token already.... }
protected void consumeMemberValuePair() { // MemberValuePair ::= SimpleName '=' MemberValue char[] simpleName = this.identifierStack[this.identifierPtr]; long position = this.identifierPositionStack[this.identifierPtr--]; this.identifierLengthPtr--; int end = (int) position; int start = (int) (position >>> 32); Expression value = this.expressionStack[this.expressionPtr--]; this.expressionLengthPtr--; MemberValuePair memberValuePair = new MemberValuePair(simpleName, start, end, value); pushOnAstStack(memberValuePair); if (this.currentElement != null && this.currentElement instanceof RecoveredAnnotation) { RecoveredAnnotation recoveredAnnotation = (RecoveredAnnotation) this.currentElement; recoveredAnnotation.setKind(RecoveredAnnotation.NORMAL); } }
protected void consumeReferenceExpressionPrimaryForm() { // ReferenceExpression ::= Primary '::' NonWildTypeArgumentsopt Identifier ReferenceExpression referenceExpression = newReferenceExpression(); TypeReference [] typeArguments = null; char [] selector; int sourceEnd; sourceEnd = (int) this.identifierPositionStack[this.identifierPtr]; referenceExpression.nameSourceStart = (int) (this.identifierPositionStack[this.identifierPtr] >>> 32); selector = this.identifierStack[this.identifierPtr--]; this.identifierLengthPtr--; int length = this.genericsLengthStack[this.genericsLengthPtr--]; if (length > 0) { this.genericsPtr -= length; System.arraycopy(this.genericsStack, this.genericsPtr + 1, typeArguments = new TypeReference[length], 0, length); this.intPtr--; // pop type arguments source start. } Expression primary = this.expressionStack[this.expressionPtr--]; this.expressionLengthPtr--; referenceExpression.initialize(this.compilationUnit.compilationResult, primary, typeArguments, selector, sourceEnd); consumeReferenceExpression(referenceExpression); }
public void unreachableCode(Statement statement) { int sourceStart = statement.sourceStart; int sourceEnd = statement.sourceEnd; if (statement instanceof LocalDeclaration) { LocalDeclaration declaration = (LocalDeclaration) statement; sourceStart = declaration.declarationSourceStart; sourceEnd = declaration.declarationSourceEnd; } else if (statement instanceof Expression) { int statemendEnd = ((Expression) statement).statementEnd; if (statemendEnd != -1) sourceEnd = statemendEnd; } this.handle( IProblem.CodeCannotBeReached, NoArgument, NoArgument, sourceStart, sourceEnd); }
public void nullityMismatchIsNull(Expression expression, TypeBinding requiredType) { int problemId = IProblem.RequiredNonNullButProvidedNull; boolean below18 = this.options.sourceLevel < ClassFileConstants.JDK1_8; if (!below18 && requiredType.isTypeVariable() && !requiredType.hasNullTypeAnnotations()) problemId = IProblem.NullNotCompatibleToFreeTypeVariable; if (requiredType instanceof CaptureBinding) { CaptureBinding capture = (CaptureBinding) requiredType; if (capture.wildcard != null) requiredType = capture.wildcard; } String[] arguments; String[] argumentsShort; if (below18) { arguments = new String[] { annotatedTypeName(requiredType, this.options.nonNullAnnotationName) }; argumentsShort = new String[] { shortAnnotatedTypeName(requiredType, this.options.nonNullAnnotationName) }; } else { if (problemId == IProblem.NullNotCompatibleToFreeTypeVariable) { arguments = new String[] { new String(requiredType.sourceName()) }; // don't show any bounds argumentsShort = new String[] { new String(requiredType.sourceName()) }; } else { arguments = new String[] { new String(requiredType.nullAnnotatedReadableName(this.options, false)) }; argumentsShort = new String[] { new String(requiredType.nullAnnotatedReadableName(this.options, true)) }; } } this.handle(problemId, arguments, argumentsShort, expression.sourceStart, expression.sourceEnd); }
/** * 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; }
public Expression get(final ASTNode source, char[] name) { MessageSend call = new MessageSend(); call.sourceStart = source.sourceStart; call.sourceEnd = source.sourceEnd; call.nameSourcePosition = pos(source); setGeneratedBy(call, source); call.selector = name; call.receiver = new ThisReference(source.sourceStart, source.sourceEnd); setGeneratedBy(call.receiver, source); return call; }
public Expression get(final ASTNode source, char[] name) { FieldReference fieldRef = new FieldReference(name, pos(source)); setGeneratedBy(fieldRef, source); fieldRef.receiver = new ThisReference(source.sourceStart, source.sourceEnd); setGeneratedBy(fieldRef.receiver, source); return fieldRef; }
private static TypeBinding getForEachComponentType(Expression collection, BlockScope scope) { if (collection != null) { TypeBinding resolved = collection.resolvedType; if (resolved == null) resolved = resolveForExpression(collection, scope); if (resolved == null) return null; if (resolved.isArrayType()) { resolved = ((ArrayBinding) resolved).elementsType(); return resolved; } else if (resolved instanceof ReferenceBinding) { ReferenceBinding iterableType = ((ReferenceBinding)resolved).findSuperTypeOriginatingFrom(TypeIds.T_JavaLangIterable, false); TypeBinding[] arguments = null; if (iterableType != null) switch (iterableType.kind()) { case Binding.GENERIC_TYPE : // for (T t : Iterable<T>) - in case used inside Iterable itself arguments = iterableType.typeVariables(); break; case Binding.PARAMETERIZED_TYPE : // for(E e : Iterable<E>) arguments = ((ParameterizedTypeBinding)iterableType).arguments; break; case Binding.RAW_TYPE : // for(Object e : Iterable) return null; } if (arguments != null && arguments.length == 1) { return arguments[0]; } } } return null; }
private static TypeBinding resolveForExpression(Expression collection, BlockScope scope) { try { return collection.resolveType(scope); } catch (ArrayIndexOutOfBoundsException e) { // Known cause of issues; for example: val e = mth("X"), where mth takes 2 arguments. return null; } }
public static Annotation[] createConstructorProperties(ASTNode source, Collection<EclipseNode> fields) { if (fields.isEmpty()) return null; int pS = source.sourceStart, pE = source.sourceEnd; long p = (long) pS << 32 | pE; long[] poss = new long[3]; Arrays.fill(poss, p); QualifiedTypeReference constructorPropertiesType = new QualifiedTypeReference(JAVA_BEANS_CONSTRUCTORPROPERTIES, poss); setGeneratedBy(constructorPropertiesType, source); SingleMemberAnnotation ann = new SingleMemberAnnotation(constructorPropertiesType, pS); ann.declarationSourceEnd = pE; ArrayInitializer fieldNames = new ArrayInitializer(); fieldNames.sourceStart = pS; fieldNames.sourceEnd = pE; fieldNames.expressions = new Expression[fields.size()]; int ctr = 0; for (EclipseNode field : fields) { char[] fieldName = removePrefixFromField(field); fieldNames.expressions[ctr] = new StringLiteral(fieldName, pS, pE, 0); setGeneratedBy(fieldNames.expressions[ctr], source); ctr++; } ann.memberValue = fieldNames; setGeneratedBy(ann, source); setGeneratedBy(ann.memberValue, source); return new Annotation[] { ann }; }
private static Expression getDefaultExpr(TypeReference type, int s, int e) { char[] lastToken = type.getLastToken(); if (Arrays.equals(TypeConstants.BOOLEAN, lastToken)) return new FalseLiteral(s, e); if (Arrays.equals(TypeConstants.CHAR, lastToken)) return new CharLiteral(new char[] {'\'', '\\', '0', '\''}, s, e); if (Arrays.equals(TypeConstants.BYTE, lastToken) || Arrays.equals(TypeConstants.SHORT, lastToken) || Arrays.equals(TypeConstants.INT, lastToken)) return IntLiteral.buildIntLiteral(new char[] {'0'}, s, e); if (Arrays.equals(TypeConstants.LONG, lastToken)) return LongLiteral.buildLongLiteral(new char[] {'0', 'L'}, s, e); if (Arrays.equals(TypeConstants.FLOAT, lastToken)) return new FloatLiteral(new char[] {'0', 'F'}, s, e); if (Arrays.equals(TypeConstants.DOUBLE, lastToken)) return new DoubleLiteral(new char[] {'0', 'D'}, s, e); return new NullLiteral(s, e); }
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); }
@Override public void handle(AnnotationValues<SneakyThrows> annotation, Annotation source, EclipseNode annotationNode) { handleFlagUsage(annotationNode, ConfigurationKeys.SNEAKY_THROWS_FLAG_USAGE, "@SneakyThrows"); List<String> exceptionNames = annotation.getRawExpressions("value"); List<DeclaredException> exceptions = new ArrayList<DeclaredException>(); MemberValuePair[] memberValuePairs = source.memberValuePairs(); if (memberValuePairs == null || memberValuePairs.length == 0) { exceptions.add(new DeclaredException("java.lang.Throwable", source)); } else { Expression arrayOrSingle = memberValuePairs[0].value; final Expression[] exceptionNameNodes; if (arrayOrSingle instanceof ArrayInitializer) { exceptionNameNodes = ((ArrayInitializer)arrayOrSingle).expressions; } else exceptionNameNodes = new Expression[] { arrayOrSingle }; if (exceptionNames.size() != exceptionNameNodes.length) { annotationNode.addError( "LOMBOK BUG: The number of exception classes in the annotation isn't the same pre- and post- guessing."); } int idx = 0; for (String exceptionName : exceptionNames) { if (exceptionName.endsWith(".class")) exceptionName = exceptionName.substring(0, exceptionName.length() - 6); exceptions.add(new DeclaredException(exceptionName, exceptionNameNodes[idx++])); } } EclipseNode owner = annotationNode.up(); switch (owner.getKind()) { // case FIELD: // return handleField(annotationNode, (FieldDeclaration)owner.get(), exceptions); case METHOD: handleMethod(annotationNode, (AbstractMethodDeclaration)owner.get(), exceptions); break; default: annotationNode.addError("@SneakyThrows is legal only on methods and constructors."); } }
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; }