public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
    if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0) {
      // need assertion flag: $assertionsDisabled on outer most source clas
      // (in case of static member of interface, will use the outermost static member - bug 22334)
      SourceTypeBinding outerMostClass = currentScope.enclosingSourceType();
      while (outerMostClass.isLocalType()) {
        ReferenceBinding enclosing = outerMostClass.enclosingType();
        if (enclosing == null || enclosing.isInterface()) break;
        outerMostClass = (SourceTypeBinding) enclosing;
      }
      this.assertionSyntheticFieldBinding = outerMostClass.addSyntheticFieldForAssert(currentScope);

      // find <clinit> and enable assertion support
      TypeDeclaration typeDeclaration = outerMostClass.scope.referenceType();
      AbstractMethodDeclaration[] methods = typeDeclaration.methods;
      for (int i = 0, max = methods.length; i < max; i++) {
        AbstractMethodDeclaration method = methods[i];
        if (method.isClinit()) {
          ((Clinit) method)
              .setAssertionSupport(
                  this.assertionSyntheticFieldBinding,
                  currentScope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_5);
          break;
        }
      }
    }
  }
Example #2
0
  /* (non-Javadoc)
   * @see org.eclipse.jdt.internal.compiler.ast.SubRoutineStatement#generateSubRoutineInvocation(org.eclipse.jdt.internal.compiler.lookup.BlockScope, org.eclipse.jdt.internal.compiler.codegen.CodeStream)
   */
  public void generateSubRoutineInvocation(BlockScope currentScope, CodeStream codeStream) {

    if (this.isSubRoutineEscaping) {
      codeStream.goto_(this.subRoutineStartLabel);
    } else {
      if (currentScope.compilerOptions().inlineJsrBytecode) {
        // cannot use jsr bytecode, then simply inline the subroutine
        this.exitAnyExceptionHandler();
        this.finallyBlock.generateCode(currentScope, codeStream);
        this.enterAnyExceptionHandler(codeStream);
      } else {
        // classic subroutine invocation, distinguish case of non-returning subroutine
        codeStream.jsr(this.subRoutineStartLabel);
      }
    }
  }
  public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {

    // {ObjectTeams: role class literal?
    if (this.roleClassLiteralAccess != null)
      return this.roleClassLiteralAccess.analyseCode(currentScope, flowContext, flowInfo);
    // SH}
    // if reachable, request the addition of a synthetic field for caching the class descriptor
    SourceTypeBinding sourceType = currentScope.outerMostClassScope().enclosingSourceType();
    // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=22334
    if (!sourceType.isInterface()
        && !this.targetType.isBaseType()
        && currentScope.compilerOptions().targetJDK < ClassFileConstants.JDK1_5) {
      this.syntheticField =
          sourceType.addSyntheticFieldForClassLiteral(this.targetType, currentScope);
    }
    return flowInfo;
  }
 public void checkTypeArgumentRedundancy(
     ParameterizedTypeBinding allocationType,
     ReferenceBinding enclosingType,
     TypeBinding[] argumentTypes,
     final BlockScope scope) {
   ProblemReporter reporter = scope.problemReporter();
   if ((reporter.computeSeverity(IProblem.RedundantSpecificationOfTypeArguments)
           == ProblemSeverities.Ignore)
       || scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_7) return;
   if (allocationType.arguments == null) return; // raw binding
   if (this.genericTypeArguments != null)
     return; // diamond can't occur with explicit type args for constructor
   if (argumentTypes == Binding.NO_PARAMETERS
       && this.typeExpected instanceof ParameterizedTypeBinding) {
     ParameterizedTypeBinding expected = (ParameterizedTypeBinding) this.typeExpected;
     if (expected.arguments != null
         && allocationType.arguments.length == expected.arguments.length) {
       // check the case when no ctor takes no params and inference uses the expected type directly
       // eg. X<String> x = new X<String>()
       int i;
       for (i = 0; i < allocationType.arguments.length; i++) {
         if (allocationType.arguments[i] != expected.arguments[i]) break;
       }
       if (i == allocationType.arguments.length) {
         reporter.redundantSpecificationOfTypeArguments(this.type, allocationType.arguments);
         return;
       }
     }
   }
   TypeBinding[] inferredTypes =
       inferElidedTypes(allocationType.genericType(), enclosingType, argumentTypes, scope);
   if (inferredTypes == null) {
     return;
   }
   for (int i = 0; i < inferredTypes.length; i++) {
     if (inferredTypes[i] != allocationType.arguments[i]) return;
   }
   reporter.redundantSpecificationOfTypeArguments(this.type, allocationType.arguments);
 }
  public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
    if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0) return;
    // if constructor from parameterized type got found, use the original constructor at codegen
    // time
    MethodBinding codegenBinding = this.binding.original();

    ReferenceBinding declaringClass;
    if (codegenBinding.isPrivate()
        && currentScope.enclosingSourceType() != (declaringClass = codegenBinding.declaringClass)) {

      // from 1.4 on, local type constructor can lose their private flag to ease emulation
      if ((declaringClass.tagBits & TagBits.IsLocalType) != 0
          && currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
        // constructor will not be dumped as private, no emulation required thus
        codegenBinding.tagBits |= TagBits.ClearPrivateModifier;
      } else {
        this.syntheticAccessor =
            ((SourceTypeBinding) declaringClass)
                .addSyntheticMethod(codegenBinding, isSuperAccess());
        currentScope.problemReporter().needToEmulateMethodAccess(codegenBinding, this);
      }
    }
  }
