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

The following examples show how to use org.eclipse.jdt.core.dom.AST. 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 Project: eclipse.jdt.ls   Author: eclipse   File: JavadocTagsSubProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> 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;
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME);

	proposals.add(proposal);
}
 
Example #2
Source Project: spotbugs   Author: spotbugs   File: CreateAndOddnessCheckResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates the new <CODE>InfixExpression</CODE> <CODE>(x &amp; 1) == 1</CODE>.
 */
@Override
protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite, Expression numberExpression) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(numberExpression);

    final AST ast = rewrite.getAST();
    InfixExpression andOddnessCheck = ast.newInfixExpression();
    ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
    InfixExpression andExpression = ast.newInfixExpression();

    andExpression.setLeftOperand((Expression) rewrite.createMoveTarget(numberExpression));
    andExpression.setOperator(AND);
    andExpression.setRightOperand(ast.newNumberLiteral("1"));
    parenthesizedExpression.setExpression(andExpression);
    andOddnessCheck.setLeftOperand(parenthesizedExpression);
    andOddnessCheck.setOperator(EQUALS);
    andOddnessCheck.setRightOperand(ast.newNumberLiteral("1"));

    return andOddnessCheck;

}
 
Example #3
Source Project: JDeodorant   Author: tsantalis   File: ReplaceTypeCodeWithStateStrategy.java    License: MIT License 6 votes vote down vote up
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #4
Source Project: spotbugs   Author: spotbugs   File: CreateDoPrivilegedBlockResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void updateImportDeclarations(ASTRewrite rewrite, CompilationUnit compilationUnit) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(compilationUnit);

    if (isUpdateImports()) {
        final AST ast = rewrite.getAST();
        SortedSet<ImportDeclaration> imports = new TreeSet<>(importComparator);
        imports.add(createImportDeclaration(ast, PrivilegedAction.class));
        if (!isStaticImport()) {
            imports.add(createImportDeclaration(ast, AccessController.class));
        } else {
            imports.add(createImportDeclaration(ast, AccessController.class, DO_PRIVILEGED_METHOD_NAME));
        }
        addImports(rewrite, compilationUnit, imports);
    }
}
 
Example #5
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: TypeParametersFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	ImportRewrite importRewrite= cuRewrite.getImportRewrite();
	AST ast= cuRewrite.getRoot().getAST();

	for (int i= 0; i < fCreatedTypes.length; i++) {
		ParameterizedType createdType= fCreatedTypes[i];

		ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments();
		ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite);

		ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
		for (int j= 0; j < typeArguments.length; j++) {
			ITypeBinding typeArgument= typeArguments[j];
			Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext);
			argumentsRewrite.insertLast(argumentNode, group);
		}
	}
}
 
Example #6
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: AbstractUpdateSignatureProposal.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a sync/async method declaration based on the associated
 * async/sync method signature.
 */
private MethodDeclaration computeMethodSignature(AST ast, RpcPair rpcPair,
    MethodDeclaration dstMethod) {

  MethodDeclaration method = ast.newMethodDeclaration();

  // New method has same name as original
  String methodName = rpcPair.srcMethod.getName().getIdentifier();
  method.setName(ast.newSimpleName(methodName));

  // Update the parameters
  @SuppressWarnings("unchecked")
  List<SingleVariableDeclaration> params = method.parameters();
  params.addAll(computeParams(ast, rpcPair.srcMethod, dstMethod,
      getImportRewrite()));

  // Update the return type
  method.setReturnType2(computeReturnType(ast, rpcPair.srcMethod, dstMethod,
      getImportRewrite()));

  return method;
}
 
Example #7
@Override
protected ASTRewrite getRewrite() {
	AST ast= fCallerNode.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ChildListPropertyDescriptor property= getProperty();

	for (int i= 0; i < fInsertIndexes.length; i++) {
		int idx= fInsertIndexes[i];
		String key= "newarg_" + i; //$NON-NLS-1$
		Expression newArg= evaluateArgumentExpressions(ast, fParamTypes[idx], key);
		ListRewrite listRewriter= rewrite.getListRewrite(fCallerNode, property);
		listRewriter.insertAt(newArg, idx, null);

		addLinkedPosition(rewrite.track(newArg), i == 0, key);
	}
	return rewrite;
}
 
