@Nullable
  private static Map<PsiExpression, PsiType> buildDataflowTypeMap(PsiExpression forPlace) {
    PsiElement scope = DfaPsiUtil.getTopmostBlockInSameClass(forPlace);
    if (scope == null) {
      PsiFile file = forPlace.getContainingFile();
      if (!(file instanceof PsiCodeFragment)) {
        return Collections.emptyMap();
      }

      scope = file;
    }

    DataFlowRunner runner =
        new DataFlowRunner() {
          @NotNull
          @Override
          protected DfaMemoryState createMemoryState() {
            return new ExpressionTypeMemoryState(getFactory());
          }
        };

    final ExpressionTypeInstructionVisitor visitor = new ExpressionTypeInstructionVisitor(forPlace);
    if (runner.analyzeMethod(scope, visitor) == RunnerResult.OK) {
      return visitor.getResult();
    }
    return null;
  }
 @Override
 public DfaInstructionState[] visitInstanceof(
     InstanceofInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
   memState.pop();
   memState.pop();
   memState.push(
       new DfaInstanceofValue(
           runner.getFactory(), instruction.getLeft(), instruction.getCastType()));
   return new DfaInstructionState[] {
     new DfaInstructionState(runner.getInstruction(instruction.getIndex() + 1), memState)
   };
 }
  @Nullable
  private static DfaInstructionState[] handleConstantComparison(
      BinopInstruction instruction,
      DataFlowRunner runner,
      DfaMemoryState memState,
      DfaValue dfaRight,
      DfaValue dfaLeft,
      IElementType opSign) {
    if (dfaRight instanceof DfaConstValue && dfaLeft instanceof DfaVariableValue) {
      Object value = ((DfaConstValue) dfaRight).getValue();
      if (value instanceof Number) {
        DfaInstructionState[] result =
            checkComparingWithConstant(
                instruction,
                runner,
                memState,
                (DfaVariableValue) dfaLeft,
                opSign,
                ((Number) value).doubleValue());
        if (result != null) {
          return result;
        }
      }
    }
    if (dfaRight instanceof DfaVariableValue && dfaLeft instanceof DfaConstValue) {
      return handleConstantComparison(
          instruction,
          runner,
          memState,
          dfaLeft,
          dfaRight,
          DfaRelationValue.getSymmetricOperation(opSign));
    }

    if (EQEQ != opSign && NE != opSign) {
      return null;
    }

    if (dfaLeft instanceof DfaConstValue && dfaRight instanceof DfaConstValue
        || dfaLeft == runner.getFactory().getConstFactory().getContractFail()
        || dfaRight == runner.getFactory().getConstFactory().getContractFail()) {
      boolean negated =
          (NE == opSign)
              ^ (DfaMemoryStateImpl.isNaN(dfaLeft) || DfaMemoryStateImpl.isNaN(dfaRight));
      if (dfaLeft == dfaRight ^ negated) {
        return alwaysTrue(instruction, runner, memState);
      }
      return alwaysFalse(instruction, runner, memState);
    }

    return null;
  }
 private static void forceNotNull(DataFlowRunner runner, DfaMemoryState memState, DfaValue arg) {
   if (arg instanceof DfaVariableValue) {
     DfaVariableValue var = (DfaVariableValue) arg;
     memState.setVarValue(
         var, runner.getFactory().createTypeValue(var.getVariableType(), Nullness.NOT_NULL));
   }
 }
  @Nullable
  private DfaInstructionState[] handleRelationBinop(
      BinopInstruction instruction,
      DataFlowRunner runner,
      DfaMemoryState memState,
      DfaValue dfaRight,
      DfaValue dfaLeft) {
    DfaValueFactory factory = runner.getFactory();
    final Instruction next = runner.getInstruction(instruction.getIndex() + 1);
    DfaRelationValue dfaRelation =
        factory
            .getRelationFactory()
            .createRelation(dfaLeft, dfaRight, instruction.getOperationSign(), false);
    if (dfaRelation == null) {
      return null;
    }

    myCanBeNullInInstanceof.add(instruction);

    ArrayList<DfaInstructionState> states = new ArrayList<DfaInstructionState>();

    final DfaMemoryState trueCopy = memState.createCopy();
    if (trueCopy.applyCondition(dfaRelation)) {
      trueCopy.push(factory.getConstFactory().getTrue());
      instruction.setTrueReachable();
      states.add(new DfaInstructionState(next, trueCopy));
    }

    //noinspection UnnecessaryLocalVariable
    DfaMemoryState falseCopy = memState;
    if (falseCopy.applyCondition(dfaRelation.createNegated())) {
      falseCopy.push(factory.getConstFactory().getFalse());
      instruction.setFalseReachable();
      states.add(new DfaInstructionState(next, falseCopy));
      if (instruction instanceof InstanceofInstruction && !falseCopy.isNull(dfaLeft)) {
        myUsefulInstanceofs.add((InstanceofInstruction) instruction);
      }
    }

    return states.toArray(new DfaInstructionState[states.size()]);
  }
  @Override
  public DfaInstructionState[] visitTypeCast(
      TypeCastInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
    final DfaValueFactory factory = runner.getFactory();
    DfaValue dfaExpr = factory.createValue(instruction.getCasted());
    if (dfaExpr != null) {
      DfaTypeValue dfaType =
          (DfaTypeValue) factory.createTypeValue(instruction.getCastTo(), Nullness.UNKNOWN);
      DfaRelationValue dfaInstanceof =
          factory.getRelationFactory().createRelation(dfaExpr, dfaType, INSTANCEOF_KEYWORD, false);
      if (dfaInstanceof != null && !memState.applyInstanceofOrNull(dfaInstanceof)) {
        onInstructionProducesCCE(instruction);
      }
    }

    if (instruction.getCastTo() instanceof PsiPrimitiveType) {
      memState.push(runner.getFactory().getBoxedFactory().createUnboxed(memState.pop()));
    }

    return nextInstruction(instruction, runner, memState);
  }
  @Override
  public DfaInstructionState[] visitMethodCall(
      final MethodCallInstruction instruction,
      final DataFlowRunner runner,
      final DfaMemoryState memState) {
    DfaValue[] argValues = popCallArguments(instruction, runner, memState);
    final DfaValue qualifier = popQualifier(instruction, runner, memState);

    List<DfaMemoryState> currentStates = ContainerUtil.newArrayList(memState);
    Set<DfaMemoryState> finalStates = ContainerUtil.newLinkedHashSet();
    if (argValues != null) {
      for (MethodContract contract : instruction.getContracts()) {
        currentStates =
            addContractResults(
                argValues, contract, currentStates, instruction, runner.getFactory(), finalStates);
      }
    }
    for (DfaMemoryState state : currentStates) {
      state.push(getMethodResultValue(instruction, qualifier, runner.getFactory()));
      finalStates.add(state);
    }

    return ContainerUtil.map2Array(
        finalStates,
        DfaInstructionState.class,
        new Function<DfaMemoryState, DfaInstructionState>() {
          @Override
          public DfaInstructionState fun(DfaMemoryState state) {
            if (instruction.shouldFlushFields()) {
              state.flushFields();
            }
            return new DfaInstructionState(
                runner.getInstruction(instruction.getIndex() + 1), state);
          }
        });
  }
