use of org.eclipse.jdt.core.dom.Statement in project che by eclipse.
the class ScopeAnalyzer method getDeclarationsAfter.
public IBinding[] getDeclarationsAfter(int offset, int flags) {
try {
org.eclipse.jdt.core.dom.NodeFinder finder = new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
ASTNode node = finder.getCoveringNode();
if (node == null) {
return null;
}
ASTNode declaration = ASTResolving.findParentStatement(node);
while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
declaration = declaration.getParent();
}
if (declaration instanceof Block) {
DefaultBindingRequestor requestor = new DefaultBindingRequestor();
DeclarationsAfterVisitor visitor = new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
declaration.accept(visitor);
List<IBinding> result = requestor.getResult();
return result.toArray(new IBinding[result.size()]);
}
return NO_BINDING;
} finally {
clearLists();
}
}
use of org.eclipse.jdt.core.dom.Statement in project che by eclipse.
the class ConvertAnonymousToNestedRefactoring method updateAndMoveBodyDeclarations.
private void updateAndMoveBodyDeclarations(CompilationUnitRewrite rewriter, IVariableBinding[] bindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations, MethodDeclaration newConstructorDecl) {
final ASTRewrite astRewrite = rewriter.getASTRewrite();
final AST ast = astRewrite.getAST();
final boolean useThisAccess = useThisForFieldAccess();
int fieldInsertIndex = newConstructorDecl != null ? newBodyDeclarations.lastIndexOf(newConstructorDecl) : newBodyDeclarations.size();
for (Iterator<BodyDeclaration> iterator = fAnonymousInnerClassNode.bodyDeclarations().iterator(); iterator.hasNext(); ) {
BodyDeclaration body = iterator.next();
for (int i = 0; i < bindings.length; i++) {
SimpleName[] names = LinkedNodeFinder.findByBinding(body, bindings[i]);
String fieldName = fieldNames[i];
for (int k = 0; k < names.length; k++) {
SimpleName newNode = ast.newSimpleName(fieldName);
if (useThisAccess) {
FieldAccess access = ast.newFieldAccess();
access.setExpression(ast.newThisExpression());
access.setName(newNode);
astRewrite.replace(names[k], access, null);
} else {
astRewrite.replace(names[k], newNode, null);
}
addLinkedPosition(KEY_FIELD_NAME_EXT + i, newNode, astRewrite, false);
}
}
if (body instanceof Initializer || body instanceof FieldDeclaration) {
newBodyDeclarations.add(fieldInsertIndex++, (BodyDeclaration) astRewrite.createMoveTarget(body));
} else {
newBodyDeclarations.add((BodyDeclaration) astRewrite.createMoveTarget(body));
}
}
if (newConstructorDecl != null) {
// move initialization of existing fields to constructor if an outer is referenced
List<Statement> bodyStatements = newConstructorDecl.getBody().statements();
List<VariableDeclarationFragment> fieldsToInitializeInConstructor = getFieldsToInitializeInConstructor();
for (Iterator<VariableDeclarationFragment> iter = fieldsToInitializeInConstructor.iterator(); iter.hasNext(); ) {
VariableDeclarationFragment fragment = iter.next();
Expression initializer = fragment.getInitializer();
Expression replacement = (Expression) astRewrite.get(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY);
if (replacement == initializer) {
replacement = (Expression) astRewrite.createMoveTarget(initializer);
}
astRewrite.remove(initializer, null);
SimpleName fieldNameNode = ast.newSimpleName(fragment.getName().getIdentifier());
bodyStatements.add(newFieldAssignment(ast, fieldNameNode, replacement, useThisAccess));
}
}
}
use of org.eclipse.jdt.core.dom.Statement in project che by eclipse.
the class ConvertAnonymousToNestedRefactoring method createNewConstructor.
private MethodDeclaration createNewConstructor(CompilationUnitRewrite rewrite, IVariableBinding[] bindings, String[] fieldNames) throws JavaModelException {
ClassInstanceCreation instanceCreation = (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
if (instanceCreation.arguments().isEmpty() && bindings.length == 0)
return null;
IJavaProject project = fCu.getJavaProject();
AST ast = rewrite.getAST();
ImportRewrite importRewrite = rewrite.getImportRewrite();
ASTRewrite astRewrite = rewrite.getASTRewrite();
MethodDeclaration newConstructor = ast.newMethodDeclaration();
newConstructor.setConstructor(true);
newConstructor.setJavadoc(null);
newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, fVisibility));
newConstructor.setName(ast.newSimpleName(fClassName));
addLinkedPosition(KEY_TYPE_NAME, newConstructor.getName(), astRewrite, false);
newConstructor.setBody(ast.newBlock());
List<Statement> newStatements = newConstructor.getBody().statements();
List<SingleVariableDeclaration> newParameters = newConstructor.parameters();
List<String> newParameterNames = new ArrayList<String>();
// add parameters for elements passed with the instance creation
if (!instanceCreation.arguments().isEmpty()) {
IMethodBinding constructorBinding = getSuperConstructorBinding();
if (constructorBinding != null) {
SuperConstructorInvocation superConstructorInvocation = ast.newSuperConstructorInvocation();
ITypeBinding[] parameterTypes = constructorBinding.getParameterTypes();
String[][] parameterNames = StubUtility.suggestArgumentNamesWithProposals(project, constructorBinding);
for (int i = 0; i < parameterNames.length; i++) {
String[] nameProposals = parameterNames[i];
String paramName = nameProposals[0];
SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, parameterTypes[i]);
newParameters.add(param);
newParameterNames.add(paramName);
SimpleName newSIArgument = ast.newSimpleName(paramName);
superConstructorInvocation.arguments().add(newSIArgument);
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_CONST + String.valueOf(i), true);
positionGroup.addPosition(astRewrite.track(param.getName()), false);
positionGroup.addPosition(astRewrite.track(newSIArgument), false);
for (int k = 0; k < nameProposals.length; k++) {
positionGroup.addProposal(nameProposals[k], null, nameProposals.length - k);
}
}
}
newStatements.add(superConstructorInvocation);
}
}
// add parameters for all outer variables used
boolean useThisAccess = useThisForFieldAccess();
for (int i = 0; i < bindings.length; i++) {
String baseName = StubUtility.getBaseName(bindings[i], project);
String[] paramNameProposals = StubUtility.getVariableNameSuggestions(NamingConventions.VK_PARAMETER, project, baseName, 0, newParameterNames, true);
String paramName = paramNameProposals[0];
SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, bindings[i].getType());
newParameters.add(param);
newParameterNames.add(paramName);
String fieldName = fieldNames[i];
SimpleName fieldNameNode = ast.newSimpleName(fieldName);
SimpleName paramNameNode = ast.newSimpleName(paramName);
newStatements.add(newFieldAssignment(ast, fieldNameNode, paramNameNode, useThisAccess || newParameterNames.contains(fieldName)));
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_EXT + String.valueOf(i), true);
positionGroup.addPosition(astRewrite.track(param.getName()), false);
positionGroup.addPosition(astRewrite.track(paramNameNode), false);
for (int k = 0; k < paramNameProposals.length; k++) {
positionGroup.addProposal(paramNameProposals[k], null, paramNameProposals.length - k);
}
fLinkedProposalModel.getPositionGroup(KEY_FIELD_NAME_EXT + i, true).addPosition(astRewrite.track(fieldNameNode), false);
}
}
addExceptionsToNewConstructor(newConstructor, importRewrite);
if (doAddComments()) {
try {
String[] allParamNames = newParameterNames.toArray(new String[newParameterNames.size()]);
String string = CodeGeneration.getMethodComment(fCu, fClassName, fClassName, allParamNames, new String[0], null, new String[0], null, StubUtility.getLineDelimiterUsed(fCu));
if (string != null) {
Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
newConstructor.setJavadoc(javadoc);
}
} catch (CoreException exception) {
throw new JavaModelException(exception);
}
}
return newConstructor;
}
use of org.eclipse.jdt.core.dom.Statement in project che by eclipse.
the class CallInliner method initializeInsertionPoint.
private void initializeInsertionPoint(int nos) {
fInsertionIndex = -1;
fNeedsStatement = false;
// if we have a constructor invocation the invocation itself is already a statement
ASTNode parentStatement = fInvocation instanceof Statement ? fInvocation : ASTNodes.getParent(fInvocation, Statement.class);
if (parentStatement == null)
return;
ASTNode container = parentStatement.getParent();
int type = container.getNodeType();
if (type == ASTNode.BLOCK) {
Block block = (Block) container;
fListRewrite = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
fInsertionIndex = fListRewrite.getRewrittenList().indexOf(parentStatement);
} else if (type == ASTNode.SWITCH_STATEMENT) {
SwitchStatement switchStatement = (SwitchStatement) container;
fListRewrite = fRewrite.getListRewrite(switchStatement, SwitchStatement.STATEMENTS_PROPERTY);
fInsertionIndex = fListRewrite.getRewrittenList().indexOf(parentStatement);
} else if (isControlStatement(container) || type == ASTNode.LABELED_STATEMENT) {
fNeedsStatement = true;
if (nos > 1 || needsBlockAroundDanglingIf()) {
Block block = fInvocation.getAST().newBlock();
fInsertionIndex = 0;
Statement currentStatement = null;
switch(type) {
case ASTNode.LABELED_STATEMENT:
currentStatement = ((LabeledStatement) container).getBody();
break;
case ASTNode.FOR_STATEMENT:
currentStatement = ((ForStatement) container).getBody();
break;
case ASTNode.ENHANCED_FOR_STATEMENT:
currentStatement = ((EnhancedForStatement) container).getBody();
break;
case ASTNode.WHILE_STATEMENT:
currentStatement = ((WhileStatement) container).getBody();
break;
case ASTNode.DO_STATEMENT:
currentStatement = ((DoStatement) container).getBody();
break;
case ASTNode.IF_STATEMENT:
IfStatement node = (IfStatement) container;
Statement thenPart = node.getThenStatement();
if (fTargetNode == thenPart || ASTNodes.isParent(fTargetNode, thenPart)) {
currentStatement = thenPart;
} else {
currentStatement = node.getElseStatement();
}
break;
}
Assert.isNotNull(currentStatement);
fRewrite.replace(currentStatement, block, null);
fListRewrite = fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
// The method to be inlined is not the body of the control statement.
if (currentStatement != fTargetNode) {
fListRewrite.insertLast(fRewrite.createCopyTarget(currentStatement), null);
} else {
// We can't replace a copy with something else. So we
// have to insert all statements to be inlined.
fTargetNode = null;
}
}
}
// We only insert one new statement or we delete the existing call.
// So there is no need to have an insertion index.
}
use of org.eclipse.jdt.core.dom.Statement in project flux by eclipse.
the class CodeFormatterUtil method format2.
/**
* Creates edits that describe how to format the given string.
* The given node is used to infer the kind to use to format the string.
* Consider to use {@link #format2(int, String, int, String, Map)} if the kind is already known.
* Returns <code>null</code> if the code could not be formatted for the given kind.
*
* @param node
* Use to infer the kind of the code snippet to format.
* @param source
* The source to format
* @param indentationLevel
* The initial indentation level, used to shift left/right the entire source fragment.
* An initial indentation level of zero or below has no effect.
* @param lineSeparator
* The line separator to use in formatted source,
* if set to <code>null</code>, then the platform default one will be used.
* @param options
* The options map to use for formatting with the default code formatter.
* Recognized options are documented on {@link JavaCore#getDefaultOptions()}.
* If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}.
* @return an TextEdit describing the changes required to format source
* @throws IllegalArgumentException
* If the offset and length are not inside the string, a IllegalArgumentException is thrown.
*/
public static TextEdit format2(ASTNode node, String source, int indentationLevel, String lineSeparator, Map<String, String> options) {
int code;
//$NON-NLS-1$
String prefix = "";
//$NON-NLS-1$
String suffix = "";
if (node instanceof Statement) {
code = CodeFormatter.K_STATEMENTS;
if (node.getNodeType() == ASTNode.SWITCH_CASE) {
//$NON-NLS-1$
prefix = "switch(1) {";
//$NON-NLS-1$
suffix = "}";
code = CodeFormatter.K_STATEMENTS;
}
} else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
code = CodeFormatter.K_EXPRESSION;
} else if (node instanceof BodyDeclaration) {
code = CodeFormatter.K_CLASS_BODY_DECLARATIONS;
} else {
switch(node.getNodeType()) {
case ASTNode.ARRAY_TYPE:
case ASTNode.PARAMETERIZED_TYPE:
case ASTNode.PRIMITIVE_TYPE:
case ASTNode.QUALIFIED_TYPE:
case ASTNode.SIMPLE_TYPE:
//$NON-NLS-1$
suffix = " x;";
code = CodeFormatter.K_CLASS_BODY_DECLARATIONS;
break;
case ASTNode.WILDCARD_TYPE:
//$NON-NLS-1$
prefix = "A<";
//$NON-NLS-1$
suffix = "> x;";
code = CodeFormatter.K_CLASS_BODY_DECLARATIONS;
break;
case ASTNode.COMPILATION_UNIT:
code = CodeFormatter.K_COMPILATION_UNIT;
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
case ASTNode.SINGLE_VARIABLE_DECLARATION:
//$NON-NLS-1$
suffix = ";";
code = CodeFormatter.K_STATEMENTS;
break;
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
//$NON-NLS-1$
prefix = "A ";
//$NON-NLS-1$
suffix = ";";
code = CodeFormatter.K_STATEMENTS;
break;
case ASTNode.PACKAGE_DECLARATION:
case ASTNode.IMPORT_DECLARATION:
//$NON-NLS-1$
suffix = "\nclass A {}";
code = CodeFormatter.K_COMPILATION_UNIT;
break;
case ASTNode.JAVADOC:
//$NON-NLS-1$
suffix = "void foo();";
code = CodeFormatter.K_CLASS_BODY_DECLARATIONS;
break;
case ASTNode.CATCH_CLAUSE:
//$NON-NLS-1$
prefix = "try {}";
code = CodeFormatter.K_STATEMENTS;
break;
case ASTNode.ANONYMOUS_CLASS_DECLARATION:
//$NON-NLS-1$
prefix = "new A()";
//$NON-NLS-1$
suffix = ";";
code = CodeFormatter.K_STATEMENTS;
break;
case ASTNode.MEMBER_VALUE_PAIR:
//$NON-NLS-1$
prefix = "@Author(";
//$NON-NLS-1$
suffix = ") class x {}";
code = CodeFormatter.K_COMPILATION_UNIT;
break;
case ASTNode.MODIFIER:
//$NON-NLS-1$
suffix = " class x {}";
code = CodeFormatter.K_COMPILATION_UNIT;
break;
case ASTNode.TYPE_PARAMETER:
//$NON-NLS-1$
prefix = "class X<";
//$NON-NLS-1$
suffix = "> {}";
code = CodeFormatter.K_COMPILATION_UNIT;
break;
case ASTNode.MEMBER_REF:
case ASTNode.METHOD_REF:
case ASTNode.METHOD_REF_PARAMETER:
case ASTNode.TAG_ELEMENT:
case ASTNode.TEXT_ELEMENT:
// Javadoc formatting not yet supported:
return null;
default:
//Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$
return null;
}
}
String concatStr = prefix + source + suffix;
TextEdit edit = format2(code, concatStr, prefix.length(), source.length(), indentationLevel, lineSeparator, options);
if (edit != null && prefix.length() > 0) {
edit.moveTree(-prefix.length());
}
return edit;
}
Aggregations