Example #8
Source Project: eclipse.jdt.ls   Author: eclipse   File: DimensionRewrite.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code>
 * and adds <code>extraDimensions</code> to it.
 *
 * @param type the type to copy
 * @param extraDimensions the dimensions to add
 * @param rewrite the ASTRewrite with which to create new nodes
 * @return the copy target with added dimensions
 */
public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	if (extraDimensions.isEmpty()) {
		return (Type) rewrite.createCopyTarget(type);
	}

	ArrayType result;
	if (type instanceof ArrayType) {
		ArrayType arrayType= (ArrayType) type;
		Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType());
		result= ast.newArrayType(varElementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
		result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite));
	} else {
		Type elementType= (Type) rewrite.createCopyTarget(type);
		result= ast.newArrayType(elementType, 0);
		result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
	}
	return result;
}
 
Example #9
Source Project: SparkBuilderGenerator   Author: helospark   File: RegularBuilderCompilationUnitGenerator.java    License: MIT License 6 votes vote down vote up
public void generateBuilder(CompilationUnitModificationDomain compilationUnitModificationDomain, RegularBuilderUserPreference preference) {
    // TODO: replace parameters, where these go separately with compilation modification domain
    AST ast = compilationUnitModificationDomain.getAst();
    ListRewrite listRewrite = compilationUnitModificationDomain.getListRewrite();
    TypeDeclaration originalType = compilationUnitModificationDomain.getOriginalType();

    builderRemover.removeExistingBuilderWhenNeeded(compilationUnitModificationDomain);

    TypeDeclaration builderType = regularBuilderClassCreator.createBuilderClass(ast, originalType, preference);
    defaultConstructorAppender.addDefaultConstructorIfNeeded(compilationUnitModificationDomain, preference.getBuilderFields());
    privateConstructorPopulator.addPrivateConstructorToCompilationUnit(ast, originalType, builderType, listRewrite, preference.getBuilderFields());
    builderMethodPopulator.addBuilderMethodToCompilationUnit(ast, listRewrite, originalType, builderType, preference);
    instanceCopyBuilderMethodPopulator.addInstanceCopyBuilderMethodToCompilationUnitIfNeeded(compilationUnitModificationDomain, builderType, preference);

    listRewrite.insertLast(builderType, null);

    globalBuilderPostProcessor.postProcessBuilder(compilationUnitModificationDomain, builderType);

    importPopulator.populateImports(compilationUnitModificationDomain);
}
 
Example #10
private SimpleName getNewName(ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	String name;
	if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
		name= ((SimpleName) fInvocationNode).getIdentifier();
		if (ast == fInvocationNode.getAST()) {
			addLinkedPosition(rewrite.track(fInvocationNode), true, KEY_NAME);
		}
	} else {
		name= "value"; //$NON-NLS-1$
	}


	SimpleName newNameNode= ast.newSimpleName(name);
	addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);
	return newNameNode;
}
 
Example #11
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
 	Assert.isTrue(! isDeclaredInAnonymousClass());
 	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent();
 	final MethodDeclaration[] constructors= getAllConstructors(declaration);
 	if (constructors.length == 0) {
 		AST ast= rewrite.getAST();
 		MethodDeclaration newConstructor= ast.newMethodDeclaration();
 		newConstructor.setConstructor(true);
 		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
 		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
 		newConstructor.setJavadoc(getNewConstructorComment(rewrite));
 		newConstructor.setBody(ast.newBlock());

 		addFieldInitializationToConstructor(rewrite, newConstructor);

 		int insertionIndex= computeInsertIndexForNewConstructor(declaration);
rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
 	} else {
 		for (int index= 0; index < constructors.length; index++) {
             if (shouldInsertTempInitialization(constructors[index]))
                 addFieldInitializationToConstructor(rewrite, constructors[index]);
         }
 	}
 }
 
Example #12
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: QuickAssistProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
	if (tryStatement == null || tryStatement.getFinally() != null) {
		return false;
	}
	Statement statement= ASTResolving.findParentStatement(node);
	if (tryStatement != statement && tryStatement.getBody() != statement) {
		return false; // an node inside a catch or finally block
	}

	if (resultingCollections == null) {
		return true;
	}

	AST ast= tryStatement.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block finallyBody= ast.newBlock();

	rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);

	String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example #13
