/** * Create an AST name node with a name string (possibly partitioned with "."). * * @param ast The {@link org.eclipse.jdt.core.dom.AST} object. * @param name The name. * @return The AST name node. */ public static Name createName(AST ast, String name) { int oldPos = 0; Name fullName = null; while (oldPos != -1) { int pos = indexOf(name, new char[] {'.', '$'}, oldPos); String subname = (pos == -1) ? name.substring(oldPos) : name.substring(oldPos, pos); char c = subname.charAt(0); while ((c >= '0') && (c <= '9')) { subname = subname.substring(1); c = subname.charAt(0); } if (fullName == null) { fullName = ast.newSimpleName(subname); } else { fullName = ast.newQualifiedName(fullName, ast.newSimpleName(subname)); } if (pos == -1) { oldPos = -1; } else { oldPos = pos + 1; } } return fullName; }
public static MarkerAnnotation createValAnnotation( AST ast, Annotation original, int start, int end) { MarkerAnnotation out = null; try { out = Reflection.markerAnnotationConstructor.newInstance(ast); } catch (InstantiationException e) { throw Lombok.sneakyThrow(e); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } if (out != null) { SimpleName valName = ast.newSimpleName("val"); valName.setSourceRange(start, end - start + 1); if (original.type instanceof SingleTypeReference) { out.setTypeName(valName); setIndex(valName, 1); } else { SimpleName lombokName = ast.newSimpleName("lombok"); lombokName.setSourceRange(start, end - start + 1); setIndex(lombokName, 1); setIndex(valName, 2); QualifiedName fullName = ast.newQualifiedName(lombokName, valName); setIndex(fullName, 1); fullName.setSourceRange(start, end - start + 1); out.setTypeName(fullName); } out.setSourceRange(start, end - start + 1); } return out; }
/** * Builds a new {@link MethodInvocation} instance. * * @param expression the method invocation expression * @param methodName the name of the invoked method * @param arguments the arguments for the method invocation * @return a new method invocation */ public MethodInvocation invoke(String expression, String methodName, Expression... arguments) { final MethodInvocation mi = ast.newMethodInvocation(); mi.setExpression(ast.newSimpleName(expression)); mi.setName(ast.newSimpleName(methodName)); addAll(arguments(mi), arguments); return mi; }
public static void getInvalidQualificationProposals( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode node = problem.getCoveringNode(context.getASTRoot()); if (!(node instanceof Name)) { return; } Name name = (Name) node; IBinding binding = name.resolveBinding(); if (!(binding instanceof ITypeBinding)) { return; } ITypeBinding typeBinding = (ITypeBinding) binding; AST ast = node.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null); String label = CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description; Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal( label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME, image); proposals.add(proposal); }
@SuppressWarnings("unchecked") public Expression newArrayCreationFromDimensions(Type type, List<Expression> dimensions) { ArrayCreation ac = ast.newArrayCreation(); ac.dimensions().addAll(dimensions); ac.setType(ast.newArrayType(type)); return ac; }
private ASTRewrite doAddEnumConst(CompilationUnit astRoot) { SimpleName node = fOriginalNode; ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl == null) { astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null); newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey()); } if (newTypeDecl != null) { AST ast = newTypeDecl.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); EnumConstantDeclaration constDecl = ast.newEnumConstantDeclaration(); constDecl.setName(ast.newSimpleName(node.getIdentifier())); ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY); listRewriter.insertLast(constDecl, null); addLinkedPosition(rewrite.track(constDecl.getName()), false, KEY_NAME); return rewrite; } return null; }
/** * Inserts the provided {@code statement} after the the node this inserter was created for. Tries * to put the {@code statement} as close to the {@code marker} as possible. * * @param statement The statement to insert after the insertion node. */ void insertAfter(final Statement statement) { Validate.notNull(statement); Validate.validState( this.insertionList != null, "Insertion is only possible after the inserter has been set up."); Validate.validState( this.insertionList.isPresent(), "Insertion is only possible if setting up the inserter succeeded."); if (this.differentAfterList) { this.afterList.add(0, statement); } else if (this.breakDetector.containsControlFlowBreakingStatement(this.markedStatement)) { // we are trying to insert after a control flow breaking statement. That’s // dangerous, better surround with try…finally final AST factory = this.markedStatement.getAST(); final TryStatement tryStatement = factory.newTryStatement(); tryStatement.setFinally(factory.newBlock()); @SuppressWarnings("unchecked") final List<Statement> tryBodyStatements = tryStatement.getBody().statements(); @SuppressWarnings("unchecked") final List<Statement> finallyStatements = tryStatement.getFinally().statements(); final Statement copy = (Statement) ASTNode.copySubtree(factory, this.markedStatement); tryBodyStatements.add(copy); finallyStatements.add(statement); this.insertionList.get().set(this.markerIndex, tryStatement); this.markedStatement = tryStatement; this.differentAfterList = true; this.afterList = finallyStatements; } else { this.insertionList.get().add(this.markerIndex, statement); } }
/** * Updates a javadoc tag, by either adding a new one or removing an existing one * * @param body */ private void updateTag(BodyDeclaration body) { Javadoc docnode = body.getJavadoc(); AST ast = body.getAST(); if (docnode == null) { docnode = ast.newJavadoc(); rewrite.set(body, body.getJavadocProperty(), docnode, null); } ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY); if (remove) { List<TagElement> tags = (List<TagElement>) docnode.getStructuralProperty(Javadoc.TAGS_PROPERTY); if (tags != null) { TagElement tag = null; for (int i = 0; i < tags.size(); i++) { tag = tags.get(i); if (tagname.equals(tag.getTagName())) { lrewrite.remove(tag, null); } } } } else { TagElement newtag = ast.newTagElement(); newtag.setTagName(tagname); lrewrite.insertLast(newtag, null); } }
private void replaceExpressionsWithConstant() throws JavaModelException { ASTRewrite astRewrite = fCuRewrite.getASTRewrite(); AST ast = astRewrite.getAST(); IASTFragment[] fragmentsToReplace = getFragmentsToReplace(); for (int i = 0; i < fragmentsToReplace.length; i++) { IASTFragment fragment = fragmentsToReplace[i]; ASTNode node = fragment.getAssociatedNode(); boolean inTypeDeclarationAnnotation = isInTypeDeclarationAnnotation(node); if (inTypeDeclarationAnnotation && JdtFlags.VISIBILITY_STRING_PRIVATE == getVisibility()) continue; SimpleName ref = ast.newSimpleName(fConstantName); Name replacement = ref; boolean qualifyReference = qualifyReferencesWithDeclaringClassName(); if (!qualifyReference) { qualifyReference = inTypeDeclarationAnnotation; } if (qualifyReference) { replacement = ast.newQualifiedName(ast.newSimpleName(getContainingTypeBinding().getName()), ref); } TextEditGroup description = fCuRewrite.createGroupDescription( RefactoringCoreMessages.ExtractConstantRefactoring_replace); fragment.replace(astRewrite, replacement, description); if (fLinkedProposalModel != null) fLinkedProposalModel .getPositionGroup(KEY_NAME, true) .addPosition(astRewrite.track(ref), false); } }
/** * Builds a new {@link MethodInvocation} instance. * * @param <E> the arguments type * @param expression the method invocation expression * @param methodName the name of the invoked method * @param arguments the arguments for the method invocation * @return a new method invocation */ public <E extends Expression> MethodInvocation invoke( Expression expression, String methodName, List<E> arguments) { final MethodInvocation mi = ast.newMethodInvocation(); mi.setExpression(expression); mi.setName(ast.newSimpleName(methodName)); addAll(arguments, mi); return mi; }
private Type type(String typeName) { final String[] names = typeName.split("\\."); if (names.length == 1) { return ast.newSimpleType(ast.newSimpleName(names[0])); } else { throw new NotImplementedException(null); } }
@SuppressWarnings("unchecked") public MethodInvocation newCall(Expression obj, String funName, Expression... args) { MethodInvocation call = ast.newMethodInvocation(); call.setExpression(obj); call.setName(ast.newSimpleName(funName)); call.arguments().addAll(Arrays.asList(args)); return call; }
/** * Builds a new {@link ArrayCreation} instance. * * @param typeBinding the type binding of the instantiated type * @param arrayInitializers the expressions forming the array initializer * @return a new array creation instance */ public ArrayCreation newArray(ITypeBinding typeBinding, Expression arrayInitializers) { final ArrayInitializer ai = ast.newArrayInitializer(); expressions(ai).add(arrayInitializers); final ArrayCreation ac = ast.newArrayCreation(); ac.setType((ArrayType) toType(ast, typeBinding)); ac.setInitializer(ai); return ac; }
@Override public Expression build(List<CompilationUnit> out) { AST ast = this.getAST(); ParenthesizedExpression paren = ast.newParenthesizedExpression(); paren.setExpression(this.expr.translate(out)); return paren; }
@SuppressWarnings("unchecked") public ArrayCreation newArrayCreation(Type type, Collection<Expression> values) { ArrayCreation ac = ast.newArrayCreation(); ArrayInitializer initializer = ast.newArrayInitializer(); for (Expression expr : values) { initializer.expressions().add(expr); } ac.setInitializer(initializer); ac.setType(ast.newArrayType(type)); return ac; }
@Override protected Statement convert( CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException { ASTRewrite rewrite = cuRewrite.getASTRewrite(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); ForStatement forStatement = getForStatement(); IJavaProject javaProject = ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject(); String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject); String parameterName; if (fElementDeclaration != null) { parameterName = fElementDeclaration.getName().getIdentifier(); } else { parameterName = proposals[0]; } LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true); if (fElementDeclaration != null) pg.addProposal(parameterName, null, 10); for (int i = 0; i < proposals.length; i++) { pg.addProposal(proposals[i], null, 10); } AST ast = forStatement.getAST(); EnhancedForStatement result = ast.newEnhancedForStatement(); SingleVariableDeclaration parameterDeclaration = createParameterDeclaration( parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal); result.setParameter(parameterDeclaration); result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess)); convertBody( forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg); result.setBody(getBody(cuRewrite, group, positionGroups)); positionGroups.setEndPosition(rewrite.track(result)); return result; }
private Type evaluateVariableType( AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext) { if (fOriginalNode.getParent() instanceof MethodInvocation) { MethodInvocation parent = (MethodInvocation) fOriginalNode.getParent(); if (parent.getExpression() == fOriginalNode) { // _x_.foo() -> guess qualifier type by looking for a type with method 'foo' ITypeBinding[] bindings = ASTResolving.getQualifierGuess( fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext); if (bindings.length > 0) { for (int i = 0; i < bindings.length; i++) { addLinkedPositionProposal(KEY_TYPE, bindings[i]); } return imports.addImport(bindings[0], ast, importRewriteContext); } } } ITypeBinding binding = ASTResolving.guessBindingForReference(fOriginalNode); if (binding != null) { if (binding.isWildcardType()) { binding = ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast); if (binding == null) { // only null binding applies binding = ast.resolveWellKnownType("java.lang.Object"); // $NON-NLS-1$ } } if (isVariableAssigned()) { ITypeBinding[] typeProposals = ASTResolving.getRelaxingTypes(ast, binding); for (int i = 0; i < typeProposals.length; i++) { addLinkedPositionProposal(KEY_TYPE, typeProposals[i]); } } return imports.addImport(binding, ast, importRewriteContext); } // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode); if (type != null) { return type; } if (fVariableKind == CONST_FIELD) { return ast.newSimpleType(ast.newSimpleName("String")); // $NON-NLS-1$ } return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$ }
/** * Builds a new {@link CatchClause} instance. * * @param exceptionTypeName the exception type name * @param caughtExceptionName the local name for the caught exception * @param stmts the statements to add to the catch clause * @return a new catch clause */ public CatchClause catch0( String exceptionTypeName, String caughtExceptionName, Statement... stmts) { final CatchClause cc = ast.newCatchClause(); final SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setType(newSimpleType(exceptionTypeName)); svd.setName(ast.newSimpleName(caughtExceptionName)); cc.setException(svd); final Block block = ast.newBlock(); addAll(statements(block), stmts); cc.setBody(block); return cc; }
// Generate a statement with assignment // E.g. input: x.f(y) ==> x = x.f(y); public static ExpressionStatement genAssignmentStatement(Expression exp) { Assignment assignExp = AST.newAST(AST.JLS8).newAssignment(); // generate a new left hand side variable assignExp.setLeftHandSide( (Expression) ASTNode.copySubtree(assignExp.getAST(), genSimpleName(VariableGenerator.genVar()))); assignExp.setRightHandSide((Expression) ASTNode.copySubtree(assignExp.getAST(), exp)); assignExp.setOperator(Assignment.Operator.ASSIGN); AST newAst = AST.newAST(AST.JLS8); return newAst.newExpressionStatement((Expression) ASTNode.copySubtree(newAst, assignExp)); }
// Função auxiliar para copiar o tipo da variável // considerando que um tipo nao pode pertencer a outra AST private Type getType(ITypeBinding typeBinding, AST newAST) { if (typeBinding.isPrimitive()) { return newAST.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName())); } else if (typeBinding.isArray()) { return newAST.newArrayType( this.getType(typeBinding.getElementType(), newAST), typeBinding.getDimensions()); } else if (typeBinding.isParameterizedType()) { ParameterizedType pt = newAST.newParameterizedType(this.getType(typeBinding.getTypeDeclaration(), newAST)); for (ITypeBinding itb : typeBinding.getTypeArguments()) { pt.typeArguments().add(this.getType(itb, newAST)); } return pt; } else if (typeBinding.isWildcardType()) { WildcardType wt = newAST.newWildcardType(); wt.setBound( typeBinding.getBound() == null ? null : this.getType(typeBinding.getBound(), newAST), typeBinding.isUpperbound()); return wt; } else { try { return newAST.newSimpleType(newAST.newName(typeBinding.getQualifiedName())); } catch (Exception e) { return newAST.newSimpleType(newAST.newName(typeBinding.getName())); } } }
private static Expression createInfixInvocationFromPostPrefixExpression( InfixExpression.Operator operator, Expression getterExpression, AST ast, ITypeBinding variableType, boolean is50OrHigher) { InfixExpression infix = ast.newInfixExpression(); infix.setLeftOperand(getterExpression); infix.setOperator(operator); NumberLiteral number = ast.newNumberLiteral(); number.setToken("1"); // $NON-NLS-1$ infix.setRightOperand(number); ITypeBinding infixType = infix.resolveTypeBinding(); return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher); }
@Override public boolean visit(VariableDeclarationFragment node) { for (Map.Entry<String, Object> entry : replaceVariablesMap.entrySet()) { String key = entry.getKey(); if (variablesMap.containsKey(key) && variablesMap.get(key) == getLine(node)) { AST ast = rewrite.getAST(); VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(key)); fragment.setInitializer(createNewObject(replaceVariablesMap.get(key))); rewrite.replace(node, fragment, null); } } return true; }
public ITypeBinding resolveJavaType(String name) { ITypeBinding result = javaBindingMap.get(name); if (result == null) { result = ast.resolveWellKnownType(name); } return result; }
private void printAnnotationValue(AST ast, Object value) { if (value == null) { print("nil"); } else if (value instanceof IVariableBinding) { IVariableBinding var = (IVariableBinding) value; ITypeBinding declaringClass = var.getDeclaringClass(); printf("[%s %s]", NameTable.getFullName(declaringClass), var.getName()); } else if (value instanceof ITypeBinding) { ITypeBinding type = (ITypeBinding) value; printf("[[%s class] getClass]", NameTable.getFullName(type)); } else if (value instanceof String) { StringLiteral node = ast.newStringLiteral(); node.setLiteralValue((String) value); print(StatementGenerator.generateStringLiteral(node)); } else if (value instanceof Number || value instanceof Character || value instanceof Boolean) { print(value.toString()); } else if (value.getClass().isArray()) { print("[IOSObjectArray arrayWithObjects:(id[]) { "); Object[] array = (Object[]) value; for (int i = 0; i < array.length; i++) { if (i > 0) { print(", "); } printAnnotationValue(ast, array[i]); } printf(" } count:%d type:[[NSObject class] getClass]]", array.length); } else { assert false : "unknown annotation value type"; } }
/** * Builds a new {@link IfStatement} instance. * * @param condition the if condition * @param thenStatement the statement of the then clause * @param elseStatement the statement of the else clause * @return a new if statement */ public IfStatement if0(Expression condition, Statement thenStatement, Statement elseStatement) { final IfStatement is = ast.newIfStatement(); is.setExpression(condition); is.setThenStatement(thenStatement); is.setElseStatement(elseStatement); return is; }
@SuppressWarnings("unchecked") public TryStatement newTryCatch(Block tryBlock, CatchClause... clauses) { TryStatement tryStmt = ast.newTryStatement(); tryStmt.setBody(tryBlock); tryStmt.catchClauses().addAll(Arrays.asList(clauses)); return tryStmt; }
/* * Evaluates possible return expressions. The favourite expression is returned. */ private Expression evaluateReturnExpressions( AST ast, ITypeBinding returnBinding, int returnOffset) { CompilationUnit root = (CompilationUnit) fMethodDecl.getRoot(); Expression result = null; if (returnBinding != null) { ScopeAnalyzer analyzer = new ScopeAnalyzer(root); IBinding[] bindings = analyzer.getDeclarationsInScope( returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); for (int i = 0; i < bindings.length; i++) { IVariableBinding curr = (IVariableBinding) bindings[i]; ITypeBinding type = curr.getType(); if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr)) { if (result == null) { result = ast.newSimpleName(curr.getName()); } addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null); } } } Expression defaultExpression = ASTNodeFactory.newDefaultExpression( ast, fMethodDecl.getReturnType2(), fMethodDecl.getExtraDimensions()); addLinkedPositionProposal(RETURN_EXPRESSION_KEY, ASTNodes.asString(defaultExpression), null); if (result == null) { return defaultExpression; } return result; }
/** * Converts an assignment, postfix expression or prefix expression into an assignable equivalent * expression using the getter. * * @param node the assignment/prefix/postfix node * @param astRewrite the astRewrite to use * @param getterExpression the expression to insert for read accesses or <code>null</code> if such * an expression does not exist * @param variableType the type of the variable that the result will be assigned to * @param is50OrHigher <code>true</code> if a 5.0 or higher environment can be used * @return an expression that can be assigned to the type variableType with node being replaced by * a equivalent expression using the getter */ public static Expression getAssignedValue( ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType, boolean is50OrHigher) { InfixExpression.Operator op = null; AST ast = astRewrite.getAST(); if (isNotInBlock(node)) return null; if (node.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment = ((Assignment) node); Expression rightHandSide = assignment.getRightHandSide(); Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide); if (assignment.getOperator() == Operator.ASSIGN) { ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding(); copiedRightOp = createNarrowCastIfNessecary( copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher); return copiedRightOp; } if (getterExpression != null) { InfixExpression infix = ast.newInfixExpression(); infix.setLeftOperand(getterExpression); infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator())); infix.setRightOperand(copiedRightOp); ITypeBinding infixType = infix.resolveTypeBinding(); return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher); } } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) { PostfixExpression po = (PostfixExpression) node; if (po.getOperator() == PostfixExpression.Operator.INCREMENT) op = InfixExpression.Operator.PLUS; if (po.getOperator() == PostfixExpression.Operator.DECREMENT) op = InfixExpression.Operator.MINUS; } else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) { PrefixExpression pe = (PrefixExpression) node; if (pe.getOperator() == PrefixExpression.Operator.INCREMENT) op = InfixExpression.Operator.PLUS; if (pe.getOperator() == PrefixExpression.Operator.DECREMENT) op = InfixExpression.Operator.MINUS; } if (op != null && getterExpression != null) { return createInfixInvocationFromPostPrefixExpression( op, getterExpression, ast, variableType, is50OrHigher); } return null; }
/** {@inheritDoc} */ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); Annotation newAnnotation = ast.newMarkerAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(fAnnotation)); TextEditGroup group = createTextEditGroup( Messages.format( FixMessages.Java50Fix_AddMissingAnnotation_description, BasicElementLabels.getJavaElementName(fAnnotation)), cuRewrite); listRewrite.insertFirst(newAnnotation, group); }
public Expression newInfixOperatorExpr( String operator, Expression leftOperand, Expression rightOperand) { InfixExpression expression = ast.newInfixExpression(); expression.setOperator(Operator.toOperator(operator)); expression.setLeftOperand(leftOperand); expression.setRightOperand(rightOperand); return expression; }