org.eclipse.jdt.core.dom.SwitchStatement Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.SwitchStatement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SwitchControlStructure.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<AbstractControlCase> createSwitchCases(SwitchStatement switchStatement)
{
	List<AbstractControlCase> returnList  = new ArrayList<AbstractControlCase>();
	List<AbstractControlCase> tempList    = new ArrayList<AbstractControlCase>();
	List<Statement> switchGroupStatements = switchStatement.statements();
	for (Statement currentStatement : switchGroupStatements)
	{
		if (currentStatement instanceof SwitchCase)
		{
			Expression caseValue = ((SwitchCase)currentStatement).getExpression();
			SwitchControlCase newCase = new SwitchControlCase(this.variable, caseValue, new ArrayList<Statement>());
			tempList.add(newCase);
			addToAll((SwitchCase)currentStatement, tempList);
		}
		else if (currentStatement instanceof BreakStatement || currentStatement instanceof ReturnStatement || currentStatement instanceof ContinueStatement)
		{
			addToAll(currentStatement, tempList);
			returnList.addAll(tempList);
			tempList = new ArrayList<AbstractControlCase>();
		}
	}
	return returnList;
}
 
Example #2
Source File: InputFlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void endVisit(SwitchStatement node) {
	if (skipNode(node)) {
		return;
	}
	SwitchData data = createSwitchData(node);
	IRegion[] ranges = data.getRanges();
	for (int i = 0; i < ranges.length; i++) {
		IRegion range = ranges[i];
		if (fSelection.coveredBy(range)) {
			GenericSequentialFlowInfo info = createSequential();
			setFlowInfo(node, info);
			info.merge(getFlowInfo(node.getExpression()), fFlowContext);
			info.merge(data.getInfo(i), fFlowContext);
			info.removeLabel(null);
			return;
		}
	}
	super.endVisit(node, data);
}
 
Example #3
Source File: MissingSwitchDefaultQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {

  return new ASTVisitor() {

    @SuppressWarnings("unchecked")
    @Override
    public boolean visit(SwitchStatement node) {
      if (containsPosition(lineInfo, node.getStartPosition())) {
        SwitchCase defNode = node.getAST().newSwitchCase();
        defNode.setExpression(null);
        node.statements().add(defNode);
        node.statements().add(node.getAST().newBreakStatement());
      }
      return true; // also visit children
    }
  };
}
 
Example #4
Source File: MissingSwitchDefaultQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(SwitchStatement node) {
            if (containsPosition(lineInfo, node.getStartPosition())) {
                final SwitchCase defNode = node.getAST().newSwitchCase();
                defNode.setExpression(null);
                node.statements().add(defNode);
                node.statements().add(node.getAST().newBreakStatement());
            }
            return true; // also visit children
        }
    };
}
 
Example #5
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Statement getParentLoopBody(ASTNode node) {
	Statement stmt = null;
	ASTNode start = node;
	while (start != null && !(start instanceof ForStatement) && !(start instanceof DoStatement) && !(start instanceof WhileStatement) && !(start instanceof EnhancedForStatement) && !(start instanceof SwitchStatement)) {
		start = start.getParent();
	}
	if (start instanceof ForStatement) {
		stmt = ((ForStatement) start).getBody();
	} else if (start instanceof DoStatement) {
		stmt = ((DoStatement) start).getBody();
	} else if (start instanceof WhileStatement) {
		stmt = ((WhileStatement) start).getBody();
	} else if (start instanceof EnhancedForStatement) {
		stmt = ((EnhancedForStatement) start).getBody();
	}
	if (start != null && start.getParent() instanceof LabeledStatement) {
		LabeledStatement labeledStatement = (LabeledStatement) start.getParent();
		fEnclosingLoopLabel = labeledStatement.getLabel();
	}
	return stmt;
}
 
Example #6
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void addMissingDefaultCaseProposal(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression) {
		StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
		ASTNode parent = selectedNode.getParent();
		List<Statement> statements;

		if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) {
			statements = ((SwitchStatement) parent).statements();
		} else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) {
			statements = ((SwitchExpression) parent).statements();
		} else {
			return;
		}

		for (Statement statement : statements) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
				return;
			}
		}
		createMissingDefaultProposal(context, parent, proposals);
	}
}
 
Example #7
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> 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;
				ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example #8
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(final ReturnStatement node) {
  this.appendToBuffer("return");
  Expression _expression = node.getExpression();
  boolean _tripleNotEquals = (_expression != null);
  if (_tripleNotEquals) {
    this.appendSpaceToBuffer();
    node.getExpression().accept(this);
    this.appendSpaceToBuffer();
  } else {
    final ASTNode parent = node.getParent();
    final boolean isIfElse = ((parent instanceof IfStatement) && (((IfStatement) parent).getElseStatement() != null));
    if (((!isIfElse) && (!(parent instanceof SwitchStatement)))) {
      this.appendToBuffer(";");
    }
  }
  return false;
}
 