Source Project: sahagin-java   Author: SahaginOrg   File: SrcTreeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static void parseAST(String[] srcFiles, Charset srcCharset,
        String[] classPathEntries, FileASTRequestor requestor) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    Map<String, String> options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(classPathEntries, null, null, true);
    String[] srcEncodings = new String[srcFiles.length];
    for (int i = 0; i < srcEncodings.length; i++) {
        srcEncodings[i] = srcCharset.name();
    }
    parser.createASTs(
            srcFiles, srcEncodings, new String[]{}, requestor, null);
}
 
Example #14
@Override
protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);

	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0);
	ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT);
	IVariableBinding varDeclFragBinding= null;
	if (varDeclFrag != null)
		varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding();
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		// Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised.
		if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) {
			if (result == null) {
				result= ast.newSimpleName(curr.getName());
			}
			addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null);
		}
	}
	return result;
}
 
Example #15
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ReturnTypeSubProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public ITypeBinding getTypeBinding(AST ast) {
	boolean couldBeObject= false;
	for (int i= 0; i < fResult.size(); i++) {
		ReturnStatement node= fResult.get(i);
		Expression expr= node.getExpression();
		if (expr != null) {
			ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
			if (binding != null) {
				return binding;
			} else {
				couldBeObject= true;
			}
		} else {
			return ast.resolveWellKnownType("void"); //$NON-NLS-1$
		}
	}
	if (couldBeObject) {
		return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
	}
	return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
 
Example #16
private static Statement createAssignmentStatement(ASTRewrite rewrite, Assignment.Operator assignmentOperator, Expression origAssignee, Expression origAssigned) {
	AST ast= rewrite.getAST();
	Assignment elseAssignment= ast.newAssignment();
	elseAssignment.setOperator(assignmentOperator);
	elseAssignment.setLeftHandSide((Expression) rewrite.createCopyTarget(origAssignee));
	elseAssignment.setRightHandSide((Expression) rewrite.createCopyTarget(origAssigned));
	ExpressionStatement statement= ast.newExpressionStatement(elseAssignment);
	return statement;
}
 
Example #17
Source Project: gwt-eclipse-plugin   Author: gwt-plugins   File: JavaASTUtilsTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setSource(testClass.getCompilationUnit());
  ast = parser.createAST(null);
}
 
Example #18
/**
 * Creates the necessary change to updated a comment reference represented
 * by a search match.
 *
 * @param rewrite
 *            the current compilation unit rewrite
 * @param declaration
 *            the source method declaration
 * @param match
 *            the search match representing the method reference
 * @param status
 *            the refactoring status
 */
protected void createMethodJavadocReference(CompilationUnitRewrite rewrite, MethodDeclaration declaration, SearchMatch match, RefactoringStatus status) {
	Assert.isNotNull(rewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(match);
	Assert.isNotNull(status);
	final ASTNode node= ASTNodeSearchUtil.findNode(match, rewrite.getRoot());
	if (node instanceof MethodRef) {
		final AST ast= node.getAST();
		final MethodRef successor= ast.newMethodRef();

		rewrite.getASTRewrite().replace(node, successor, null);
	}
}
 
Example #19
Source Project: eclipse.jdt.ls   Author: eclipse   File: SelfEncapsulateFieldRefactoring.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block = ast.newBlock();
	result.setBody(block);

	String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(getterNode);
	} else {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example #20
private static Statement copyStatementExceptBreak(AST ast, ASTRewrite rewrite, Statement source) {
	if (source instanceof Block) {
		Block block= (Block) source;
		Block newBlock= ast.newBlock();
		for (Iterator<Statement> iter= block.statements().iterator(); iter.hasNext();) {
			Statement statement= iter.next();
			if (statement instanceof BreakStatement) {
				continue;
			}
			newBlock.statements().add(copyStatementExceptBreak(ast, rewrite, statement));
		}
		return newBlock;
	}
	return (Statement) rewrite.createMoveTarget(source);
}
 
Example #21
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: JavadocUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static TagElement createParamTag(String parameterName, AST ast, IJavaProject javaProject) {
	TagElement paramNode= ast.newTagElement();
	paramNode.setTagName(TagElement.TAG_PARAM);

	SimpleName simpleName= ast.newSimpleName(parameterName);
	paramNode.fragments().add(simpleName);

	TextElement textElement= ast.newTextElement();
	String text= StubUtility.getTodoTaskTag(javaProject);
	if (text != null)
		textElement.setText(text); //TODO: use template with {@todo} ...
	paramNode.fragments().add(textElement);

	return paramNode;
}
 
Example #22
Source Project: eclipse.jdt.ls   Author: eclipse   File: CastCorrectionProposal.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST);
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	return newCastType;
}
 