Example #6
0
  public void resolve(BlockScope upperScope) {

    // special scope for secret locals optimization.
    this.scope = new BlockScope(upperScope);

    BlockScope tryScope = new BlockScope(scope);
    BlockScope finallyScope = null;

    if (finallyBlock != null) {
      if (finallyBlock.isEmptyBlock()) {
        if ((finallyBlock.bits & UndocumentedEmptyBlockMASK) != 0) {
          scope
              .problemReporter()
              .undocumentedEmptyBlock(finallyBlock.sourceStart, finallyBlock.sourceEnd);
        }
      } else {
        finallyScope = new BlockScope(scope, false); // don't add it yet to parent scope

        // provision for returning and forcing the finally block to run
        MethodScope methodScope = scope.methodScope();

        // the type does not matter as long as it is not a base type
        if (!upperScope.compilerOptions().inlineJsrBytecode) {
          this.returnAddressVariable =
              new LocalVariableBinding(
                  SecretReturnName, upperScope.getJavaLangObject(), AccDefault, false);
          finallyScope.addLocalVariable(returnAddressVariable);
          this.returnAddressVariable.setConstant(NotAConstant); // not inlinable
        }
        this.subRoutineStartLabel = new Label();

        this.anyExceptionVariable =
            new LocalVariableBinding(
                SecretAnyHandlerName, scope.getJavaLangThrowable(), AccDefault, false);
        finallyScope.addLocalVariable(this.anyExceptionVariable);
        this.anyExceptionVariable.setConstant(NotAConstant); // not inlinable

        if (!methodScope.isInsideInitializer()) {
          MethodBinding methodBinding =
              ((AbstractMethodDeclaration) methodScope.referenceContext).binding;
          if (methodBinding != null) {
            TypeBinding methodReturnType = methodBinding.returnType;
            if (methodReturnType.id != T_void) {
              this.secretReturnValue =
                  new LocalVariableBinding(
                      SecretLocalDeclarationName, methodReturnType, AccDefault, false);
              finallyScope.addLocalVariable(this.secretReturnValue);
              this.secretReturnValue.setConstant(NotAConstant); // not inlinable
            }
          }
        }
        finallyBlock.resolveUsing(finallyScope);
        // force the finally scope to have variable positions shifted after its try scope and catch
        // ones
        finallyScope.shiftScopes =
            new BlockScope[catchArguments == null ? 1 : catchArguments.length + 1];
        finallyScope.shiftScopes[0] = tryScope;
      }
    }
    this.tryBlock.resolveUsing(tryScope);

    // arguments type are checked against JavaLangThrowable in resolveForCatch(..)
    if (this.catchBlocks != null) {
      int length = this.catchArguments.length;
      TypeBinding[] argumentTypes = new TypeBinding[length];
      boolean catchHasError = false;
      for (int i = 0; i < length; i++) {
        BlockScope catchScope = new BlockScope(scope);
        if (finallyScope != null) {
          finallyScope.shiftScopes[i + 1] = catchScope;
        }
        // side effect on catchScope in resolveForCatch(..)
        if ((argumentTypes[i] = catchArguments[i].resolveForCatch(catchScope)) == null) {
          catchHasError = true;
        }
        catchBlocks[i].resolveUsing(catchScope);
      }
      if (catchHasError) {
        return;
      }
      // Verify that the catch clause are ordered in the right way:
      // more specialized first.
      this.caughtExceptionTypes = new ReferenceBinding[length];
      for (int i = 0; i < length; i++) {
        caughtExceptionTypes[i] = (ReferenceBinding) argumentTypes[i];
        for (int j = 0; j < i; j++) {
          if (caughtExceptionTypes[i].isCompatibleWith(argumentTypes[j])) {
            scope
                .problemReporter()
                .wrongSequenceOfExceptionTypesError(
                    this, caughtExceptionTypes[i], i, argumentTypes[j]);
          }
        }
      }
    } else {
      caughtExceptionTypes = new ReferenceBinding[0];
    }

    if (finallyScope != null) {
      // add finallyScope as last subscope, so it can be shifted behind try/catch subscopes.
      // the shifting is necessary to achieve no overlay in between the finally scope and its
      // sibling in term of local variable positions.
      this.scope.addSubscope(finallyScope);
    }
  }
