List of usage examples for org.eclipse.jdt.core.dom Block statements
ASTNode.NodeList statements
To view the source code for org.eclipse.jdt.core.dom Block statements.
Click Source Link
From source file:org.eclipse.wb.internal.core.model.variable.LazyVariableSupport.java
License:Open Source License
@Override public String add_getVariableStatementSource(StatementTarget associationTarget) throws Exception { AstEditor editor = m_javaInfo.getEditor(); boolean isStatic = isStaticContext(associationTarget.getPosition()); // prepare component class String className = ReflectionUtils.getCanonicalName(m_javaInfo.getDescription().getComponentClass()); // add field/*from w w w. j a v a 2 s . com*/ String fieldName; FieldDeclaration field; { // prepare modifiers String modifiers = "private "; if (isStatic) { modifiers += "static "; } // do add fieldName = editor.getUniqueVariableName(-1, NamesManager.getName(m_javaInfo), null); field = addField(modifiers + className + " " + fieldName + ";"); } // add method { String methodName = LazyVariableSupportUtils.getExpectedMethodName(m_javaInfo, fieldName); methodName = editor.getUniqueMethodName(methodName); // prepare target BodyDeclarationTarget bodyTarget; { TypeDeclaration typeDeclaration = AstNodeUtils.getEnclosingType(field); bodyTarget = new BodyDeclarationTarget(typeDeclaration, false); } // add accessor method { NodeTarget creationTarget = new NodeTarget(bodyTarget); String initializer = m_javaInfo.getCreationSupport().add_getSource(creationTarget); initializer = AssociationUtils.replaceTemplates(m_javaInfo, initializer, creationTarget); // prepare modifiers String modifiers = prefMethodModifier(m_javaInfo); if (isStatic) { modifiers += "static "; } // String header = modifiers + className + " " + methodName + "()"; List<String> bodyLines = Lists.newArrayList(); bodyLines.add("if (" + fieldName + " == null) {"); bodyLines.add("\t" + fieldName + " = " + initializer + ";"); bodyLines.add("}"); bodyLines.add("return " + fieldName + ";"); m_accessor = editor.addMethodDeclaration(header, bodyLines, bodyTarget); } // include accessor into execution flow, to allow visiting its nodes JavaInfoUtils.getState(m_javaInfo).getFlowDescription().addStartMethod(m_accessor); // initialize variable and creation { IfStatement ifStatement = (IfStatement) m_accessor.getBody().statements().get(0); Block thenBlock = (Block) ifStatement.getThenStatement(); ExpressionStatement expressionStatement = (ExpressionStatement) thenBlock.statements().get(0); Assignment assignment = (Assignment) expressionStatement.getExpression(); add_setVariableAndInitializer(assignment.getLeftHandSide(), assignment.getRightHandSide()); } } // no variable statement return null; }
From source file:org.eclipse.wb.internal.core.model.variable.LazyVariableSupportUtils.java
License:Open Source License
/** * Conversion for {@link FieldVariableSupport}. *///from www .ja va 2 s . c o m private static LazyVariableInformation convertAsField(JavaInfo javaInfo) throws Exception { FieldVariableSupport fieldVariableSupport = (FieldVariableSupport) javaInfo.getVariableSupport(); String fieldName = fieldVariableSupport.getName(); Expression creation = (Expression) javaInfo.getCreationSupport().getNode(); // add method by template MethodDeclaration accessor = addMethod(javaInfo, AstNodeUtils.getEnclosingType(creation), fieldName); // initialize variable and creation Assignment assignment; { IfStatement ifStatement = (IfStatement) accessor.getBody().statements().get(0); Block thenBlock = (Block) ifStatement.getThenStatement(); ExpressionStatement expressionStatement = (ExpressionStatement) thenBlock.statements().get(0); assignment = (Assignment) expressionStatement.getExpression(); } AstEditor editor = javaInfo.getEditor(); StatementTarget target = new StatementTarget(assignment, false); // process related nodes List<Statement> moveStatements = Lists.newArrayList(); List<ASTNode> replaceNodes = Lists.newArrayList(); // prepare node lists... collectNodesToEdit(javaInfo, moveStatements, replaceNodes, target); moveStatements.remove(AstNodeUtils.getEnclosingStatement(creation)); replaceNodes.remove(creation); // move creation directly { // check Assert.isTrue(canMoveNode(target, javaInfo, creation)); // remove creation at old location String replacementSource = editor.getSource(creation); { // replace by "null" and remove statement NullLiteral newNullLiteral = creation.getAST().newNullLiteral(); AstEditor.replaceNode(creation, newNullLiteral); editor.removeEnclosingStatement(newNullLiteral); } // replace "null" expression in template by creation ASTNode originalNode = assignment.getRightHandSide(); int startPosition = originalNode.getStartPosition(); editor.replaceExpression((Expression) originalNode, replacementSource); AstNodeUtils.moveNode(creation, startPosition); assignment.setRightHandSide(creation); } // replace statements with blocks { // prepare unique list of blocks List<Block> blocks = Lists.newArrayList(); for (Statement statement : moveStatements) { Block block = AstNodeUtils.getEnclosingBlock(statement); if (!blocks.contains(block)) { blocks.add(block); } } // replace statements with blocks Collections.sort(blocks, AstNodeUtils.SORT_BY_REVERSE_POSITION); for (Block block : blocks) { List<Statement> blockStatements = DomGenerics.statements(block); if (moveStatements.containsAll(blockStatements) && block.getParent() instanceof Block) { moveStatements.removeAll(blockStatements); moveStatements.add(block); } } } // sort the resulting list of statements { Statement[] statements = moveStatements.toArray(new Statement[moveStatements.size()]); Arrays.sort(statements, AstNodeUtils.SORT_BY_POSITION); moveStatements = Lists.newArrayList(statements); } // move statements for (Statement moveStatement : moveStatements) { editor.moveStatement(moveStatement, target); target = new StatementTarget(moveStatement, false); } // replace field access nodes to access by invocation nodes String invocationSource = accessor.getName().getIdentifier() + "()"; List<ASTNode> relatedNodes = javaInfo.getRelatedNodes(); for (ASTNode replaceNode : replaceNodes) { if (relatedNodes.contains(replaceNode)) { Expression replaceExpression = editor.replaceExpression((Expression) replaceNode, invocationSource); relatedNodes.remove(replaceNode); javaInfo.addRelatedNode(replaceExpression); } } // ready return new LazyVariableInformation(accessor, assignment.getLeftHandSide(), creation); }
From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java
License:Open Source License
/** * Adds new {@link Statement} with given source in given {@link StatementTarget}. * /*from ww w. j a v a2s . com*/ * @param lines * the lines of source (possible with empty lines) with single statement. * @param target * describes location for new {@link Statement}. */ public Statement addStatement(List<String> lines, StatementTarget target) throws Exception { Assert.isNotNull(lines); // statement or method declaration required Assert.isTrue(target.getBlock() != null || target.getStatement() != null); // prepare code generation constants AstCodeGeneration generation = getGeneration(); String singleIndent = generation.getIndentation(1); String eol = generation.getEndOfLine(); // if (target.getStatement() != null) { Statement targetStatement = target.getStatement(); Block targetBlock = ensureParentBlock(targetStatement); // prepare information about target statement String indent = getWhitespaceToLeft(targetStatement.getStartPosition(), false); int index = targetBlock.statements().indexOf(targetStatement); // prepare source String source = getIndentedSource(lines, indent, singleIndent, eol); source = replaceSourceTemplates(targetStatement.getStartPosition(), source); // add statement Statement newStatement; if (target.isBefore()) { // add before any empty lines and EOLC lines int position = skipWhitespaceAndPureEOLCToLeft(targetStatement.getStartPosition()); // add source replaceSubstring(position, 0, source + eol); // parse statement newStatement = getParser().parseStatement(position, source); DomGenerics.statements(targetBlock).add(index, newStatement); } else { // move at the end of target int position = getStatementEndIndex(targetStatement); source = eol + source; // add source replaceSubstring(position, 0, source); // parse statement newStatement = getParser().parseStatement(position, source); DomGenerics.statements(targetBlock).add(index + 1, newStatement); } // resolveImports(newStatement); return newStatement; } else { Block targetBlock = target.getBlock(); // prepare indentation String indent; { if (targetBlock.getParent() instanceof MethodDeclaration) { indent = getWhitespaceToLeft(targetBlock.getParent().getStartPosition(), false); } else { indent = getWhitespaceToLeft(targetBlock.getStartPosition(), false); } indent += singleIndent; } // prepare source String source = getIndentedSource(lines, indent, singleIndent, eol); source = replaceSourceTemplates(targetBlock.getStartPosition(), source); // add statement Statement newStatement; if (target.isBefore()) { // prepare position as position after '{' of block int position; { position = targetBlock.getStartPosition(); Assert.isTrue(position != -1); position++; } // add source { String prefix = eol; replaceSubstring(position, 0, prefix + source); position += prefix.length(); } // parse statement newStatement = getParser().parseStatement(position, source); DomGenerics.statements(targetBlock).add(0, newStatement); } else { // prepare position as position of '}' of block int position = AstNodeUtils.getSourceEnd(targetBlock) - 1; String endMethodIndent = getWhitespaceToLeft(position, false); position -= endMethodIndent.length(); // add source replaceSubstring(position, 0, source + eol); // parse statement newStatement = getParser().parseStatement(position, source); DomGenerics.statements(targetBlock).add(newStatement); } // resolveImports(newStatement); return newStatement; } }
From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java
License:Open Source License
/** * Move statement to given {@link StatementTarget}. * //from w ww . j ava 2 s . com * @param target * the new position for statement * @param statement * the statement to move * @param includePrefixComment * flag to mark that comment before statement also should be moved */ public void moveStatement(Statement statement, StatementTarget target) throws Exception { // statement or method declaration required Assert.isTrue(target.getBlock() != null || target.getStatement() != null); // check for no-op if (target.getStatement() != null) { Statement targetStatement = target.getStatement(); // adding relative same statement if (targetStatement == statement) { return; } // adding before current next statement Block targetBlock = (Block) targetStatement.getParent(); List<Statement> targetStatements = DomGenerics.statements(targetBlock); if (statement.getParent() == targetStatement.getParent()) { if (target.isBefore()) { // statement before target if (targetStatements.indexOf(statement) == targetStatements.indexOf(targetStatement) - 1) { return; } } else { // statement after target if (targetStatements.indexOf(statement) == targetStatements.indexOf(targetStatement) + 1) { return; } } } } else { Block targetBlock = target.getBlock(); List<Statement> targetStatements = DomGenerics.statements(targetBlock); if (statement.getParent() == targetBlock) { if (target.isBefore()) { if (targetStatements.indexOf(statement) == 0) { return; } } else { if (targetStatements.indexOf(statement) == targetStatements.size() - 1) { return; } } } } // prepare code generation constants AstCodeGeneration generation = getGeneration(); String singleIndent = generation.getIndentation(1); String eol = generation.getEndOfLine(); // prepare source location Block sourceBlock = (Block) statement.getParent(); int sourceBegin = skipWhitespaceAndPureEOLCToLeft(statement.getStartPosition()); int sourceLength = getStatementEndIndex(statement) - sourceBegin; // remove leading EOL { int leftEOLEnd = sourceBegin; int leftEOLBegin = skipSingleEOLToLeft(leftEOLEnd); int leftEOLLength = leftEOLEnd - leftEOLBegin; // replaceSubstring(leftEOLBegin, leftEOLLength, ""); sourceBegin -= leftEOLLength; } // if (target.getStatement() != null) { Statement targetStatement = target.getStatement(); String indent = getWhitespaceToLeft(targetStatement.getStartPosition(), false); // int position; if (target.isBefore()) { // move before any empty lines and EOLC lines position = skipWhitespaceAndPureEOLCToLeft(targetStatement.getStartPosition()); // move source position = moveSource(position, sourceBegin, sourceLength); // add EOL after statement replaceSubstring(position + sourceLength, 0, eol); } else { // move at the end of target position = getStatementEndIndex(targetStatement); // move source position = moveSource(position, sourceBegin, sourceLength); // add EOL before statement replaceSubstring(position, 0, eol); position += eol.length(); } // move node { Block targetBlock = (Block) targetStatement.getParent(); int index = targetBlock.statements().indexOf(targetStatement); if (!target.isBefore()) { index++; } if (sourceBlock == targetBlock && sourceBlock.statements().indexOf(statement) < index) { index--; } sourceBlock.statements().remove(statement); DomGenerics.statements(targetBlock).add(index, statement); } // re-indent reindentSource(position, sourceLength, indent, eol); } else { Block targetBlock = target.getBlock(); // prepare indentation String indent; { ASTNode indentNode = targetBlock; if (targetBlock.getLocationInParent() == MethodDeclaration.BODY_PROPERTY || targetBlock.getLocationInParent() == TryStatement.BODY_PROPERTY) { indentNode = targetBlock.getParent(); } indent = getWhitespaceToLeft(indentNode.getStartPosition(), false); indent += singleIndent; } // int position; if (target.isBefore()) { // prepare position as position after '{' of block { position = targetBlock.getStartPosition(); Assert.isTrue(position != -1); position++; } // move source position = moveSource(position, sourceBegin, sourceLength); // add EOL before statement replaceSubstring(position, 0, eol); position += eol.length(); // move node sourceBlock.statements().remove(statement); DomGenerics.statements(targetBlock).add(0, statement); } else { // prepare position as position of '}' of block position = AstNodeUtils.getSourceEnd(targetBlock) - 1; String endMethodIndent = getWhitespaceToLeft(position, false); position -= endMethodIndent.length(); // move source position = moveSource(position, sourceBegin, sourceLength); // add EOL after statement replaceSubstring(position + sourceLength, 0, eol); // move node sourceBlock.statements().remove(statement); DomGenerics.statements(targetBlock).add(statement); } // re-indent reindentSource(position, sourceLength, indent, eol); } }
From source file:org.eclipse.wb.internal.core.utils.ast.DomGenerics.java
License:Open Source License
@SuppressWarnings("unchecked") public static List<Statement> statements(Block block) { return block.statements(); }
From source file:org.eclipse.wb.internal.swt.model.layout.LayoutDataInfo.java
License:Open Source License
/** * Performs following optimizations:/* w w w.ja v a2 s. c o m*/ * <ul> * <li>When <code>LayoutData</code> gets converted from simple * <code>setLayoutData(new SomeData())</code> into real variable, wrap its {@link Statement}s with * {@link Block}.</li> * <li>When <code>LayoutData</code> has {@link LocalUniqueVariableSupport}, but it is used just to * call <code>setLayoutData()</code>, then variable may be inlined, and enclosing {@link Block} * probably too.</li> * <li>When <code>LayoutData</code> has all default values, then we can delete it at all.</li> * </ul> */ private void turnIntoBlock_whenEnsureVariable() { // empty -> Block addBroadcastListener(new JavaEventListener() { @Override public void variable_emptyMaterializeBefore(EmptyVariableSupport variableSupport) throws Exception { if (variableSupport.getJavaInfo() == m_this && isBlockMode()) { ASTNode creationNode = variableSupport.getInitializer(); Statement creationStatement = AstNodeUtils.getEnclosingStatement(creationNode); getEditor().encloseInBlock(creationStatement); } } private boolean isBlockMode() { GenerationSettings settings = getDescription().getToolkit().getGenerationSettings(); return settings.getStatement() == BlockStatementGeneratorDescription.INSTANCE; } }); // no invocations/fields -> inline Block addBroadcastListener(new ObjectEventListener() { @Override public void endEdit_aboutToRefresh() throws Exception { if (getVariableSupport() instanceof LocalUniqueVariableSupport) { LocalUniqueVariableSupport variableSupport = (LocalUniqueVariableSupport) getVariableSupport(); if (variableSupport.canInline()) { variableSupport.inline(); inlineBlockIfSingleStatement(); } } } private void inlineBlockIfSingleStatement() throws Exception { ASTNode node = ((EmptyVariableSupport) getVariableSupport()).getInitializer(); Statement statement = AstNodeUtils.getEnclosingStatement(node); if (statement != null) { Block block = (Block) statement.getParent(); if (block.statements().size() == 1) { getEditor().inlineBlock(block); } } } }); // is default -> delete addBroadcastListener(new ObjectEventListener() { @Override public void endEdit_aboutToRefresh() throws Exception { if (!isDeleted() && getCreationSupport() instanceof ConstructorCreationSupport && getMethodInvocations().isEmpty() && getFieldAssignments().isEmpty()) { ConstructorCreationSupport creationSupport = (ConstructorCreationSupport) getCreationSupport(); ClassInstanceCreation creation = creationSupport.getCreation(); String signature = creationSupport.getDescription().getSignature(); // prepare arguments List<Expression> arguments = DomGenerics.arguments(creation); if (!AstNodeUtils.areLiterals(arguments)) { return; } // evaluate arguments List<Object> argumentValues; { EditorState state = JavaInfoUtils.getState(m_this); EvaluationContext context = new EvaluationContext(state.getEditorLoader(), state.getFlowDescription()); argumentValues = Lists.newArrayList(); for (Expression argument : arguments) { Object value = AstEvaluationEngine.evaluate(context, argument); JavaInfoEvaluationHelper.setValue(argument, value); argumentValues.add(value); } } // delete, if default constructor arguments if (isDefault(signature, argumentValues)) { delete(); } } } /** * @return <code>true</code> if existing <code>isDefault</code> script says that object of * this {@link LayoutDataInfo} is in default state. */ private boolean isDefault(String signature, List<Object> args) throws Exception { String script = JavaInfoUtils.getParameter(m_this, "isDefault"); if (script != null) { Map<String, Object> variables = ImmutableMap.of("signature", signature, "args", args); return (Boolean) ScriptUtils.evaluate(JavaInfoUtils.getClassLoader(m_this), script, variables); } return false; } }); }
From source file:org.eclipse.wb.tests.designer.core.AbstractJavaTest.java
License:Open Source License
/** * @return the {@link Statement} with given index's in each {@link Block}. *//*from w w w . ja v a 2 s . c o m*/ protected static final Statement getStatement(Block block, int... indexes) { Statement statement = block; for (int i = 0; i < indexes.length; i++) { int index = indexes[i]; if (index == -1) { // handle -1 as "this", i.e. just ignore it, keep old statement } else { Block nextBlock; if (statement instanceof IfStatement) { nextBlock = (Block) ((IfStatement) statement).getThenStatement(); } else { nextBlock = (Block) statement; } statement = (Statement) nextBlock.statements().get(index); } } return statement; }
From source file:org.eclipse.wb.tests.designer.core.util.ast.AstEditorTest.java
License:Open Source License
/** * Tests for {@link AstEditor} "getEnclosing*" methods. *//*from w w w .j a va 2 s.co m*/ public void test_getEnclosing_all() throws Exception { TypeDeclaration typeDeclaration = createTypeDeclaration_Test("public class Test {", " void foo() {", " System.out.println();", " }", "}"); // prepare testing targets MethodDeclaration method = typeDeclaration.getMethods()[0]; Block block = method.getBody(); ExpressionStatement statement = (ExpressionStatement) block.statements().get(0); Expression expression = statement.getExpression(); // Statement { assertSame(statement, m_lastEditor.getEnclosingStatement(statement.getStartPosition())); assertSame(statement, m_lastEditor.getEnclosingStatement(statement.getStartPosition() + 5)); assertSame(statement, m_lastEditor.getEnclosingStatement(expression.getStartPosition())); assertNull(m_lastEditor.getEnclosingStatement(typeDeclaration.getStartPosition())); } // Block { assertSame(block, m_lastEditor.getEnclosingBlock(block.getStartPosition())); assertSame(block, m_lastEditor.getEnclosingBlock(statement.getStartPosition())); assertSame(block, m_lastEditor.getEnclosingBlock(statement.getStartPosition() + 5)); assertNull(m_lastEditor.getEnclosingBlock(typeDeclaration.getStartPosition())); } // MethodDeclaration { assertSame(method, m_lastEditor.getEnclosingMethod(method.getStartPosition())); assertSame(method, m_lastEditor.getEnclosingMethod(method.getStartPosition() + 5)); assertSame(method, m_lastEditor.getEnclosingMethod(block.getStartPosition())); assertNull(m_lastEditor.getEnclosingMethod(typeDeclaration.getStartPosition())); } // TypeDeclaration { assertSame(typeDeclaration, m_lastEditor.getEnclosingType(typeDeclaration.getStartPosition())); assertSame(typeDeclaration, m_lastEditor.getEnclosingType(typeDeclaration.getStartPosition() + 5)); assertNull(m_lastEditor.getEnclosingType(typeDeclaration.getParent().getStartPosition())); } }
From source file:org.eclipse.wb.tests.designer.core.util.ast.AstNodeUtilsTest.java
License:Open Source License
public void test_getEnclosingBlock() throws Exception { TypeDeclaration typeDeclaration = createTypeDeclaration_TestC("void foo(){System.out.println();}"); MethodDeclaration methodDeclaration = typeDeclaration.getMethods()[0]; Block body = methodDeclaration.getBody(); ///*from w w w . j a v a 2 s . c o m*/ ExpressionStatement statement = (ExpressionStatement) body.statements().get(0); assertSame(body, AstNodeUtils.getEnclosingBlock(body)); assertSame(body, AstNodeUtils.getEnclosingBlock(statement)); assertNull(AstNodeUtils.getEnclosingBlock(typeDeclaration)); }
From source file:org.eclipse.xtend.core.javaconverter.JavaASTFlattener.java
License:Open Source License
public void acceptSyntaticBlock(final Block node) { final int childrenCount = node.statements().size(); if ((childrenCount > 0)) { final Procedure2<ASTNode, Integer> _function = (ASTNode child, Integer counter) -> { child.accept(this); this.appendLineWrapToBuffer(); };/*from ww w. j a v a2 s . com*/ IterableExtensions.<ASTNode>forEach(node.statements(), _function); } }