Example #9
Source File: InputFlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void endVisit(SwitchStatement node) {
	if (skipNode(node))
		return;
	SwitchData data= createSwitchData(node);
	IRegion[] ranges= data.getRanges();
	for (int i= 0; i < ranges.length; i++) {
		IRegion range= ranges[i];
		if (fSelection.coveredBy(range)) {
			GenericSequentialFlowInfo info= createSequential();
			setFlowInfo(node, info);
			info.merge(getFlowInfo(node.getExpression()), fFlowContext);
			info.merge(data.getInfo(i), fFlowContext);
			info.removeLabel(null);
			return;
		}
	}
	super.endVisit(node, data);
}
 
Example #10
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Statement getParentLoopBody(ASTNode node) {
	Statement stmt= null;
	ASTNode start= node;
	while (start != null
			&& !(start instanceof ForStatement)
			&& !(start instanceof DoStatement)
			&& !(start instanceof WhileStatement)
			&& !(start instanceof EnhancedForStatement)
			&& !(start instanceof SwitchStatement)) {
		start= start.getParent();
	}
	if (start instanceof ForStatement) {
		stmt= ((ForStatement)start).getBody();
	} else if (start instanceof DoStatement) {
		stmt= ((DoStatement)start).getBody();
	} else if (start instanceof WhileStatement) {
		stmt= ((WhileStatement)start).getBody();
	} else if (start instanceof EnhancedForStatement) {
		stmt= ((EnhancedForStatement)start).getBody();
	}
	if (start != null && start.getParent() instanceof LabeledStatement) {
		LabeledStatement labeledStatement= (LabeledStatement)start.getParent();
		fEnclosingLoopLabel= labeledStatement.getLabel();
	}
	return stmt;
}
 
Example #11
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
			}
		}
	}
}
 
Example #14
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void getMissingEnumConstantCaseProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	for (Iterator<ICommandAccess> iterator= proposals.iterator(); iterator.hasNext();) {
		ICommandAccess proposal= iterator.next();
		if (proposal instanceof ChangeCorrectionProposal) {
			if (CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description.equals(((ChangeCorrectionProposal) proposal).getName())) {
				return;
			}
		}
	}
	
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		SwitchStatement statement= (SwitchStatement) selectedNode.getParent();
		ITypeBinding binding= statement.getExpression().resolveTypeBinding();
		if (binding == null || !binding.isEnum()) {
			return;
		}

		ArrayList<String> missingEnumCases= new ArrayList<String>();
		boolean hasDefault= evaluateMissingSwitchCases(binding, statement.statements(), missingEnumCases);
		if (missingEnumCases.size() == 0 && hasDefault)
			return;

		createMissingCaseProposals(context, statement, missingEnumCases, proposals);
	}
}
 
Example #15
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void getMissingEnumConstantCaseProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	for (ChangeCorrectionProposal proposal : proposals) {
		if (CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description.equals(proposal.getName())) {
			return;
		}
	}

	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression) {
		StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
		ASTNode parent = selectedNode.getParent();
		ITypeBinding binding;
		List<Statement> statements;

		if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) {
			SwitchStatement statement = (SwitchStatement) parent;
			binding = statement.getExpression().resolveTypeBinding();
			statements = statement.statements();
		} else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) {
			SwitchExpression switchExpression = (SwitchExpression) parent;
			binding = switchExpression.getExpression().resolveTypeBinding();
			statements = switchExpression.statements();
		} else {
			return;
		}

		if (binding == null || !binding.isEnum()) {
			return;
		}

		ArrayList<String> missingEnumCases = new ArrayList<>();
		boolean hasDefault = evaluateMissingSwitchCases(binding, statements, missingEnumCases);
		if (missingEnumCases.size() == 0 && hasDefault) {
			return;
		}

		createMissingCaseProposals(context, parent, missingEnumCases, proposals);
	}
}
 
Example #17
Source File: ImplementationSmellDetector.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
private void hasMissingDefaults() {
	MethodControlFlowVisitor visitor = new MethodControlFlowVisitor();
	methodMetrics.getMethod().getMethodDeclaration().accept(visitor);
	List<SwitchStatement> switchStatements = visitor.getSwitchStatements();
	for(SwitchStatement singleSwitchStatement : switchStatements) {
		if(switchIsMissingDefault(singleSwitchStatement)) {
			addToSmells(initializeCodeSmell(MISSING_DEFAULT));
		}
	}
}
 
Example #18
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(SwitchStatement stmnt){
	/*
	 * switch ( Expression )
                       { { SwitchCase | Statement } } }
	 */
	styledString.append("switch", new StyledStringStyler(keywordStyle));
	appendSpace();
	appendOpenParenthesis();
	handleExpression((Expression) stmnt.getExpression());
	appendClosedParenthesis();
	return false;
}
 
Example #19
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #20
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void endVisit(SwitchStatement node, SwitchData data) {
	SwitchFlowInfo switchFlowInfo= createSwitch();
	setFlowInfo(node, switchFlowInfo);
	switchFlowInfo.mergeTest(getFlowInfo(node.getExpression()), fFlowContext);
	FlowInfo[] cases= data.getInfos();
	for (int i= 0; i < cases.length; i++)
		switchFlowInfo.mergeCase(cases[i], fFlowContext);
	switchFlowInfo.mergeDefault(data.hasDefaultCase(), fFlowContext);
	switchFlowInfo.removeLabel(null);
}
 