Example #7
0
  /**
   * Try statement code generation with or without jsr bytecode use post 1.5 target level, cannot
   * use jsr bytecode, must instead inline finally block returnAddress is only allocated if jsr is
   * allowed
   */
  public void generateCode(BlockScope currentScope, CodeStream codeStream) {
    if ((bits & IsReachableMASK) == 0) {
      return;
    }
    // in case the labels needs to be reinitialized
    // when the code generation is restarted in wide mode
    if (this.anyExceptionLabelsCount > 0) {
      this.anyExceptionLabels = NO_EXCEPTION_HANDLER;
      this.anyExceptionLabelsCount = 0;
    }
    int pc = codeStream.position;
    final int NO_FINALLY = 0; // no finally block
    final int FINALLY_SUBROUTINE =
        1; // finally is generated as a subroutine (using jsr/ret bytecodes)
    final int FINALLY_DOES_NOT_COMPLETE =
        2; // non returning finally is optimized with only one instance of finally block
    final int FINALLY_MUST_BE_INLINED =
        3; // finally block must be inlined since cannot use jsr/ret bytecodes >1.5
    int finallyMode;
    if (subRoutineStartLabel == null) {
      finallyMode = NO_FINALLY;
    } else {
      if (this.isSubRoutineEscaping) {
        finallyMode = FINALLY_DOES_NOT_COMPLETE;
      } else if (scope.compilerOptions().inlineJsrBytecode) {
        finallyMode = FINALLY_MUST_BE_INLINED;
      } else {
        finallyMode = FINALLY_SUBROUTINE;
      }
    }
    boolean requiresNaturalExit = false;
    // preparing exception labels
    int maxCatches;
    ExceptionLabel[] exceptionLabels =
        new ExceptionLabel[maxCatches = catchArguments == null ? 0 : catchArguments.length];
    for (int i = 0; i < maxCatches; i++) {
      exceptionLabels[i] = new ExceptionLabel(codeStream, catchArguments[i].binding.type);
    }
    if (subRoutineStartLabel != null) {
      subRoutineStartLabel.initialize(codeStream);
      this.enterAnyExceptionHandler(codeStream);
    }
    // generate the try block
    tryBlock.generateCode(scope, codeStream);
    boolean tryBlockHasSomeCode = codeStream.position != pc;
    // flag telling if some bytecodes were issued inside the try block

    // place end positions of user-defined exception labels
    if (tryBlockHasSomeCode) {
      // natural exit may require subroutine invocation (if finally != null)
      Label naturalExitLabel = new Label(codeStream);
      if (!tryBlockExit) {
        int position = codeStream.position;
        switch (finallyMode) {
          case FINALLY_SUBROUTINE:
          case FINALLY_MUST_BE_INLINED:
            requiresNaturalExit = true;
            // fall through
          case NO_FINALLY:
            codeStream.goto_(naturalExitLabel);
            break;
          case FINALLY_DOES_NOT_COMPLETE:
            codeStream.goto_(subRoutineStartLabel);
            break;
        }
        codeStream.updateLastRecordedEndPC(tryBlock.scope, position);
        // goto is tagged as part of the try block
      }
      for (int i = 0; i < maxCatches; i++) {
        exceptionLabels[i].placeEnd();
      }
      /* generate sequence of handler, all starting by storing the TOS (exception
      thrown) into their own catch variables, the one specified in the source
      that must denote the handled exception.
      */
      if (catchArguments != null) {
        for (int i = 0; i < maxCatches; i++) {
          // May loose some local variable initializations : affecting the local variable attributes
          if (preTryInitStateIndex != -1) {
            codeStream.removeNotDefinitelyAssignedVariables(currentScope, preTryInitStateIndex);
          }
          exceptionLabels[i].place();
          codeStream.incrStackSize(1);
          // optimizing the case where the exception variable is not actually used
          LocalVariableBinding catchVar;
          int varPC = codeStream.position;
          if ((catchVar = catchArguments[i].binding).resolvedPosition != -1) {
            codeStream.store(catchVar, false);
            catchVar.recordInitializationStartPC(codeStream.position);
            codeStream.addVisibleLocalVariable(catchVar);
          } else {
            codeStream.pop();
          }
          codeStream.recordPositionsFrom(varPC, catchArguments[i].sourceStart);
          // Keep track of the pcs at diverging point for computing the local attribute
          // since not passing the catchScope, the block generation will exitUserScope(catchScope)
          catchBlocks[i].generateCode(scope, codeStream);
          if (!catchExits[i]) {
            switch (finallyMode) {
              case FINALLY_SUBROUTINE:
              case FINALLY_MUST_BE_INLINED:
                requiresNaturalExit = true;
                // fall through
              case NO_FINALLY:
                codeStream.goto_(naturalExitLabel);
                break;
              case FINALLY_DOES_NOT_COMPLETE:
                codeStream.goto_(subRoutineStartLabel);
                break;
            }
          }
        }
      }
      this.exitAnyExceptionHandler();
      // extra handler for trailing natural exit (will be fixed up later on when natural exit is
      // generated below)
      ExceptionLabel naturalExitExceptionHandler =
          finallyMode == FINALLY_SUBROUTINE && requiresNaturalExit
              ? new ExceptionLabel(codeStream, null)
              : null;

      // addition of a special handler so as to ensure that any uncaught exception (or exception
      // thrown
      // inside catch blocks) will run the finally block
      int finallySequenceStartPC = codeStream.position;
      if (subRoutineStartLabel != null) {
        this.placeAllAnyExceptionHandlers();
        if (naturalExitExceptionHandler != null) naturalExitExceptionHandler.place();

        if (preTryInitStateIndex != -1) {
          // reset initialization state, as for a normal catch block
          codeStream.removeNotDefinitelyAssignedVariables(currentScope, preTryInitStateIndex);
        }

        codeStream.incrStackSize(1);
        switch (finallyMode) {
          case FINALLY_SUBROUTINE:
            codeStream.store(anyExceptionVariable, false);
            codeStream.jsr(subRoutineStartLabel);
            codeStream.recordPositionsFrom(finallySequenceStartPC, finallyBlock.sourceStart);
            int position = codeStream.position;
            codeStream.load(anyExceptionVariable);
            codeStream.athrow();
            codeStream.recordPositionsFrom(position, finallyBlock.sourceEnd);
            subRoutineStartLabel.place();
            codeStream.incrStackSize(1);
            position = codeStream.position;
            codeStream.store(returnAddressVariable, false);
            codeStream.recordPositionsFrom(position, finallyBlock.sourceStart);
            finallyBlock.generateCode(scope, codeStream);
            position = codeStream.position;
            codeStream.ret(returnAddressVariable.resolvedPosition);
            //						codeStream.updateLastRecordedEndPC(position);
            codeStream.recordPositionsFrom(position, finallyBlock.sourceEnd);
            // the ret bytecode is part of the subroutine
            break;
          case FINALLY_MUST_BE_INLINED:
            codeStream.store(anyExceptionVariable, false);
            codeStream.recordPositionsFrom(finallySequenceStartPC, finallyBlock.sourceStart);
            this.finallyBlock.generateCode(currentScope, codeStream);
            position = codeStream.position;
            codeStream.load(anyExceptionVariable);
            codeStream.athrow();
            subRoutineStartLabel.place();
            codeStream.recordPositionsFrom(position, finallyBlock.sourceEnd);
            break;
          case FINALLY_DOES_NOT_COMPLETE:
            codeStream.pop();
            subRoutineStartLabel.place();
            codeStream.recordPositionsFrom(finallySequenceStartPC, finallyBlock.sourceStart);
            finallyBlock.generateCode(scope, codeStream);
            break;
        }
        // will naturally fall into subsequent code after subroutine invocation
        naturalExitLabel.place();
        if (requiresNaturalExit) {
          switch (finallyMode) {
            case FINALLY_SUBROUTINE:
              int position = codeStream.position;
              // fix up natural exit handler
              naturalExitExceptionHandler.placeStart();
              codeStream.jsr(subRoutineStartLabel);
              naturalExitExceptionHandler.placeEnd();
              codeStream.recordPositionsFrom(position, finallyBlock.sourceEnd);
              break;
            case FINALLY_MUST_BE_INLINED:
              // May loose some local variable initializations : affecting the local variable
              // attributes
              // needed since any exception handler got inlined subroutine
              if (preTryInitStateIndex != -1) {
                codeStream.removeNotDefinitelyAssignedVariables(currentScope, preTryInitStateIndex);
              }
              // entire sequence for finally is associated to finally block
              finallyBlock.generateCode(scope, codeStream);
              break;
            case FINALLY_DOES_NOT_COMPLETE:
              break;
          }
        }
      } else {
        // no subroutine, simply position end label (natural exit == end)
        naturalExitLabel.place();
      }
    } else {
      // try block had no effect, only generate the body of the finally block if any
      if (subRoutineStartLabel != null) {
        finallyBlock.generateCode(scope, codeStream);
      }
    }
    // May loose some local variable initializations : affecting the local variable attributes
    if (mergedInitStateIndex != -1) {
      codeStream.removeNotDefinitelyAssignedVariables(currentScope, mergedInitStateIndex);
      codeStream.addDefinitelyAssignedVariables(currentScope, mergedInitStateIndex);
    }
    codeStream.recordPositionsFrom(pc, this.sourceStart);
  }
 /** Analysing arguments of MessageSend, ExplicitConstructorCall, AllocationExpression. */
 protected void analyseArguments(
     BlockScope currentScope,
     FlowContext flowContext,
     FlowInfo flowInfo,
     MethodBinding methodBinding,
     Expression[] arguments) {
   // compare actual null-status against parameter annotations of the called method:
   if (arguments != null) {
     CompilerOptions compilerOptions = currentScope.compilerOptions();
     boolean considerTypeAnnotations =
         compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8
             && compilerOptions.isAnnotationBasedNullAnalysisEnabled;
     boolean hasJDK15NullAnnotations = methodBinding.parameterNonNullness != null;
     int numParamsToCheck = methodBinding.parameters.length;
     if (considerTypeAnnotations || hasJDK15NullAnnotations) {
       // check if varargs need special treatment:
       boolean passThrough = false;
       if (methodBinding.isVarargs()) {
         int varArgPos = numParamsToCheck - 1;
         // this if-block essentially copied from generateArguments(..):
         if (numParamsToCheck == arguments.length) {
           TypeBinding varArgsType = methodBinding.parameters[varArgPos];
           TypeBinding lastType = arguments[varArgPos].resolvedType;
           if (lastType == TypeBinding.NULL
               || (varArgsType.dimensions() == lastType.dimensions()
                   && lastType.isCompatibleWith(varArgsType)))
             passThrough = true; // pass directly as-is
         }
         if (!passThrough)
           numParamsToCheck--; // with non-passthrough varargs last param is fed from individual
         // args -> don't check
       }
     }
     if (considerTypeAnnotations) {
       for (int i = 0; i < numParamsToCheck; i++) {
         TypeBinding expectedType = methodBinding.parameters[i];
         Expression argument = arguments[i];
         // prefer check based on type annotations:
         int severity = findNullTypeAnnotationMismatch(expectedType, argument.resolvedType);
         if (severity > 0) {
           // immediate reporting:
           currentScope
               .problemReporter()
               .nullityMismatchingTypeAnnotation(
                   argument,
                   argument.resolvedType,
                   expectedType,
                   severity == 1,
                   currentScope.environment());
           // next check flow-based null status against null JDK15-style annotations:
         } else if (hasJDK15NullAnnotations
             && methodBinding.parameterNonNullness[i] == Boolean.TRUE) {
           int nullStatus =
               argument.nullStatus(
                   flowInfo,
                   flowContext); // slight loss of precision: should also use the null info from
           // the receiver.
           if (nullStatus != FlowInfo.NON_NULL) // if required non-null is not provided
           flowContext.recordNullityMismatch(
                 currentScope, argument, argument.resolvedType, expectedType, nullStatus);
         }
       }
     } else if (hasJDK15NullAnnotations) {
       for (int i = 0; i < numParamsToCheck; i++) {
         if (methodBinding.parameterNonNullness[i] == Boolean.TRUE) {
           TypeBinding expectedType = methodBinding.parameters[i];
           Expression argument = arguments[i];
           int nullStatus =
               argument.nullStatus(
                   flowInfo,
                   flowContext); // slight loss of precision: should also use the null info from
           // the receiver.
           if (nullStatus != FlowInfo.NON_NULL) // if required non-null is not provided
           flowContext.recordNullityMismatch(
                 currentScope, argument, argument.resolvedType, expectedType, nullStatus);
         }
       }
     }
   }
 }
  public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
    this.preAssertInitStateIndex = currentScope.methodScope().recordInitializationStates(flowInfo);

    Constant cst = this.assertExpression.optimizedBooleanConstant();
    if ((this.assertExpression.implicitConversion & TypeIds.UNBOXING) != 0) {
      this.assertExpression.checkNPE(currentScope, flowContext, flowInfo);
    }
    boolean isOptimizedTrueAssertion = cst != Constant.NotAConstant && cst.booleanValue() == true;
    boolean isOptimizedFalseAssertion = cst != Constant.NotAConstant && cst.booleanValue() == false;

    flowContext.tagBits |= FlowContext.HIDE_NULL_COMPARISON_WARNING;
    FlowInfo conditionFlowInfo =
        this.assertExpression.analyseCode(currentScope, flowContext, flowInfo.copy());
    flowContext.extendTimeToLiveForNullCheckedField(1); // survive this assert as a Statement
    flowContext.tagBits &= ~FlowContext.HIDE_NULL_COMPARISON_WARNING;
    UnconditionalFlowInfo assertWhenTrueInfo =
        conditionFlowInfo.initsWhenTrue().unconditionalInits();
    FlowInfo assertInfo = conditionFlowInfo.initsWhenFalse();
    if (isOptimizedTrueAssertion) {
      assertInfo.setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
    }

    if (this.exceptionArgument != null) {
      // only gets evaluated when escaping - results are not taken into account
      FlowInfo exceptionInfo =
          this.exceptionArgument.analyseCode(currentScope, flowContext, assertInfo.copy());

      if (isOptimizedTrueAssertion) {
        currentScope.problemReporter().fakeReachable(this.exceptionArgument);
      } else {
        flowContext.checkExceptionHandlers(
            currentScope.getJavaLangAssertionError(), this, exceptionInfo, currentScope);
      }
    }

    if (!isOptimizedTrueAssertion) {
      // add the assert support in the clinit
      manageSyntheticAccessIfNecessary(currentScope, flowInfo);
    }
    // account for potential AssertionError:
    flowContext.recordAbruptExit();
    if (isOptimizedFalseAssertion) {
      return flowInfo; // if assertions are enabled, the following code will be unreachable
      // change this if we need to carry null analysis results of the assert
      // expression downstream
    } else {
      CompilerOptions compilerOptions = currentScope.compilerOptions();
      if (!compilerOptions.includeNullInfoFromAsserts) {
        // keep just the initializations info, don't include assert's null info
        // merge initialization info's and then add back the null info from flowInfo to
        // make sure that the empty null info of assertInfo doesnt change flowInfo's null info.
        return ((flowInfo.nullInfoLessUnconditionalCopy())
                .mergedWith(assertInfo.nullInfoLessUnconditionalCopy()))
            .addNullInfoFrom(flowInfo);
      }
      return flowInfo
          .mergedWith(assertInfo.nullInfoLessUnconditionalCopy())
          .addInitializationsFrom(assertWhenTrueInfo.discardInitializationInfo());
      // keep the merge from the initial code for the definite assignment
      // analysis, tweak the null part to influence nulls downstream
    }
  }
  public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
    // check captured variables are initialized in current context (26134)
    checkCapturedLocalInitializationIfNecessary(
        (ReferenceBinding) this.binding.declaringClass.erasure(), currentScope, flowInfo);

    // process arguments
    if (this.arguments != null) {
      boolean analyseResources = currentScope.compilerOptions().analyseResourceLeaks;
      boolean hasResourceWrapperType =
          analyseResources
              && this.resolvedType instanceof ReferenceBinding
              && ((ReferenceBinding) this.resolvedType).hasTypeBit(TypeIds.BitWrapperCloseable);
      for (int i = 0, count = this.arguments.length; i < count; i++) {
        flowInfo =
            this.arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();
        // if argument is an AutoCloseable insert info that it *may* be closed (by the target
        // method, i.e.)
        if (analyseResources
            && !hasResourceWrapperType) { // allocation of wrapped closeables is analyzed specially
          flowInfo =
              FakedTrackingVariable.markPassedToOutside(
                  currentScope, this.arguments[i], flowInfo, flowContext, false);
        }
        this.arguments[i].checkNPEbyUnboxing(currentScope, flowContext, flowInfo);
      }
      analyseArguments(currentScope, flowContext, flowInfo, this.binding, this.arguments);
    }

    // record some dependency information for exception types
    ReferenceBinding[] thrownExceptions;
    if (((thrownExceptions = this.binding.thrownExceptions).length) != 0) {
      if ((this.bits & ASTNode.Unchecked) != 0 && this.genericTypeArguments == null) {
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=277643, align with javac on JLS 15.12.2.6
        thrownExceptions =
            currentScope.environment().convertToRawTypes(this.binding.thrownExceptions, true, true);
      }
      // check exception handling
      flowContext.checkExceptionHandlers(
          thrownExceptions, this, flowInfo.unconditionalCopy(), currentScope);
    }

    // after having analysed exceptions above start tracking newly allocated resource:
    if (currentScope.compilerOptions().analyseResourceLeaks
        && FakedTrackingVariable.isAnyCloseable(this.resolvedType))
      FakedTrackingVariable.analyseCloseableAllocation(currentScope, flowInfo, this);

    if (this.binding.declaringClass.isMemberType() && !this.binding.declaringClass.isStatic()) {
      // allocating a non-static member type without an enclosing instance of parent type
      // https://bugs.eclipse.org/bugs/show_bug.cgi?id=335845
      currentScope.resetDeclaringClassMethodStaticFlag(this.binding.declaringClass.enclosingType());
      // Reviewed for https://bugs.eclipse.org/bugs/show_bug.cgi?id=378674 :
      // The corresponding problem (when called from static) is not produced until during code
      // generation
    }
    manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
    manageSyntheticAccessIfNecessary(currentScope, flowInfo);

    // account for possible exceptions thrown by the constructor
    flowContext.recordAbruptExit(); // TODO whitelist of ctors that cannot throw any exc.??

    return flowInfo;
  }
  public TypeBinding resolveType(BlockScope scope) {
    // Propagate the type checking to the arguments, and check if the constructor is defined.
    this.constant = Constant.NotAConstant;
    if (this.type == null) {
      // initialization of an enum constant
      this.resolvedType = scope.enclosingReceiverType();
    } else {
      this.resolvedType = this.type.resolveType(scope, true /* check bounds*/);
      checkParameterizedAllocation:
      {
        if (this.type
            instanceof ParameterizedQualifiedTypeReference) { // disallow new X<String>.Y<Integer>()
          ReferenceBinding currentType = (ReferenceBinding) this.resolvedType;
          if (currentType == null) return currentType;
          do {
            // isStatic() is answering true for toplevel types
            if ((currentType.modifiers & ClassFileConstants.AccStatic) != 0)
              break checkParameterizedAllocation;
            if (currentType.isRawType()) break checkParameterizedAllocation;
          } while ((currentType = currentType.enclosingType()) != null);
          ParameterizedQualifiedTypeReference qRef =
              (ParameterizedQualifiedTypeReference) this.type;
          for (int i = qRef.typeArguments.length - 2; i >= 0; i--) {
            if (qRef.typeArguments[i] != null) {
              scope
                  .problemReporter()
                  .illegalQualifiedParameterizedTypeAllocation(this.type, this.resolvedType);
              break;
            }
          }
        }
      }
    }
    // will check for null after args are resolved

    final boolean isDiamond = this.type != null && (this.type.bits & ASTNode.IsDiamond) != 0;
    // resolve type arguments (for generic constructor call)
    if (this.typeArguments != null) {
      int length = this.typeArguments.length;
      boolean argHasError = scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_5;
      this.genericTypeArguments = new TypeBinding[length];
      for (int i = 0; i < length; i++) {
        TypeReference typeReference = this.typeArguments[i];
        if ((this.genericTypeArguments[i] =
                typeReference.resolveType(scope, true /* check bounds*/))
            == null) {
          argHasError = true;
        }
        if (argHasError && typeReference instanceof Wildcard) {
          scope.problemReporter().illegalUsageOfWildcard(typeReference);
        }
      }
      if (isDiamond) {
        scope.problemReporter().diamondNotWithExplicitTypeArguments(this.typeArguments);
        return null;
      }
      if (argHasError) {
        if (this.arguments != null) { // still attempt to resolve arguments
          for (int i = 0, max = this.arguments.length; i < max; i++) {
            this.arguments[i].resolveType(scope);
          }
        }
        return null;
      }
    }

    // buffering the arguments' types
    boolean argsContainCast = false;
    TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
    if (this.arguments != null) {
      boolean argHasError = false;
      int length = this.arguments.length;
      argumentTypes = new TypeBinding[length];
      for (int i = 0; i < length; i++) {
        Expression argument = this.arguments[i];
        if (argument instanceof CastExpression) {
          argument.bits |= DisableUnnecessaryCastCheck; // will check later on
          argsContainCast = true;
        }
        if ((argumentTypes[i] = argument.resolveType(scope)) == null) {
          argHasError = true;
        }
      }
      if (argHasError) {
        /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=345359, if arguments have errors, completely bail out in the <> case.
          No meaningful type resolution is possible since inference of the elided types is fully tied to argument types. Do
          not return the partially resolved type.
        */
        if (isDiamond) {
          return null; // not the partially cooked this.resolvedType
        }
        if (this.resolvedType instanceof ReferenceBinding) {
          // record a best guess, for clients who need hint about possible constructor match
          TypeBinding[] pseudoArgs = new TypeBinding[length];
          for (int i = length; --i >= 0; ) {
            pseudoArgs[i] =
                argumentTypes[i] == null
                    ? TypeBinding.NULL
                    : argumentTypes[i]; // replace args with errors with null type
          }
          this.binding =
              scope.findMethod(
                  (ReferenceBinding) this.resolvedType, TypeConstants.INIT, pseudoArgs, this);
          if (this.binding != null && !this.binding.isValidBinding()) {
            MethodBinding closestMatch = ((ProblemMethodBinding) this.binding).closestMatch;
            // record the closest match, for clients who may still need hint about possible method
            // match
            if (closestMatch != null) {
              if (closestMatch.original().typeVariables
                  != Binding.NO_TYPE_VARIABLES) { // generic method
                // shouldn't return generic method outside its context, rather convert it to raw
                // method (175409)
                closestMatch =
                    scope
                        .environment()
                        .createParameterizedGenericMethod(
                            closestMatch.original(), (RawTypeBinding) null);
              }
              this.binding = closestMatch;
              MethodBinding closestMatchOriginal = closestMatch.original();
              if (closestMatchOriginal.isOrEnclosedByPrivateType()
                  && !scope.isDefinedInMethod(closestMatchOriginal)) {
                // ignore cases where method is used from within inside itself (e.g. direct
                // recursions)
                closestMatchOriginal.modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
              }
            }
          }
        }
        return this.resolvedType;
      }
    }
    if (this.resolvedType == null || !this.resolvedType.isValidBinding()) {
      return null;
    }

    // null type denotes fake allocation for enum constant inits
    if (this.type != null && !this.resolvedType.canBeInstantiated()) {
      scope.problemReporter().cannotInstantiate(this.type, this.resolvedType);
      return this.resolvedType;
    }
    if (isDiamond) {
      TypeBinding[] inferredTypes =
          inferElidedTypes(
              ((ParameterizedTypeBinding) this.resolvedType).genericType(),
              null,
              argumentTypes,
              scope);
      if (inferredTypes == null) {
        scope.problemReporter().cannotInferElidedTypes(this);
        return this.resolvedType = null;
      }
      this.resolvedType =
          this.type.resolvedType =
              scope
                  .environment()
                  .createParameterizedType(
                      ((ParameterizedTypeBinding) this.resolvedType).genericType(),
                      inferredTypes,
                      ((ParameterizedTypeBinding) this.resolvedType).enclosingType());
    }
    ReferenceBinding allocationType = (ReferenceBinding) this.resolvedType;
    if (!(this.binding = scope.getConstructor(allocationType, argumentTypes, this))
        .isValidBinding()) {
      if (this.binding.declaringClass == null) {
        this.binding.declaringClass = allocationType;
      }
      if (this.type != null && !this.type.resolvedType.isValidBinding()) {
        return null;
      }
      scope.problemReporter().invalidConstructor(this, this.binding);
      return this.resolvedType;
    }
    if ((this.binding.tagBits & TagBits.HasMissingType) != 0) {
      scope.problemReporter().missingTypeInConstructor(this, this.binding);
    }
    if (isMethodUseDeprecated(this.binding, scope, true))
      scope.problemReporter().deprecatedMethod(this.binding, this);
    if (checkInvocationArguments(
        scope,
        null,
        allocationType,
        this.binding,
        this.arguments,
        argumentTypes,
        argsContainCast,
        this)) {
      this.bits |= ASTNode.Unchecked;
    }
    if (this.typeArguments != null
        && this.binding.original().typeVariables == Binding.NO_TYPE_VARIABLES) {
      scope
          .problemReporter()
          .unnecessaryTypeArgumentsForMethodInvocation(
              this.binding, this.genericTypeArguments, this.typeArguments);
    }
    if (!isDiamond && this.resolvedType.isParameterizedTypeWithActualArguments()) {
      checkTypeArgumentRedundancy(
          (ParameterizedTypeBinding) this.resolvedType, null, argumentTypes, scope);
    }
    final CompilerOptions compilerOptions = scope.compilerOptions();
    if (compilerOptions.isAnnotationBasedNullAnalysisEnabled
        && (this.binding.tagBits & TagBits.IsNullnessKnown) == 0) {
      new ImplicitNullAnnotationVerifier(
              scope.environment(), compilerOptions.inheritNullAnnotations)
          .checkImplicitNullAnnotations(this.binding, null /*srcMethod*/, false, scope);
    }
    return allocationType;
  }