Example #23
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExtractConstantRefactoring.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Type getConstantType() throws JavaModelException {
	if (fConstantTypeCache == null) {
		IExpressionFragment fragment = getSelectedExpression();
		ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
		AST ast = fCuRewrite.getAST();
		typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
		ImportRewrite importRewrite = fCuRewrite.getImportRewrite();
		ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
		fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context, TypeLocation.FIELD);
	}
	return fConstantTypeCache;
}
 
Example #24
Source Project: SimFix   Author: xgdsmileboy   File: TryPurifyByException.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Set<String> purify(){
	if(_method != null && _method.getBody() != null){
		AST ast = AST.newAST(AST.JLS8);
		_backupBody = (Block) ASTNode.copySubtree(ast, _method.getBody());
		splitMethodCalls();
	}
	return _purifiedTestCases;
}
 
Example #25
Source Project: SparkBuilderGenerator   Author: helospark   File: StagedBuilderInterfaceCreatorFragment.java    License: MIT License 5 votes vote down vote up
private void addBuildMethod(CompilationUnitModificationDomain modificationDomain, TypeDeclaration addedInterface) {
    AST ast = modificationDomain.getAst();
    TypeDeclaration originalType = modificationDomain.getOriginalType();
    MethodDeclaration buildMethod = buildMethodDeclarationCreatorFragment.createMethod(ast,
            originalType);
    javadocAdder.addJavadocForBuildMethod(ast, buildMethod);
    addedInterface.bodyDeclarations().add(buildMethod);
}
 
Example #26
/**
 * Creates and adds the necessary argument declarations to the given factory method.<br>
 * An argument is needed for each original constructor argument for which the
 * evaluation of the actual arguments across all calls was not able to be
 * pushed inside the factory method (e.g. arguments with side-effects, references
 * to fields if the factory method is to be static or reside in a factory class,
 * or arguments that varied across the set of constructor calls).<br>
 * <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
 * @param ast utility object used to create AST nodes
 * @param newMethod the <code>MethodDeclaration</code> for the factory method
 */
private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) {
	List<SingleVariableDeclaration> argDecls= newMethod.parameters();

	for(int i=0; i < fArgTypes.length; i++) {
		SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
		Type argType;

		if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
			// The trailing varargs arg has an extra array dimension, compared to
			// what we need to pass to setType()...
			argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
					fArgTypes[i].getDimensions()-1, ast);
			argDecl.setVarargs(true);
		} else
			argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);

		argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
		argDecl.setType(argType);
		argDecls.add(argDecl);
	}

	ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes();
	List<Type> exceptions= newMethod.thrownExceptionTypes();

	for(int i=0; i < ctorExcepts.length; i++) {
		exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast));
	}

       copyTypeParameters(ast, newMethod);
}
 
Example #27
@Override
public final boolean visit(final SuperFieldAccess node) {
	if (!fAnonymousClassDeclaration && !fTypeDeclarationStatement) {
		final AST ast= node.getAST();
		final FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(node.getName().getIdentifier()));
		fRewrite.replace(node, access, null);
		if (!fSourceRewriter.getCu().equals(fTargetRewriter.getCu()))
			fSourceRewriter.getImportRemover().registerRemovedNode(node);
		return true;
	}
	return false;
}
 
Example #28
Source Project: SparkBuilderGenerator   Author: helospark   File: JavadocAdder.java    License: MIT License 5 votes vote down vote up
public void addJavadocForWithBuilderMethod(AST ast, String typeName, String parameterName, MethodDeclaration builderMethod) {
    if (preferencesManager.getPreferenceValue(PluginPreferenceList.GENERATE_JAVADOC_ON_BUILDER_METHOD)) {
        Javadoc javadoc = javadocGenerator.generateJavadoc(ast,
                String.format(Locale.ENGLISH, "Creates builder to build {@link %s} and setting %s parameter.", typeName, parameterName),
                Collections.singletonMap(RETURN_JAVADOC_TAG_NAME, "created builder"));
        builderMethod.setJavadoc(javadoc);
    }
}
 
Example #29
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);
	}
}
 
Example #30
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: QuickAssistProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) {
	ITypeBinding binding= type2.resolveBinding();
	if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) {
		Type newType= (Type) ASTNode.copySubtree(ast, type2);

		ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
		listRewriter.insertLast(newType, null);
	}
}