Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a2e75b6784fc44393ba9b91aebf542090975dbbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/*******************************************************************************
 * Copyright (c) 2010, 2016 Mateusz Matela and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Mateusz Matela <mateusz.matela@gmail.com> - [code manipulation] [dcr] toString() builder wizard - https://bugs.eclipse.org/bugs/show_bug.cgi?id=26070
 *     Mateusz Matela <mateusz.matela@gmail.com> - [toString] finish toString() builder wizard - https://bugs.eclipse.org/bugs/show_bug.cgi?id=267710
 *******************************************************************************/
package org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration;

import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;

import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;

import org.eclipse.ltk.core.refactoring.RefactoringStatus;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;

import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationMessages;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil;


/**
 * <p>
 * A workspace runnable to add implementation for <code>{@link java.lang.Object#toString()}</code>
 * </p>
 * 
 * @since 3.5
 */
public class GenerateToStringOperation implements IWorkspaceRunnable {

	/** The insertion point, or <code>null</code> */
	private IJavaElement fInsert;

	private CompilationUnitRewrite fRewrite;

	private ToStringGenerationContext fContext;

	private AbstractToStringGenerator fGenerator;

	private CompilationUnit fUnit;

	private GenerateToStringOperation(IJavaElement insert, ToStringGenerationContext context, AbstractToStringGenerator generator, CompilationUnit unit, CompilationUnitRewrite rewrite) {
		fInsert= insert;
		fContext= context;
		fRewrite= rewrite;
		fUnit= unit;
		fGenerator= generator;
	}

	@Override
	public void run(IProgressMonitor monitor) throws CoreException {
		if (monitor == null)
			monitor= new NullProgressMonitor();
		try {
			monitor.beginTask("", 1); //$NON-NLS-1$
			monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);


			AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
			ListRewrite rewriter= fRewrite.getASTRewrite().getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
			if (fContext.getTypeBinding() != null && rewriter != null) {

				MethodDeclaration toStringMethod= fGenerator.generateToStringMethod();

				List<BodyDeclaration> list= declaration.bodyDeclarations();
				BodyDeclaration replace= findMethodToReplace(list, toStringMethod);
				if (replace == null || ((Boolean)toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY)).booleanValue())
					insertMethod(toStringMethod, rewriter, replace);

				List<MethodDeclaration> helperMethods= fGenerator.generateHelperMethods();
				for (Iterator<MethodDeclaration> iterator= helperMethods.iterator(); iterator.hasNext();) {
					MethodDeclaration method= iterator.next();
					replace= findMethodToReplace(list, method);
					if (replace == null || ((Boolean)method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY)).booleanValue()) {
						insertMethod(method, rewriter, replace);
					}
				}