Example #12
0
  public TypeBinding resolveTypeExpecting(BlockScope scope, TypeBinding expectedType) {
    // Array initializers can only occur on the right hand side of an assignment
    // expression, therefore the expected type contains the valid information
    // concerning the type that must be enforced by the elements of the array initializer.

    // this method is recursive... (the test on isArrayType is the stop case)

    this.constant = Constant.NotAConstant;

    if (expectedType instanceof ArrayBinding) {
      // allow new List<?>[5]
      if ((this.bits & IsAnnotationDefaultValue)
          == 0) { // annotation default value need only to be commensurate JLS9.7
        // allow new List<?>[5] - only check for generic array when no initializer, since also
        // checked inside initializer resolution
        TypeBinding leafComponentType = expectedType.leafComponentType();
        if (!leafComponentType.isReifiable()) {
          scope.problemReporter().illegalGenericArray(leafComponentType, this);
        }
      }
      this.resolvedType = this.binding = (ArrayBinding) expectedType;
      if (this.expressions == null) return this.binding;
      TypeBinding elementType = this.binding.elementsType();
      for (int i = 0, length = this.expressions.length; i < length; i++) {
        Expression expression = this.expressions[i];
        expression.setExpectedType(elementType);
        TypeBinding expressionType =
            expression instanceof ArrayInitializer
                ? expression.resolveTypeExpecting(scope, elementType)
                : expression.resolveType(scope);
        if (expressionType == null) continue;

        // Compile-time conversion required?
        if (elementType
            != expressionType) // must call before computeConversion() and typeMismatchError()
        scope.compilationUnitScope().recordTypeConversion(elementType, expressionType);

        if (expression.isConstantValueOfTypeAssignableToType(expressionType, elementType)
            || expressionType.isCompatibleWith(elementType)) {
          expression.computeConversion(scope, elementType, expressionType);
        } else if (scope.isBoxingCompatibleWith(expressionType, elementType)
            || (expressionType.isBaseType() // narrowing then boxing ?
                && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing
                && !elementType.isBaseType()
                && expression.isConstantValueOfTypeAssignableToType(
                    expressionType, scope.environment().computeBoxingType(elementType)))) {
          expression.computeConversion(scope, elementType, expressionType);
        } else {
          scope.problemReporter().typeMismatchError(expressionType, elementType, expression, null);
        }
      }
      return this.binding;
    }

    // infer initializer type for error reporting based on first element
    TypeBinding leafElementType = null;
    int dim = 1;
    if (this.expressions == null) {
      leafElementType = scope.getJavaLangObject();
    } else {
      Expression expression = this.expressions[0];
      while (expression != null && expression instanceof ArrayInitializer) {
        dim++;
        Expression[] subExprs = ((ArrayInitializer) expression).expressions;
        if (subExprs == null) {
          leafElementType = scope.getJavaLangObject();
          expression = null;
          break;
        }
        expression = ((ArrayInitializer) expression).expressions[0];
      }
      if (expression != null) {
        leafElementType = expression.resolveType(scope);
      }
      // fault-tolerance - resolve other expressions as well
      for (int i = 1, length = this.expressions.length; i < length; i++) {
        expression = this.expressions[i];
        if (expression != null) {
          expression.resolveType(scope);
        }
      }
    }
    if (leafElementType != null) {
      this.resolvedType = scope.createArrayType(leafElementType, dim);
      if (expectedType != null)
        scope.problemReporter().typeMismatchError(this.resolvedType, expectedType, this, null);
    }
    return null;
  }
  public TypeBinding resolveType(BlockScope scope) {

    this.constant = Constant.NotAConstant;
    if ((this.targetType = this.type.resolveType(scope, true /* check bounds*/)) == null)
      return null;

    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=320463
      https://bugs.eclipse.org/bugs/show_bug.cgi?id=312076
      JLS3 15.8.2 forbids the type named in the class literal expression from being a parameterized type.
      And the grammar in 18.1 disallows (where X and Y are some concrete types) constructs of the form
      Outer<X>.class, Outer<X>.Inner.class, Outer.Inner<X>.class, Outer<X>.Inner<Y>.class etc.
      Corollary wise, we should resolve the type of the class literal expression to be a raw type as
      class literals exist only for the raw underlying type.
    */
    LookupEnvironment environment = scope.environment();
    this.targetType =
        environment.convertToRawType(
            this.targetType, true /* force conversion of enclosing types*/);

    if (this.targetType.isArrayType()) {
      ArrayBinding arrayBinding = (ArrayBinding) this.targetType;
      TypeBinding leafComponentType = arrayBinding.leafComponentType;
      if (leafComponentType == TypeBinding.VOID) {
        scope.problemReporter().cannotAllocateVoidArray(this);
        return null;
      } else if (leafComponentType.isTypeVariable()) {
        scope
            .problemReporter()
            .illegalClassLiteralForTypeVariable((TypeVariableBinding) leafComponentType, this);
      }
    } else if (this.targetType.isTypeVariable()) {
      scope
          .problemReporter()
          .illegalClassLiteralForTypeVariable((TypeVariableBinding) this.targetType, this);
    }
    // {ObjectTeams: do we need a RoleClassLiteralAccess?
    if (this.targetType instanceof ReferenceBinding) {
      ReferenceBinding targetRef = (ReferenceBinding) this.targetType;
      if (targetRef.isRole()) {
        if (this.verbatim) {
          this.targetType =
              RoleTypeCreator.maybeWrapUnqualifiedRoleType(scope, this.targetType, this);
        } else {
          SourceTypeBinding site = scope.enclosingSourceType();
          if (scope.methodScope().isStatic // role class literal needs team instance
              && !site.isRole() // static role method are OK.
              && !RoleTypeBinding.isRoleWithExplicitAnchor(this.targetType)) // t.R.class?
          {
            scope.problemReporter().roleClassLiteralLacksTeamInstance(this, targetRef);
            return null;
          }
          ReferenceBinding teamBinding;
          if (RoleTypeBinding.isRoleWithExplicitAnchor(targetRef))
            teamBinding = targetRef.enclosingType();
          else teamBinding = TeamModel.findEnclosingTeamContainingRole(site, targetRef);
          if (teamBinding == null)
            scope.problemReporter().externalizedRoleClassLiteral(this, targetRef);
          else {
            TypeBinding methodType =
                RoleClassLiteralAccess.ensureGetClassMethod(
                    teamBinding.getTeamModel(),
                    targetRef.roleModel); // not affected by visibility check (for resilience)
            this.roleClassLiteralAccess = new RoleClassLiteralAccess(this, methodType);
            this.resolvedType = this.roleClassLiteralAccess.resolveType(scope);
          }
          return this.resolvedType;
        }
      }
    }
    // SH}
    ReferenceBinding classType = scope.getJavaLangClass();
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=328689
    if (scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
      // Integer.class --> Class<Integer>, perform boxing of base types (int.class -->
      // Class<Integer>)
      TypeBinding boxedType = null;
      if (this.targetType.id == T_void) {
        boxedType = environment.getResolvedType(JAVA_LANG_VOID, scope);
      } else {
        boxedType = scope.boxing(this.targetType);
      }
      if (environment.usesNullTypeAnnotations())
        boxedType =
            environment.createAnnotatedType(
                boxedType, new AnnotationBinding[] {environment.getNonNullAnnotation()});
      this.resolvedType =
          environment.createParameterizedType(
              classType, new TypeBinding[] {boxedType}, null /*not a member*/);
    } else {
      this.resolvedType = classType;
    }
    return this.resolvedType;
  }