package org.eclipse.jdt.internal.compiler.ast;
import static org.eclipse.jdt.internal.compiler.ast.ExpressionContext.ASSIGNMENT_CONTEXT;
import static org.eclipse.jdt.internal.compiler.ast.ExpressionContext.VANILLA_CONTEXT;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.impl.*;
import org.eclipse.jdt.internal.compiler.ast.TypeReference.AnnotationCollector;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.flow.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.RecoveryScanner;
@SuppressWarnings("rawtypes")
public class LocalDeclaration extends AbstractVariableDeclaration {
public LocalVariableBinding binding;
public LocalDeclaration(
char[] name,
int sourceStart,
int sourceEnd) {
this.name = name;
this.sourceStart = sourceStart;
this.sourceEnd = sourceEnd;
this.declarationEnd = sourceEnd;
}
@Override
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0) {
this.bits |= ASTNode.IsLocalDeclarationReachable;
}
if (this.initialization == null) {
return flowInfo;
}
this.initialization.checkNPEbyUnboxing(currentScope, flowContext, flowInfo);
FlowInfo preInitInfo = null;
boolean shouldAnalyseResource = this.binding != null
&& flowInfo.reachMode() == FlowInfo.REACHABLE
&& currentScope.compilerOptions().analyseResourceLeaks
&& FakedTrackingVariable.isAnyCloseable(this.initialization.resolvedType);
if (shouldAnalyseResource) {
preInitInfo = flowInfo.unconditionalCopy();
FakedTrackingVariable.preConnectTrackerAcrossAssignment(this, this.binding, this.initialization, flowInfo);
}
flowInfo =
this.initialization
.analyseCode(currentScope, flowContext, flowInfo)
.unconditionalInits();
if (shouldAnalyseResource)
FakedTrackingVariable.handleResourceAssignment(currentScope, preInitInfo, flowInfo, flowContext, this, this.initialization, this.binding);
else
FakedTrackingVariable.cleanUpAfterAssignment(currentScope, Binding.LOCAL, this.initialization);
int nullStatus = this.initialization.nullStatus(flowInfo, flowContext);
if (!flowInfo.isDefinitelyAssigned(this.binding)){
this.bits |= FirstAssignmentToLocal;
} else {
this.bits &= ~FirstAssignmentToLocal;
}
flowInfo.markAsDefinitelyAssigned(this.binding);
if (currentScope.compilerOptions().isAnnotationBasedNullAnalysisEnabled) {
nullStatus = NullAnnotationMatching.checkAssignment(currentScope, flowContext, this.binding, flowInfo, nullStatus, this.initialization, this.initialization.resolvedType);
}
if ((this.binding.type.tagBits & TagBits.IsBaseType) == 0) {
flowInfo.markNullStatus(this.binding, nullStatus);
}
return flowInfo;
}
public void checkModifiers() {
if (((this.modifiers & ExtraCompilerModifiers.AccJustFlag) & ~ClassFileConstants.AccFinal) != 0)
this.modifiers = (this.modifiers & ~ExtraCompilerModifiers.AccAlternateModifierProblem) | ExtraCompilerModifiers.AccModifierProblem;
}
@Override
public void generateCode(BlockScope currentScope, CodeStream codeStream) {
if (this.binding.resolvedPosition != -1) {
codeStream.addVisibleLocalVariable(this.binding);
}
if ((this.bits & IsReachable) == 0) {
return;
}
int pc = codeStream.position;
generateInit: {
if (this.initialization == null)
break generateInit;
if (this.binding.resolvedPosition < 0) {
if (this.initialization.constant != Constant.NotAConstant)
break generateInit;
this.initialization.generateCode(currentScope, codeStream, false);
break generateInit;
}
this.initialization.generateCode(currentScope, codeStream, true);
if (this.binding.type.isArrayType()
&& ((this.initialization instanceof CastExpression)
&& (((CastExpression)this.initialization).innermostCastedExpression().resolvedType == TypeBinding.NULL))){
codeStream.checkcast(this.binding.type);
}
codeStream.store(this.binding, false);
if ((this.bits & ASTNode.FirstAssignmentToLocal) != 0) {
this.binding.recordInitializationStartPC(codeStream.position);
}
}
codeStream.recordPositionsFrom(pc, this.sourceStart);
}
@Override
public int getKind() {
return LOCAL_VARIABLE;
}
public void getAllAnnotationContexts(int targetType, LocalVariableBinding localVariable, List allAnnotationContexts) {
AnnotationCollector collector = new AnnotationCollector(this, targetType, localVariable, allAnnotationContexts);
this.traverseWithoutInitializer(collector, (BlockScope) null);
}
public void getAllAnnotationContexts(int targetType, int parameterIndex, List allAnnotationContexts) {
AnnotationCollector collector = new AnnotationCollector(this, targetType, parameterIndex, allAnnotationContexts);
this.traverse(collector, (BlockScope) null);
}
public boolean isArgument() {
return false;
}
public boolean isReceiver() {
return false;
}
public TypeBinding patchType(TypeBinding newType) {
TypeBinding[] mentionedTypeVariables= findCapturedTypeVariables(newType);
if (mentionedTypeVariables != null && mentionedTypeVariables.length > 0) {
newType = newType.upwardsProjection(this.binding.declaringScope, mentionedTypeVariables);
}
this.type.resolvedType = newType;
if (this.binding != null) {
this.binding.type = newType;
this.binding.markInitialized();
}
return this.type.resolvedType;
}
private TypeVariableBinding[] findCapturedTypeVariables(TypeBinding typeBinding) {
final Set<TypeVariableBinding> mentioned = new HashSet<>();
TypeBindingVisitor.visit(new TypeBindingVisitor() {
@Override
public boolean visit(TypeVariableBinding typeVariable) {
if (typeVariable.isCapture())
mentioned.add(typeVariable);
return super.visit(typeVariable);
}
}, typeBinding);
if (mentioned.isEmpty()) return null;
return mentioned.toArray(new TypeVariableBinding[mentioned.size()]);
}
private static Expression findPolyExpression(Expression e) {
if (e instanceof FunctionalExpression) {
return e;
}
if (e instanceof ConditionalExpression) {
ConditionalExpression ce = (ConditionalExpression)e;
Expression candidate = findPolyExpression(ce.valueIfTrue);
if (candidate == null) {
candidate = findPolyExpression(ce.valueIfFalse);
}
if (candidate != null) return candidate;
}
if (e instanceof SwitchExpression) {
SwitchExpression se = (SwitchExpression)e;
for (Expression re : se.resultExpressions) {
Expression candidate = findPolyExpression(re);
if (candidate != null) return candidate;
}
}
return null;
}
@Override
public void resolve(BlockScope scope) {
handleNonNullByDefault(scope, this.annotations, this);
TypeBinding variableType = null;
boolean variableTypeInferenceError = false;
boolean isTypeNameVar = isTypeNameVar(scope);
if (isTypeNameVar) {
if ((this.bits & ASTNode.IsForeachElementVariable) == 0) {
if (this.initialization != null) {
variableType = checkInferredLocalVariableInitializer(scope);
variableTypeInferenceError = variableType != null;
} else {
scope.problemReporter().varLocalWithoutInitizalier(this);
variableType = scope.getJavaLangObject();
variableTypeInferenceError = true;
}
}
} else {
variableType = this.type.resolveType(scope, true );
}
this.bits |= (this.type.bits & ASTNode.HasTypeAnnotations);
checkModifiers();
if (variableType != null) {
if (variableType == TypeBinding.VOID) {
scope.problemReporter().variableTypeCannotBeVoid(this);
return;
}
if (variableType.isArrayType() && ((ArrayBinding) variableType).leafComponentType == TypeBinding.VOID) {
scope.problemReporter().variableTypeCannotBeVoidArray(this);
return;
}
}
Binding existingVariable = scope.getBinding(this.name, Binding.VARIABLE, this, false );
if (existingVariable != null && existingVariable.isValidBinding()){
boolean localExists = existingVariable instanceof LocalVariableBinding;
if (localExists && (this.bits & ASTNode.ShadowsOuterLocal) != 0 && scope.isLambdaSubscope() && this.hiddenVariableDepth == 0) {
scope.problemReporter().lambdaRedeclaresLocal(this);
} else if (localExists && this.hiddenVariableDepth == 0) {
scope.problemReporter().redefineLocal(this);
} else {
scope.problemReporter().localVariableHiding(this, existingVariable, false);
}
}
if ((this.modifiers & ClassFileConstants.AccFinal)!= 0 && this.initialization == null) {
this.modifiers |= ExtraCompilerModifiers.AccBlankFinal;
}
if (isTypeNameVar) {
this.binding = new LocalVariableBinding(this, variableType != null ? variableType : scope.getJavaLangObject(), this.modifiers, false) {
private boolean isInitialized = false;
@Override
public void markReferenced() {
if (! this.isInitialized) {
scope.problemReporter().varLocalReferencesItself(LocalDeclaration.this);
this.type = null;
this.isInitialized = true;
}
}
@Override
public void markInitialized() {
this.isInitialized = true;
}
};
} else {
this.binding = new LocalVariableBinding(this, variableType, this.modifiers, false );
}
scope.addLocalVariable(this.binding);
this.binding.setConstant(Constant.NotAConstant);
if (variableType == null) {
if (this.initialization != null) {
this.initialization.resolveType(scope);
if (isTypeNameVar && this.initialization.resolvedType != null) {
if (TypeBinding.equalsEquals(TypeBinding.NULL, this.initialization.resolvedType)) {
scope.problemReporter().varLocalInitializedToNull(this);
variableTypeInferenceError = true;
} else if (TypeBinding.equalsEquals(TypeBinding.VOID, this.initialization.resolvedType)) {
scope.problemReporter().varLocalInitializedToVoid(this);
variableTypeInferenceError = true;
}
variableType = patchType(this.initialization.resolvedType);
} else {
variableTypeInferenceError = true;
}
}
}
this.binding.markInitialized();
if (variableTypeInferenceError) {
return;
}
boolean resolveAnnotationsEarly = false;
if (scope.environment().usesNullTypeAnnotations()
&& !isTypeNameVar
&& variableType != null && variableType.isValidBinding()) {
resolveAnnotationsEarly = this.initialization instanceof Invocation
|| this.initialization instanceof ConditionalExpression
|| this.initialization instanceof SwitchExpression
|| this.initialization instanceof ArrayInitializer;
}
if (resolveAnnotationsEarly) {
resolveAnnotations(scope, this.annotations, this.binding, true);
variableType = this.type.resolvedType;
}
if (this.initialization != null) {
if (this.initialization instanceof ArrayInitializer) {
TypeBinding initializationType = this.initialization.resolveTypeExpecting(scope, variableType);
if (initializationType != null) {
((ArrayInitializer) this.initialization).binding = (ArrayBinding) initializationType;
this.initialization.computeConversion(scope, variableType, initializationType);
}
} else {
this.initialization.setExpressionContext(isTypeNameVar ? VANILLA_CONTEXT : ASSIGNMENT_CONTEXT);
this.initialization.setExpectedType(variableType);
TypeBinding initializationType = this.initialization.resolvedType != null ? this.initialization.resolvedType : this.initialization.resolveType(scope);
if (initializationType != null) {
if (TypeBinding.notEquals(variableType, initializationType))
scope.compilationUnitScope().recordTypeConversion(variableType, initializationType);
if (this.initialization.isConstantValueOfTypeAssignableToType(initializationType, variableType)
|| initializationType.isCompatibleWith(variableType, scope)) {
this.initialization.computeConversion(scope, variableType, initializationType);
if (initializationType.needsUncheckedConversion(variableType)) {
scope.problemReporter().unsafeTypeConversion(this.initialization, initializationType, variableType);
}
if (this.initialization instanceof CastExpression
&& (this.initialization.bits & ASTNode.UnnecessaryCast) == 0) {
CastExpression.checkNeedForAssignedCast(scope, variableType, (CastExpression) this.initialization);
}
} else if (isBoxingCompatible(initializationType, variableType, this.initialization, scope)) {
this.initialization.computeConversion(scope, variableType, initializationType);
if (this.initialization instanceof CastExpression
&& (this.initialization.bits & ASTNode.UnnecessaryCast) == 0) {
CastExpression.checkNeedForAssignedCast(scope, variableType, (CastExpression) this.initialization);
}
} else {
if ((variableType.tagBits & TagBits.HasMissingType) == 0) {
scope.problemReporter().typeMismatchError(initializationType, variableType, this.initialization, null);
}
}
}
}
if (this.binding == Expression.getDirectBinding(this.initialization)) {
scope.problemReporter().assignmentHasNoEffect(this, this.name);
}
this.binding.setConstant(
this.binding.isFinal()
? this.initialization.constant.castTo((variableType.id << 4) + this.initialization.constant.typeID())
: Constant.NotAConstant);
}
if (!resolveAnnotationsEarly)
resolveAnnotations(scope, this.annotations, this.binding, true);
Annotation.isTypeUseCompatible(this.type, scope, this.annotations);
validateNullAnnotations(scope);
}
void validateNullAnnotations(BlockScope scope) {
if (!scope.validateNullAnnotation(this.binding.tagBits, this.type, this.annotations))
this.binding.tagBits &= ~TagBits.AnnotationNullMASK;
}
private TypeBinding checkInferredLocalVariableInitializer(BlockScope scope) {
TypeBinding errorType = null;
if (this.initialization instanceof ArrayInitializer) {
scope.problemReporter().varLocalCannotBeArrayInitalizers(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1);
} else {
Expression polyExpression = findPolyExpression(this.initialization);
if (polyExpression instanceof ReferenceExpression) {
scope.problemReporter().varLocalCannotBeMethodReference(this);
errorType = TypeBinding.NULL;
} else if (polyExpression != null) {
scope.problemReporter().varLocalCannotBeLambda(this);
errorType = TypeBinding.NULL;
}
}
if (this.type.dimensions() > 0 || this.type.extraDimensions() > 0) {
scope.problemReporter().varLocalCannotBeArray(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1);
}
if ((this.bits & ASTNode.IsAdditionalDeclarator) != 0) {
scope.problemReporter().varLocalMultipleDeclarators(this);
errorType = this.initialization.resolveType(scope);
}
return errorType;
}
@Override
public void traverse(ASTVisitor visitor, BlockScope scope) {
if (visitor.visit(this, scope)) {
if (this.annotations != null) {
int annotationsLength = this.annotations.length;
for (int i = 0; i < annotationsLength; i++)
this.annotations[i].traverse(visitor, scope);
}
this.type.traverse(visitor, scope);
if (this.initialization != null)
this.initialization.traverse(visitor, scope);
}
visitor.endVisit(this, scope);
}
private void traverseWithoutInitializer(ASTVisitor visitor, BlockScope scope) {
if (visitor.visit(this, scope)) {
if (this.annotations != null) {
int annotationsLength = this.annotations.length;
for (int i = 0; i < annotationsLength; i++)
this.annotations[i].traverse(visitor, scope);
}
this.type.traverse(visitor, scope);
}
visitor.endVisit(this, scope);
}
public boolean isRecoveredFromLoneIdentifier() {
return this.name == RecoveryScanner.FAKE_IDENTIFIER &&
(this.type instanceof SingleTypeReference || (this.type instanceof QualifiedTypeReference && !(this.type instanceof ArrayQualifiedTypeReference))) && this.initialization == null && !this.type.isBaseTypeReference();
}
public boolean isTypeNameVar(Scope scope) {
return this.type != null && this.type.isTypeNameVar(scope);
}
}