private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
private void handleSimpleName(SimpleName node) { ASTNode firstExpression = node.getParent(); if (firstExpression instanceof FieldAccess) { while (firstExpression instanceof FieldAccess) { firstExpression = ((FieldAccess) firstExpression).getExpression(); } if (!(firstExpression instanceof SimpleName)) return; node = (SimpleName) firstExpression; } else if (firstExpression instanceof SuperFieldAccess) return; StructuralPropertyDescriptor parentDescription = node.getLocationInParent(); if (parentDescription == VariableDeclarationFragment.NAME_PROPERTY || parentDescription == SwitchCase.EXPRESSION_PROPERTY) return; IBinding binding = node.resolveBinding(); if (!(binding instanceof IVariableBinding)) return; handleVariable(node, (IVariableBinding) binding); }
/** * Method that check statement type. * @author Mariana Azevedo * @since 13/07/2014 * @param itStatement */ private void getStatementType(Object itStatement) { if (itStatement instanceof CatchClause){ this.visitor.visit((CatchClause)itStatement); }else if (itStatement instanceof ForStatement){ this.visitor.visit((ForStatement)itStatement); }else if (itStatement instanceof IfStatement){ this.visitor.visit((IfStatement)itStatement); }else if (itStatement instanceof WhileStatement){ this.visitor.visit((WhileStatement)itStatement); }else if (itStatement instanceof TryStatement){ this.visitor.visit((TryStatement)itStatement); }else if (itStatement instanceof ConditionalExpression){ this.visitor.visit((ConditionalExpression)itStatement); }else if (itStatement instanceof SwitchCase){ this.visitor.visit((SwitchCase)itStatement); }else if (itStatement instanceof DoStatement){ this.visitor.visit((DoStatement)itStatement); }else if (itStatement instanceof ExpressionStatement){ this.visitor.visit((ExpressionStatement)itStatement); } }
@Override public boolean visit(SwitchCase node) { // switch on enum allows to use enum constants without qualification if (hasFlag(VARIABLES, fFlags) && !node.isDefault() && isInside(node.getExpression())) { SwitchStatement switchStatement = (SwitchStatement) node.getParent(); ITypeBinding binding = switchStatement.getExpression().resolveTypeBinding(); if (binding != null && binding.isEnum()) { IVariableBinding[] declaredFields = binding.getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { IVariableBinding curr = declaredFields[i]; if (curr.isEnumConstant()) { fBreak = fRequestor.acceptBinding(curr); if (fBreak) return false; } } } } return false; }
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation // ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
private static boolean canReplace(IASTFragment fragment) { ASTNode node = fragment.getAssociatedNode(); ASTNode parent = node.getParent(); if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent; if (node.equals(vdf.getName())) return false; } if (isMethodParameter(node)) return false; if (isThrowableInCatchBlock(node)) return false; if (parent instanceof ExpressionStatement) return false; if (isLeftValue(node)) return false; if (isReferringToLocalVariableFromFor((Expression) node)) return false; if (isUsedInForInitializerOrUpdater((Expression) node)) return false; if (parent instanceof SwitchCase) return false; return true; }
private void checkExpression(RefactoringStatus status) { ASTNode[] nodes = getSelectedNodes(); if (nodes != null && nodes.length == 1) { ASTNode node = nodes[0]; if (node instanceof Type) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node)); } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node)); } else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node)); } } }
private static boolean canReplace(IASTFragment fragment) { ASTNode node = fragment.getAssociatedNode(); ASTNode parent = node.getParent(); if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent; if (node.equals(vdf.getName())) return false; } if (parent instanceof ExpressionStatement) return false; if (parent instanceof SwitchCase) { if (node instanceof Name) { Name name = (Name) node; ITypeBinding typeBinding = name.resolveTypeBinding(); if (typeBinding != null) { return !typeBinding.isEnum(); } } } return true; }
private static boolean canReplace(IASTFragment fragment) { ASTNode node= fragment.getAssociatedNode(); ASTNode parent= node.getParent(); if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent; if (node.equals(vdf.getName())) return false; } if (isMethodParameter(node)) return false; if (isThrowableInCatchBlock(node)) return false; if (parent instanceof ExpressionStatement) return false; if (isLeftValue(node)) return false; if (isReferringToLocalVariableFromFor((Expression) node)) return false; if (isUsedInForInitializerOrUpdater((Expression) node)) return false; if (parent instanceof SwitchCase) return false; return true; }
private static boolean canReplace(IASTFragment fragment) { ASTNode node= fragment.getAssociatedNode(); ASTNode parent= node.getParent(); if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent; if (node.equals(vdf.getName())) return false; } if (parent instanceof ExpressionStatement) return false; if (parent instanceof SwitchCase) { if (node instanceof Name) { Name name= (Name) node; ITypeBinding typeBinding= name.resolveTypeBinding(); if (typeBinding != null) { return !typeBinding.isEnum(); } } } return true; }
@Override public boolean visit(SwitchCase node) { // switch on enum allows to use enum constants without qualification if (hasFlag(VARIABLES, fFlags) && !node.isDefault() && isInside(node.getExpression())) { SwitchStatement switchStatement= (SwitchStatement) node.getParent(); ITypeBinding binding= switchStatement.getExpression().resolveTypeBinding(); if (binding != null && binding.isEnum()) { IVariableBinding[] declaredFields= binding.getDeclaredFields(); for (int i= 0; i < declaredFields.length; i++) { IVariableBinding curr= declaredFields[i]; if (curr.isEnumConstant()) { fBreak= fRequestor.acceptBinding(curr); if (fBreak) return false; } } } } return false; }
private void handleSimpleName(SimpleName node) { ASTNode firstExpression= node.getParent(); if (firstExpression instanceof FieldAccess) { while (firstExpression instanceof FieldAccess) { firstExpression= ((FieldAccess)firstExpression).getExpression(); } if (!(firstExpression instanceof SimpleName)) return; node= (SimpleName)firstExpression; } else if (firstExpression instanceof SuperFieldAccess) return; StructuralPropertyDescriptor parentDescription= node.getLocationInParent(); if (parentDescription == VariableDeclarationFragment.NAME_PROPERTY || parentDescription == SwitchCase.EXPRESSION_PROPERTY) return; IBinding binding= node.resolveBinding(); if (!(binding instanceof IVariableBinding)) return; handleVariable(node, (IVariableBinding) binding); }
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { AST ast= selectedNode.getAST(); SwitchStatement parent= (SwitchStatement) selectedNode.getParent(); for (Statement statement : (List<Statement>) parent.statements()) { if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { // insert //$CASES-OMITTED$: ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ listRewrite.insertBefore(casesOmittedComment, statement, null); String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image); proposals.add(proposal); break; } } } }
public static boolean evaluateMissingSwitchCases(ITypeBinding enumBindings, List<Statement> switchStatements, ArrayList<String> enumConstNames) { IVariableBinding[] fields= enumBindings.getDeclaredFields(); for (int i= 0; i < fields.length; i++) { if (fields[i].isEnumConstant()) { enumConstNames.add(fields[i].getName()); } } boolean hasDefault=false; List<Statement> statements= switchStatements; for (int i= 0; i < statements.size(); i++) { Statement curr= statements.get(i); if (curr instanceof SwitchCase) { Expression expression= ((SwitchCase) curr).getExpression(); if (expression instanceof SimpleName) { enumConstNames.remove(((SimpleName) expression).getFullyQualifiedName()); } else if(expression== null){ hasDefault=true; } } } return hasDefault; }
private static boolean getMissingCaseStatementProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> proposals) { if (node instanceof SwitchCase) { node= node.getParent(); } if (!(node instanceof SwitchStatement)) return false; SwitchStatement switchStatement= (SwitchStatement)node; ITypeBinding expressionBinding= switchStatement.getExpression().resolveTypeBinding(); if (expressionBinding == null || !expressionBinding.isEnum()) return false; ArrayList<String> missingEnumCases= new ArrayList<String>(); boolean hasDefault= LocalCorrectionsSubProcessor.evaluateMissingSwitchCases(expressionBinding, switchStatement.statements(), missingEnumCases); if (missingEnumCases.size() == 0 && hasDefault) return false; if (proposals == null) return true; LocalCorrectionsSubProcessor.createMissingCaseProposals(context, switchStatement, missingEnumCases, proposals); return true; }
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { AST ast= selectedNode.getAST(); SwitchStatement parent= (SwitchStatement) selectedNode.getParent(); for (Statement statement : (List<Statement>) parent.statements()) { if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { // insert //$CASES-OMITTED$: ASTRewrite rewrite= ASTRewrite.create(ast); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ listRewrite.insertBefore(casesOmittedComment, statement, null); String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 4, image); proposals.add(proposal); break; } } } }
@Override protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException { ASTNode node = getASTNode(workingUnit, bug.getPrimarySourceLineAnnotation()); node = TraversalUtil.backtrackToBlock(node); DefaultCaseVisitor visitor = new DefaultCaseVisitor(); node.accept(visitor); if (visitor.badSwitchStatement != null) { ListRewrite statementsRewrite = rewrite.getListRewrite(visitor.badSwitchStatement, SwitchStatement.STATEMENTS_PROPERTY); SwitchCase defaultCase = rewrite.getAST().newSwitchCase(); defaultCase.setExpression(null); statementsRewrite.insertLast(defaultCase, null); statementsRewrite.insertLast(rewrite.getAST().newBreakStatement(), null); } }
@SuppressWarnings("unchecked") @Override public boolean visit(SwitchStatement node) { if (badSwitchStatement != null) { return false; } List<Statement> switchStatements = node.statements(); for (Statement statement : switchStatements) { if (statement instanceof SwitchCase) { if (((SwitchCase) statement).getExpression() == null) { return true; // this one has a default case...skip it } } } badSwitchStatement = node; return false; }
@Override public boolean visit(SwitchCase node) { //System.out.println("Found: " + node.getClass()); if (node.isDefault()) { println("default:"); } else { print("case "); node.getExpression().accept(this); println(":"); } // Case fallthrough SwitchStatement ss = (SwitchStatement)node.getParent(); List statements = ss.statements(); if (statements.indexOf(node) < statements.size() - 1) { Object nextSibling = statements.get(statements.indexOf(node) + 1); if (nextSibling instanceof SwitchCase) { //indent++; println("goto " + (((SwitchCase)nextSibling).isDefault() ? "default;" : "case;" )); //indent--; return false; } } // TODO Get indentation right //indent++; return false; }
/** * @see ASTVisitor#visit(SwitchCase) */ @Override public boolean visit(SwitchCase node) { if (!node.isDefault()){ cyclomaticComplexityIndex++; sumCyclomaticComplexity++; } return true; }
protected SwitchData createSwitchData(SwitchStatement node) { SwitchData result = new SwitchData(); List<Statement> statements = node.statements(); if (statements.isEmpty()) { return result; } int start = -1, end = -1; GenericSequentialFlowInfo info = null; for (Iterator<Statement> iter = statements.iterator(); iter.hasNext();) { Statement statement = iter.next(); if (statement instanceof SwitchCase) { SwitchCase switchCase = (SwitchCase) statement; if (switchCase.isDefault()) { result.setHasDefaultCase(); } if (info == null) { info = createSequential(); start = statement.getStartPosition(); } else { if (info.isReturn() || info.isPartialReturn() || info.branches()) { result.add(new Region(start, end - start + 1), info); info = createSequential(); start = statement.getStartPosition(); } } } else { info.merge(getFlowInfo(statement), fFlowContext); } end = statement.getStartPosition() + statement.getLength() - 1; } result.add(new Region(start, end - start + 1), info); return result; }
private void checkExpression(RefactoringStatus status) { ASTNode[] nodes = getSelectedNodes(); if (nodes != null && nodes.length == 1) { ASTNode node = nodes[0]; if (node instanceof Type) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node)); } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node)); } else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node)); } } }
@Override public void endVisit(SwitchStatement node) { ASTNode[] selectedNodes = getSelectedNodes(); if (doAfterValidation(node, selectedNodes)) { List<SwitchCase> cases = getSwitchCases(node); for (int i = 0; i < selectedNodes.length; i++) { ASTNode topNode = selectedNodes[i]; if (cases.contains(topNode)) { invalidSelection(RefactoringCoreMessages.StatementAnalyzer_switch_statement); break; } } } super.endVisit(node); }
private static List<SwitchCase> getSwitchCases(SwitchStatement node) { List<SwitchCase> result = new ArrayList<>(); for (Iterator<Statement> iter = node.statements().iterator(); iter.hasNext();) { Object element = iter.next(); if (element instanceof SwitchCase) { result.add((SwitchCase) element); } } return result; }
public static boolean isEnumCase(ASTNode node) { if (node instanceof SwitchCase) { final SwitchCase caze = (SwitchCase) node; final Expression expression = caze.getExpression(); if (expression instanceof Name) { final Name name = (Name) expression; final IBinding binding = name.resolveBinding(); if (binding instanceof IVariableBinding) { IVariableBinding variableBinding = (IVariableBinding) binding; return variableBinding.isEnumConstant(); } } } return false; }
private static List<SwitchCase> getSwitchCases(SwitchStatement node) { List<SwitchCase> result = new ArrayList<SwitchCase>(); for (Iterator<Statement> iter = node.statements().iterator(); iter.hasNext(); ) { Object element = iter.next(); if (element instanceof SwitchCase) result.add((SwitchCase) element); } return result; }
/** {@inheritDoc} */ @Override public void endVisit(SwitchCase node) { // TODO-JRO Implement method endVisit logger.warn("Method endVisit not implemented!"); super.endVisit(node); }
public static boolean isEnumCase(ASTNode node) { if (node instanceof SwitchCase) { final SwitchCase caze= (SwitchCase) node; final Expression expression= caze.getExpression(); if (expression instanceof Name) { final Name name= (Name) expression; final IBinding binding= name.resolveBinding(); if (binding instanceof IVariableBinding) { IVariableBinding variableBinding= (IVariableBinding) binding; return variableBinding.isEnumConstant(); } } } return false; }
protected SwitchData createSwitchData(SwitchStatement node) { SwitchData result= new SwitchData(); List<Statement> statements= node.statements(); if (statements.isEmpty()) return result; int start= -1, end= -1; GenericSequentialFlowInfo info= null; for (Iterator<Statement> iter= statements.iterator(); iter.hasNext(); ) { Statement statement= iter.next(); if (statement instanceof SwitchCase) { SwitchCase switchCase= (SwitchCase)statement; if (switchCase.isDefault()) { result.setHasDefaultCase(); } if (info == null) { info= createSequential(); start= statement.getStartPosition(); } else { if (info.isReturn() || info.isPartialReturn() || info.branches()) { result.add(new Region(start, end - start + 1), info); info= createSequential(); start= statement.getStartPosition(); } } } else { info.merge(getFlowInfo(statement), fFlowContext); } end= statement.getStartPosition() + statement.getLength() - 1; } result.add(new Region(start, end - start + 1), info); return result; }
private void checkExpression(RefactoringStatus status) { ASTNode[] nodes= getSelectedNodes(); if (nodes != null && nodes.length == 1) { ASTNode node= nodes[0]; if (node instanceof Type) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node)); } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node)); } else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node)); } } }
@Override public void endVisit(SwitchStatement node) { ASTNode[] selectedNodes= getSelectedNodes(); if (doAfterValidation(node, selectedNodes)) { List<SwitchCase> cases= getSwitchCases(node); for (int i= 0; i < selectedNodes.length; i++) { ASTNode topNode= selectedNodes[i]; if (cases.contains(topNode)) { invalidSelection(RefactoringCoreMessages.StatementAnalyzer_switch_statement); break; } } } super.endVisit(node); }