				JavaElementUtil.applyEdit((ICompilationUnit)fUnit.getJavaElement(), fRewrite.createChange(true).getEdit(), false, monitor);
			}

		} finally {
			monitor.done();
		}
	}

	/**
	 * @return RefactoringStatus with eventual errors and warnings
	 */
	public RefactoringStatus checkConditions() {
		return fGenerator.checkConditions();
	}



	protected void insertMethod(MethodDeclaration method, ListRewrite rewriter, BodyDeclaration replace) throws JavaModelException {
		if (replace != null) {
			rewriter.replace(replace, method, null);
		} else {
			ASTNode insertion= StubUtility2.getNodeToInsertBefore(rewriter, fInsert);
			if (insertion != null)
				rewriter.insertBefore(method, insertion, null);
			else
				rewriter.insertLast(method, null);
		}
	}

	/**
	 * Determines if given method exists in a given list
	 * 
	 * @param list list of method to search through
	 * @param method method to find
	 * @return declaration of method from the list that has the same name and parameter types, or
	 *         null if not found
	 */
	protected BodyDeclaration findMethodToReplace(final List<BodyDeclaration> list, MethodDeclaration method) {
		for (final Iterator<BodyDeclaration> iterator= list.iterator(); iterator.hasNext();) {
			final BodyDeclaration bodyDecl= iterator.next();
			if (bodyDecl instanceof MethodDeclaration) {
				final MethodDeclaration method2= (MethodDeclaration)bodyDecl;
				if (method2.getName().getIdentifier().equals(method.getName().getIdentifier()) && method2.parameters().size() == method.parameters().size()) {
					Iterator<SingleVariableDeclaration> iterator1= method.parameters().iterator();
					Iterator<SingleVariableDeclaration> iterator2= method2.parameters().iterator();
					boolean ok= true;
					while (iterator1.hasNext()) {
						if (!iterator1.next().getType().subtreeMatch(new ASTMatcher(), iterator2.next().getType())) {
							ok= false;
							break;
						}
					}
					if (ok)
						return method2;
				}
			}
		}
		return null;
	}

	public ISchedulingRule getSchedulingRule() {
		return ResourcesPlugin.getWorkspace().getRoot();
	}

	public static final int STRING_CONCATENATION= 0;

	public static final int STRING_BUILDER= 1;

	public static final int STRING_BUILDER_CHAINED= 2;

	public static final int STRING_FORMAT= 3;

	public static final int CUSTOM_BUILDER= 4;

	private final static String[] hardcoded_styles= {
			CodeGenerationMessages.GenerateToStringOperation_stringConcatenation_style_name,
			CodeGenerationMessages.GenerateToStringOperation_stringBuilder_style_name,
			CodeGenerationMessages.GenerateToStringOperation_StringBuilder_chained_style_name,
			CodeGenerationMessages.GenerateToStringOperation_string_format_style_name,
			CodeGenerationMessages.GenerateToStringOperation_customStringBuilder_style_name
			};

	/**
	 * @return Array containing names of implemented code styles
	 */
	public static String[] getStyleNames() {
		return hardcoded_styles;
	}

	/**
	 * 
	 * @param toStringStyle id number of the code style (its position in the array returned by
	 *            {@link #getStyleNames()}
	 * @return a toString() generator implementing given code style
	 */
	private static AbstractToStringGenerator createToStringGenerator(int toStringStyle) {
		switch (toStringStyle) {
			case STRING_CONCATENATION:
				return new StringConcatenationGenerator();
			case STRING_BUILDER:
				return new StringBuilderGenerator();
			case STRING_BUILDER_CHAINED:
				return new StringBuilderChainGenerator();
			case STRING_FORMAT:
				return new StringFormatGenerator();
			case CUSTOM_BUILDER:
				return new CustomBuilderGenerator();
			default:
				throw new IllegalArgumentException("Undefined toString() code style: " + toStringStyle); //$NON-NLS-1$
		}
	}

	/**
	 * @param toStringStyle id number of the style (its position in the array returned by
	 *            {@link #getStyleNames()}
	 * @return a template parser that should be used with given code style
	 */
	public static ToStringTemplateParser createTemplateParser(int toStringStyle) {
		return new ToStringTemplateParser();
	}

	/**
	 * Creates new <code>GenerateToStringOperation</code>, using <code>settings.toStringStyle</code>
	 * field to choose the right subclass.
	 * 
	 * @param typeBinding binding for the type for which the toString() method will be created
	 * @param selectedBindings bindings for the typetype's members to be used in created method
	 * @param unit a compilation unit containing the type
	 * @param elementPosition at this position in the compilation unit created method will be added
	 * @param settings the settings for toString() generator
	 * @return a ready to use <code>GenerateToStringOperation</code> object
	 */
	public static GenerateToStringOperation createOperation(ITypeBinding typeBinding, Object[] selectedBindings, CompilationUnit unit, IJavaElement elementPosition,
			ToStringGenerationSettings settings) {
		AbstractToStringGenerator generator= createToStringGenerator(settings.toStringStyle);
		ToStringTemplateParser parser= createTemplateParser(settings.toStringStyle);
		parser.parseTemplate(settings.stringFormatTemplate);
		CompilationUnitRewrite rewrite= new CompilationUnitRewrite((ICompilationUnit)unit.getTypeRoot(), unit);
		ToStringGenerationContext context= new ToStringGenerationContext(parser, selectedBindings, settings, typeBinding, rewrite);
		generator.setContext(context);
		return new GenerateToStringOperation(elementPosition, context, generator, unit, rewrite);
	}


}

Back to the top