Example #21
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private SwitchStmt visit(SwitchStatement node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	SwitchStmt switchStmt = new SwitchStmt(startLine, endLine, node);
	
	Expr expression = (Expr) process(node.getExpression());
	expression.setParent(switchStmt);
	switchStmt.setExpression(expression);
	
	SwCase lastSW = null;
	List<Stmt> statements = new ArrayList<>();
	for(Object object : node.statements()){
		Stmt stmt = (Stmt) process((ASTNode) object);
		stmt.setParent(switchStmt);
		if (stmt instanceof SwCase) {
			lastSW = (SwCase) stmt;
			statements.add(stmt);
		} else if(lastSW != null){
			lastSW.addSibling(stmt);
		} else {
			statements.add(stmt);
		}
	}
	switchStmt.setStatements(statements);
	
	return switchStmt;
}
 
Example #23
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void insertAt(ASTNode target, Statement declaration) {
	ASTRewrite rewrite= fCURewrite.getASTRewrite();
	TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable);

	ASTNode parent= target.getParent();
	StructuralPropertyDescriptor locationInParent= target.getLocationInParent();
	while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) {
		if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
				|| locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
				|| locationInParent == ForStatement.BODY_PROPERTY
				|| locationInParent == EnhancedForStatement.BODY_PROPERTY
				|| locationInParent == DoStatement.BODY_PROPERTY
				|| locationInParent == WhileStatement.BODY_PROPERTY) {
			// create intermediate block if target was the body property of a control statement:
			Block replacement= rewrite.getAST().newBlock();
			ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			replacementRewrite.insertFirst(declaration, null);
			replacementRewrite.insertLast(rewrite.createMoveTarget(target), null);
			rewrite.replace(target, replacement, groupDescription);
			return;
		}
		target= parent;
		parent= parent.getParent();
		locationInParent= target.getLocationInParent();
	}
	ListRewrite listRewrite= rewrite.getListRewrite(parent, (ChildListPropertyDescriptor)locationInParent);
	listRewrite.insertBefore(declaration, target, groupDescription);
}
 
Example #24
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
private static AbstractControlStructure generateAbstractControlStructure(Object object)
{
	if (object instanceof IfStatement)
	{
		return new IfControlStructure((IfStatement) object);
	}
	else if (object instanceof SwitchStatement)
	{
		return new SwitchControlStructure((SwitchStatement) object);
	}
	else if (object instanceof ExpressionStatement)
	{
		ExpressionStatement expressionStatement = (ExpressionStatement) object;
		if (AbstractControlStructureUtilities.hasOneConditionalExpression(expressionStatement) != null)
		{
			return new TernaryControlStructure(expressionStatement);
		}
	}
	else if (object instanceof ReturnStatement)
	{
		ReturnStatement returnStatement = (ReturnStatement) object;
		if (returnStatement.getExpression() instanceof ConditionalExpression)
		{
			return new TernaryControlStructure(returnStatement);
		}
	}
	return null;
}
 
Example #25
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean match(SwitchStatement node, Object other) {
	if (!(other instanceof SwitchStatement)) {
		return false;
	}
	SwitchStatement o = (SwitchStatement) other;
	if(isNestedUnderAnonymousClassDeclaration(node) && isNestedUnderAnonymousClassDeclaration(o)) {
		return super.match(node, o);
	}
	SwitchControlStructure nodeSwitchStructure = new SwitchControlStructure(node);
	SwitchControlStructure otherSwitchStructure = new SwitchControlStructure((SwitchStatement)other);
	return nodeSwitchStructure.match(otherSwitchStructure, this);
}
 
Example #26
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void createMissingDefaultProposal(IInvocationContext context, SwitchStatement switchStatement, Image image, Collection<ICommandAccess> proposals) {
	AST ast= switchStatement.getAST();
	ASTRewrite astRewrite= ASTRewrite.create(ast);
	ListRewrite listRewrite= astRewrite.getListRewrite(switchStatement, SwitchStatement.STATEMENTS_PROPERTY);

	SwitchCase newSwitchCase= ast.newSwitchCase();
	newSwitchCase.setExpression(null);
	listRewrite.insertLast(newSwitchCase, null);
	listRewrite.insertLast(ast.newBreakStatement(), null);

	String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_description;
	proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE, image));
}
 
Example #27
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getConvertSwitchToIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
	if (!(covering instanceof SwitchStatement)) {
		return false;
	}
	//  we could produce quick assist (if all 'case' statements end with 'break')
	if (resultingCollections == null) {
		return true;
	}
	if (!getConvertSwitchToIfProposals(context, covering, resultingCollections, false))
		return false;
	return getConvertSwitchToIfProposals(context, covering, resultingCollections, true);
}
 
Example #28
Source File: StatementAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: StatementAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addMissingDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		SwitchStatement switchStatement= (SwitchStatement) selectedNode.getParent();
		for (Statement statement : (List<Statement>) switchStatement.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
				return;
			}
		}
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		createMissingDefaultProposal(context, switchStatement, image, proposals);
	}
}