Esempio n. 8
0
    @Override
    public DfaInstructionState[] visitAssign(
        AssignInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
      final Instruction nextInstruction = runner.getInstruction(instruction.getIndex() + 1);

      final DfaValue dfaSource = memState.pop();
      final DfaValue dfaDest = memState.pop();

      if (dfaDest instanceof DfaVariableValue) {
        DfaVariableValue var = (DfaVariableValue) dfaDest;
        final PsiExpression rightValue = instruction.getRExpression();
        final PsiElement parent = rightValue == null ? null : rightValue.getParent();
        final IElementType type =
            parent instanceof PsiAssignmentExpression
                ? ((PsiAssignmentExpression) parent).getOperationTokenType()
                : JavaTokenType.EQ;
        // store current value - to use in case of '+='
        final PsiExpression prevValue =
            ((ValuableDataFlowRunner.ValuableDfaVariableState)
                    ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableState(var))
                .myExpression;
        memState.setVarValue(var, dfaSource);
        // state may have been changed so re-retrieve it
        final ValuableDataFlowRunner.ValuableDfaVariableState curState =
            (ValuableDataFlowRunner.ValuableDfaVariableState)
                ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableState(var);
        final PsiExpression curValue = curState.myExpression;
        final PsiExpression nextValue;
        if (type == JavaTokenType.PLUSEQ && prevValue != null) {
          PsiExpression tmpExpression;
          try {
            tmpExpression =
                JavaPsiFacade.getElementFactory(myContext.getProject())
                    .createExpressionFromText(
                        prevValue.getText() + "+" + rightValue.getText(), rightValue);
          } catch (Exception e) {
            tmpExpression = curValue == null ? rightValue : curValue;
          }
          nextValue = tmpExpression;
        } else {
          nextValue = curValue == null ? rightValue : curValue;
        }
        curState.myExpression = nextValue;
      }
      memState.push(dfaDest);
      return new DfaInstructionState[] {new DfaInstructionState(nextInstruction, memState)};
    }
  @Override
  public DfaInstructionState[] visitAssign(
      AssignInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
    DfaValue dfaSource = memState.pop();
    DfaValue dfaDest = memState.pop();

    if (dfaDest instanceof DfaVariableValue) {
      DfaVariableValue var = (DfaVariableValue) dfaDest;

      DfaValueFactory factory = runner.getFactory();
      if (dfaSource instanceof DfaVariableValue
          && factory.getVarFactory().getAllQualifiedBy(var).contains(dfaSource)) {
        Nullness nullability =
            memState.isNotNull(dfaSource)
                ? Nullness.NOT_NULL
                : ((DfaVariableValue) dfaSource).getInherentNullability();
        dfaSource =
            factory.createTypeValue(((DfaVariableValue) dfaSource).getVariableType(), nullability);
      }

      if (var.getInherentNullability() == Nullness.NOT_NULL) {
        checkNotNullable(
            memState,
            dfaSource,
            NullabilityProblem.assigningToNotNull,
            instruction.getRExpression());
      }
      final PsiModifierListOwner psi = var.getPsiVariable();
      if (!(psi instanceof PsiField) || !psi.hasModifierProperty(PsiModifier.VOLATILE)) {
        memState.setVarValue(var, dfaSource);
      }
    } else if (dfaDest instanceof DfaTypeValue && ((DfaTypeValue) dfaDest).isNotNull()) {
      checkNotNullable(
          memState, dfaSource, NullabilityProblem.assigningToNotNull, instruction.getRExpression());
    }

    memState.push(dfaDest);

    return nextInstruction(instruction, runner, memState);
  }
  @Override
  public DfaInstructionState[] visitBinop(
      BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
    myReachable.add(instruction);

    DfaValue dfaRight = memState.pop();
    DfaValue dfaLeft = memState.pop();

    final IElementType opSign = instruction.getOperationSign();
    if (opSign != null) {
      DfaInstructionState[] states =
          handleConstantComparison(instruction, runner, memState, dfaRight, dfaLeft, opSign);
      if (states == null) {
        states = handleRelationBinop(instruction, runner, memState, dfaRight, dfaLeft);
      }
      if (states != null) {
        return states;
      }

      if (PLUS == opSign) {
        memState.push(instruction.getNonNullStringValue(runner.getFactory()));
      } else {
        if (instruction instanceof InstanceofInstruction) {
          handleInstanceof((InstanceofInstruction) instruction, dfaRight, dfaLeft);
        }
        memState.push(DfaUnknownValue.getInstance());
      }
    } else {
      memState.push(DfaUnknownValue.getInstance());
    }

    instruction.setTrueReachable(); // Not a branching instruction actually.
    instruction.setFalseReachable();

    return nextInstruction(instruction, runner, memState);
  }
 private static DfaInstructionState[] alwaysTrue(
     BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
   memState.push(runner.getFactory().getConstFactory().getTrue());
   instruction.setTrueReachable();
   return nextInstruction(instruction, runner, memState);
 }