public LambdaMethodFilter(PsiLambdaExpression lambda, int expressionOrdinal, Range<Integer> callingExpressionLines) { myLambdaOrdinal = expressionOrdinal; myCallingExpressionLines = callingExpressionLines; SourcePosition firstStatementPosition = null; SourcePosition lastStatementPosition = null; final PsiElement body = lambda.getBody(); if (body instanceof PsiCodeBlock) { final PsiStatement[] statements = ((PsiCodeBlock)body).getStatements(); if (statements.length > 0) { firstStatementPosition = SourcePosition.createFromElement(statements[0]); if (firstStatementPosition != null) { final PsiStatement lastStatement = statements[statements.length - 1]; lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()); } } } else if (body != null) { firstStatementPosition = SourcePosition.createFromElement(body); } myFirstStatementPosition = firstStatementPosition; myLastStatementLine = lastStatementPosition != null ? lastStatementPosition.getLine() : -1; }
public AnonymousClassMethodFilter(PsiMethod psiMethod, Range<Integer> lines) { super(psiMethod, lines); SourcePosition firstStatementPosition = null; SourcePosition lastStatementPosition = null; final PsiCodeBlock body = psiMethod.getBody(); if (body != null) { final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { firstStatementPosition = SourcePosition.createFromElement(statements[0]); if (firstStatementPosition != null) { final PsiStatement lastStatement = statements[statements.length - 1]; lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()); } } } myBreakpointPosition = firstStatementPosition; myLastStatementLine = lastStatementPosition != null? lastStatementPosition.getLine() : -1; }
private static List<PsiStatement> getFinallyStatements(@Nullable SourcePosition position) { if (position == null) { return Collections.emptyList(); } List<PsiStatement> res = new ArrayList<PsiStatement>(); PsiElement element = position.getFile().findElementAt(position.getOffset()); PsiTryStatement tryStatement = PsiTreeUtil.getParentOfType(element, PsiTryStatement.class); while (tryStatement != null) { PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock(); if (finallyBlock != null) { ContainerUtil.addAll(res, finallyBlock.getStatements()); } tryStatement = PsiTreeUtil.getParentOfType(tryStatement, PsiTryStatement.class); } return res; }
@Override public void visitContinueStatement( @NotNull PsiContinueStatement statement) { super.visitContinueStatement(statement); if (!ControlFlowUtils.isInFinallyBlock(statement)) { return; } final PsiStatement continuedStatement = statement.findContinuedStatement(); if (continuedStatement == null) { return; } if (ControlFlowUtils.isInFinallyBlock(continuedStatement)) { return; } registerStatementError(statement); }
private int calculateReturnPointCount(PsiMethod method) { final ReturnPointCountVisitor visitor = new ReturnPointCountVisitor(ignoreGuardClauses); method.accept(visitor); final int count = visitor.getCount(); if (!mayFallThroughBottom(method)) { return count; } final PsiCodeBlock body = method.getBody(); if (body == null) { return count; } final PsiStatement[] statements = body.getStatements(); if (statements.length == 0) { return count + 1; } final PsiStatement lastStatement = statements[statements.length - 1]; if (ControlFlowUtils.statementMayCompleteNormally(lastStatement)) { return count + 1; } return count; }
@Override public void visitIfStatement(@NotNull PsiIfStatement statement) { super.visitIfStatement(statement); final PsiElement parent = statement.getParent(); if (parent instanceof PsiIfStatement) { final PsiIfStatement parentStatement = (PsiIfStatement)parent; final PsiStatement elseBranch = parentStatement.getElseBranch(); if (statement.equals(elseBranch)) { return; } } final int branchCount = calculateBranchCount(statement); if (branchCount <= m_limit) { return; } registerStatementError(statement, Integer.valueOf(branchCount)); }
@Override public void visitSynchronizedStatement( @NotNull PsiSynchronizedStatement statement) { super.visitSynchronizedStatement(statement); if (FileTypeUtils.isInJsp(statement.getContainingFile())) { return; } final PsiCodeBlock body = statement.getBody(); if (body == null) { return; } final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { return; } registerStatementError(statement); }
private boolean isChainingConstructor(PsiMethod constructor) { PsiCodeBlock body = constructor.getBody(); if (body != null) { PsiStatement[] statements = body.getStatements(); if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) { PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression(); if (expression instanceof PsiMethodCallExpression) { PsiReferenceExpression methodExpr = ((PsiMethodCallExpression) expression).getMethodExpression(); if ("this".equals(methodExpr.getReferenceName())) { PsiElement resolved = methodExpr.resolve(); return resolved instanceof PsiMethod && ((PsiMethod) resolved).isConstructor(); //delegated via "this" call } } } } return false; }
/** * Add new statement after given anchor statement creating code block, if necessary * * @param anchor existing statement * @param newStatement a new statement which should be added after an existing one * @return added physical statement */ public static PsiStatement addAfter(PsiStatement anchor, PsiStatement newStatement) { PsiElement oldStatement = anchor; PsiElement parent = oldStatement.getParent(); while(parent instanceof PsiLabeledStatement) { oldStatement = parent; parent = oldStatement.getParent(); } final PsiElement result; if(parent instanceof PsiCodeBlock) { result = parent.addAfter(newStatement, oldStatement); } else { PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject()); final PsiBlockStatement newBlockStatement = (PsiBlockStatement) factory.createStatementFromText("{}", oldStatement); final PsiElement codeBlock = newBlockStatement.getCodeBlock(); codeBlock.add(oldStatement); codeBlock.add(newStatement); result = ((PsiBlockStatement) oldStatement.replace(newBlockStatement)).getCodeBlock().getStatements()[1]; } return (PsiStatement) result; }
@RequiredReadAction @Override public void collectSlowLineMarkers(@NotNull List<PsiElement> elements, @NotNull Collection<LineMarkerInfo> result) { final Set<PsiStatement> statements = new HashSet<>(); for(PsiElement element : elements) { ProgressManager.checkCanceled(); if(element instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) element; final PsiStatement statement = PsiTreeUtil.getParentOfType(methodCall, PsiStatement.class, true, PsiMethod.class); if(!statements.contains(statement) && isRecursiveMethodCall(methodCall)) { statements.add(statement); result.add(new RecursiveMethodCallMarkerInfo(methodCall)); } } } }
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PsiExpressionStatement statement = myPointer.getElement(); if(statement == null) { return; } PsiExpression expression = statement.getExpression(); List<PsiExpression> sideEffects = SideEffectChecker.extractSideEffectExpressions(expression); PsiStatement[] statements = StatementExtractor.generateStatements(sideEffects, expression); if(statements.length > 0) { BlockUtils.addBefore(statement, statements); } statement.delete(); }
private static void replaceSimplifiableAssignment( PsiIfStatement statement) throws IncorrectOperationException { final PsiExpression condition = statement.getCondition(); if (condition == null) { return; } final String conditionText = condition.getText(); final PsiStatement thenBranch = statement.getThenBranch(); final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement) ControlFlowUtils.stripBraces(thenBranch); final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression(); final PsiJavaToken operator = assignmentExpression.getOperationSign(); final String operand = operator.getText(); final PsiExpression lhs = assignmentExpression.getLExpression(); final String lhsText = lhs.getText(); replaceStatement(statement, lhsText + operand + conditionText + ';'); }
private static void replaceSimplifiableAssignmentNegated( PsiIfStatement statement) throws IncorrectOperationException { final PsiExpression condition = statement.getCondition(); if (condition == null) { return; } final String conditionText = BoolUtils.getNegatedExpressionText(condition); final PsiStatement thenBranch = statement.getThenBranch(); final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement) ControlFlowUtils.stripBraces(thenBranch); final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) assignmentStatement.getExpression(); final PsiJavaToken operator = assignmentExpression.getOperationSign(); final String operand = operator.getText(); final PsiExpression lhs = assignmentExpression.getLExpression(); final String lhsText = lhs.getText(); replaceStatement(statement, lhsText + operand + conditionText + ';'); }
public static boolean isSimplifiableImplicitReturn( PsiIfStatement ifStatement) { if (ifStatement.getElseBranch() != null) { return false; } PsiStatement thenBranch = ifStatement.getThenBranch(); thenBranch = ControlFlowUtils.stripBraces(thenBranch); final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); if (!(nextStatement instanceof PsiStatement)) { return false; } final PsiStatement elseBranch = (PsiStatement)nextStatement; return ConditionalUtils.isReturn(thenBranch, PsiKeyword.TRUE) && ConditionalUtils.isReturn(elseBranch, PsiKeyword.FALSE); }
public static boolean isSimplifiableImplicitReturnNegated( PsiIfStatement ifStatement) { if (ifStatement.getElseBranch() != null) { return false; } PsiStatement thenBranch = ifStatement.getThenBranch(); thenBranch = ControlFlowUtils.stripBraces(thenBranch); final PsiElement nextStatement = PsiTreeUtil.skipSiblingsForward(ifStatement, PsiWhiteSpace.class); if (!(nextStatement instanceof PsiStatement)) { return false; } final PsiStatement elseBranch = (PsiStatement)nextStatement; return ConditionalUtils.isReturn(thenBranch, PsiKeyword.FALSE) && ConditionalUtils.isReturn(elseBranch, PsiKeyword.TRUE); }
private void checkStatement(PsiStatement statement) { if(ControlFlowUtils.statementMayCompleteNormally(statement)) { return; } if(ControlFlowUtils.containsReturn(statement)) { return; } if(ControlFlowUtils.containsSystemExit(statement)) { return; } registerStatementError(statement); }
@Override public void visitSynchronizedStatement( @NotNull PsiSynchronizedStatement statement) { super.visitSynchronizedStatement(statement); /* if (JspPsiUtil.isInJspFile(statement.getContainingFile())) { return; }*/ final PsiCodeBlock body = statement.getBody(); if (body == null) { return; } final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { return; } registerStatementError(statement); }
public AnonymousClassMethodFilter(PsiMethod psiMethod, Range<Integer> lines) { super(psiMethod, lines); SourcePosition firstStatementPosition = null; SourcePosition lastStatementPosition = null; final PsiCodeBlock body = psiMethod.getBody(); if(body != null) { final PsiStatement[] statements = body.getStatements(); if(statements.length > 0) { firstStatementPosition = SourcePosition.createFromElement(statements[0]); if(firstStatementPosition != null) { final PsiStatement lastStatement = statements[statements.length - 1]; lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()); } } } myBreakpointPosition = firstStatementPosition; myLastStatementLine = lastStatementPosition != null ? lastStatementPosition.getLine() : -1; }
private static void extractStatements(@NonNull PsiElement element, List<PsiStatement> statements) { for (PsiElement child : element.getChildren()) { if (child instanceof PsiStatement) { statements.add((PsiStatement) child); continue; } extractStatements(child, statements); } }
public void startElement(PsiElement element) { myElementStack.push(element); myElementToStartOffsetMap.put(element, myInstructions.size()); if (LOG.isDebugEnabled()){ if (element instanceof PsiStatement){ String text = element.getText(); int index = Math.min(text.indexOf('\n'), text.indexOf('\r')); if (index >= 0){ text = text.substring(0, index); } addInstruction(new CommentInstruction(text)); } } }
@Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { PsiStatement then = ((PsiIfStatement)element).getThenBranch(); context.extractFromBlockOrSingleStatement(then, element); context.delete(element); }
@Override protected void unwrapElseBranch(PsiStatement branch, PsiElement parent, Context context) throws IncorrectOperationException { // if we have 'else if' then we have to extract statements from the 'if' branch if (branch instanceof PsiIfStatement) { branch = ((PsiIfStatement)branch).getThenBranch(); } parent = findTopmostIfStatement(parent); context.extractFromBlockOrSingleStatement(branch, parent); context.delete(parent); }
@Override public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException { if (psiElement instanceof PsiCodeBlock && afterUnmatchedBrace(editor,psiElement.getContainingFile().getFileType())) { PsiCodeBlock block = (PsiCodeBlock) psiElement; int stopOffset = block.getTextRange().getEndOffset(); final PsiStatement[] statements = block.getStatements(); if (statements.length > 0) { stopOffset = statements[0].getTextRange().getEndOffset(); } editor.getDocument().insertString(stopOffset, "}"); } }
@Override public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { List<TextRange> result = new ArrayList<TextRange>(); result.addAll(expandToWholeLine(editorText, e.getTextRange(), false)); PsiIfStatement statement = (PsiIfStatement)e; final PsiKeyword elseKeyword = statement.getElseElement(); if (elseKeyword != null) { final PsiStatement then = statement.getThenBranch(); if (then != null) { final TextRange thenRange = new TextRange(statement.getTextRange().getStartOffset(), then.getTextRange().getEndOffset()); if (thenRange.contains(cursorOffset)) { result.addAll(expandToWholeLine(editorText, thenRange, false)); } } result.addAll(expandToWholeLine(editorText, new TextRange(elseKeyword.getTextRange().getStartOffset(), statement.getTextRange().getEndOffset()), false)); final PsiStatement branch = statement.getElseBranch(); if (branch instanceof PsiIfStatement) { PsiIfStatement elseIf = (PsiIfStatement)branch; final PsiKeyword element = elseIf.getElseElement(); if (element != null) { final PsiStatement elseThen = elseIf.getThenBranch(); if (elseThen != null) { result.addAll(expandToWholeLine(editorText, new TextRange(elseKeyword.getTextRange().getStartOffset(), elseThen.getTextRange().getEndOffset()), false)); } } } } return result; }
@Override public void visitSwitchStatement( @NotNull PsiSwitchStatement statement) { super.visitSwitchStatement(statement); final PsiCodeBlock body = statement.getBody(); if (body == null) { return; } final PsiStatement[] statements = body.getStatements(); boolean labelSeen = false; for (int i = statements.length - 1; i >= 0; i--) { final PsiStatement child = statements[i]; if (child instanceof PsiSwitchLabelStatement) { final PsiSwitchLabelStatement label = (PsiSwitchLabelStatement)child; if (label.isDefaultCase()) { if (labelSeen) { registerStatementError(label); } return; } else { labelSeen = true; } } } }
private int calculateBranchCount(PsiIfStatement statement) { final PsiStatement branch = statement.getElseBranch(); if (branch == null) { return 1; } if (!(branch instanceof PsiIfStatement)) { return 2; } return 1 + calculateBranchCount((PsiIfStatement)branch); }
private void checkStatement(PsiStatement statement) { if (ControlFlowUtils.statementMayCompleteNormally(statement)) { return; } if (ControlFlowUtils.statementContainsReturn(statement)) { return; } if (ControlFlowUtils.statementContainsSystemExit(statement)) { return; } registerStatementError(statement); }
@Override public void visitSynchronizedStatement(@NotNull PsiSynchronizedStatement statement) { super.visitSynchronizedStatement(statement); final PsiCodeBlock body = statement.getBody(); if (body == null) { return; } final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { return; } registerStatementError(statement); }
@Override public void visitBreakStatement(@NotNull PsiBreakStatement statement) { super.visitBreakStatement(statement); if (!ControlFlowUtils.isInFinallyBlock(statement)) { return; } final PsiStatement exitedStatement = statement.findExitedStatement(); if (exitedStatement == null) { return; } if (ControlFlowUtils.isInFinallyBlock(exitedStatement)) { return; } registerStatementError(statement); }
public void processIntention(PsiElement element) throws IncorrectOperationException { final PsiJavaToken token = (PsiJavaToken)element; final PsiIfStatement parentStatement = (PsiIfStatement)token.getParent(); if (parentStatement == null) { return; } final PsiStatement elseBranch = parentStatement.getElseBranch(); if (elseBranch == null) { return; } final String newStatement = '{' + elseBranch.getText() + '}'; PsiReplacementUtil.replaceStatement(elseBranch, newStatement); }
public boolean satisfiedBy(PsiElement element) { if (!(element instanceof PsiJavaToken)) { return false; } final PsiJavaToken token = (PsiJavaToken)element; final PsiElement parent = token.getParent(); if (!(parent instanceof PsiIfStatement)) { return false; } final PsiIfStatement ifStatement = (PsiIfStatement)parent; if (ErrorUtil.containsError(ifStatement)) { return false; } PsiStatement thenBranch = ifStatement.getThenBranch(); thenBranch = ControlFlowUtils.stripBraces(thenBranch); PsiStatement elseBranch = ifStatement.getElseBranch(); elseBranch = ControlFlowUtils.stripBraces(elseBranch); if (thenBranch == null) { return false; } if (elseBranch != null) { return false; } if (!(thenBranch instanceof PsiIfStatement)) { return false; } final PsiIfStatement childIfStatement = (PsiIfStatement)thenBranch; return childIfStatement.getElseBranch() == null; }
private void visitMethodDefinition(JavaContext context, PsiMethod method) { if (method == null) { return; } //make sure we are not looking in the onCreate() method of a subclass of android.app.Application, // and not the actual android.app.Application class ..sometimes the search will take you into // the sdk's Application class, particularly in testing if (TARGET_ORIGINATION_METHOD_NAME.equals(method.getName()) && isApplicationClassCall(context, method) && !method.getContainingClass().getQualifiedName().contains("android.app.Application")) { hasApplicationOnCreateMethod = true; properMethodCalls = findMethodCalledFrom(TARGET_METHOD_QUALIFIED_NAME, method, MAX_AST_DEPTH); if (properMethodCalls.size() >= 1) { if (properMethodCall == null) { properMethodCall = properMethodCalls.get(0); } for (int i = 1; i < properMethodCalls.size(); i++) { PsiMethodCallExpression call = properMethodCalls.get(i); if (!reportedDuplicateMethodCalls.contains(call)) { context.report(ISSUE, context.getLocation(call), MESSAGE_MULTIPLE_START_CALLS); reportedDuplicateMethodCalls.add(call); } } } else { context.report(ISSUE, context.getNameLocation(method), MESSAGE_NO_START_CALL_IN_ON_CREATE); } } if (method.getBody() != null) { for (PsiStatement statement : method.getBody().getStatements()) { PsiMethodCallExpression methodCall = findMethodCall(statement); if (methodCall != null && !properMethodCalls.contains(methodCall)) { visitMethodCall(context, methodCall, method); } } } }