Skip to main content
summaryrefslogtreecommitdiffstats
blob: 650314bb65ca6e803654fc9299e4a8f2aa29368a (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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jdt.internal.corext.refactoring.structure.constraints;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.text.edits.TextEditGroup;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;

import org.eclipse.ltk.core.refactoring.IInitializableRefactoringComponent;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;

import org.eclipse.jdt.core.BindingKey;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.WorkingCopyOwner;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTRequestor;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.VariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchPattern;

import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringScopeFactory;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine2;
import org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.tagging.ICommentProvider;
import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType;
import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.SearchUtils;

import org.eclipse.jdt.internal.ui.JavaPlugin;

/**
 * Partial implementation of a refactoring processor solving supertype constraint models.
 * 
 * @since 3.1
 */
public abstract class SuperTypeRefactoringProcessor extends RefactoringProcessor implements IInitializableRefactoringComponent, ICommentProvider {

	protected static final String ATTRIBUTE_INSTANCEOF= "instanceof"; //$NON-NLS-1$

	/** Number of compilation units to parse at once */
	private static final int SIZE_BATCH= 500;

	/**
	 * Returns a new ast node corresponding to the given type.
	 * 
	 * @param rewrite the compilation unit rewrite to use
	 * @param type the specified type
	 * @return A corresponding ast node
	 */
	protected static ASTNode createCorrespondingNode(final CompilationUnitRewrite rewrite, final TType type) {
		return rewrite.getImportRewrite().addImportFromSignature(new BindingKey(type.getBindingKey()).toSignature(), rewrite.getAST());
	}

	/** Should type occurrences on instanceof's also be rewritten? */
	protected boolean fInstanceOf= false;

	/** The obsolete casts (element type: <code>&ltICompilationUnit, Collection&ltCastVariable2&gt&gt</code>) */
	protected Map fObsoleteCasts= null;

	/** The comment */
	protected String fComment;

	/** The working copy owner */
	protected final WorkingCopyOwner fOwner= new WorkingCopyOwner() {
	};

	/** The type occurrences (element type: <code>&ltICompilationUnit, Collection&ltIDeclaredConstraintVariable&gt&gt</code>) */
	protected Map fTypeOccurrences= null;

	/**
	 * Creates the super type constraint solver to solve the model.
	 * 
	 * @param model the model to create a solver for
	 * @return The created super type constraint solver
	 */
	protected abstract SuperTypeConstraintsSolver createContraintSolver(SuperTypeConstraintsModel model);

	/**
	 * Returns the field which corresponds to the specified variable declaration fragment
	 * 
	 * @param fragment the variable declaration fragment
	 * @return the corresponding field
	 * @throws JavaModelException if an error occurs
	 */
	protected final IField getCorrespondingField(final VariableDeclarationFragment fragment) throws JavaModelException {
		final IBinding binding= fragment.getName().resolveBinding();
		if (binding instanceof IVariableBinding) {
			final IVariableBinding variable= (IVariableBinding) binding;
			if (variable.isField()) {
				final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(fragment);
				final IJavaElement element= unit.getElementAt(fragment.getStartPosition());
				if (element instanceof IField)
					return (IField) element;
			}
		}
		return null;
	}

	/**
	 * Computes the compilation units of fields referencing the specified type occurrences.
	 * 
	 * @param units the compilation unit map (element type: <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
	 * @param nodes the ast nodes representing the type occurrences
	 * @throws JavaModelException if an error occurs
	 */
	protected final void getFieldReferencingCompilationUnits(final Map units, final ASTNode[] nodes) throws JavaModelException {
		ASTNode node= null;
		IField field= null;
		IJavaProject project= null;
		for (int index= 0; index < nodes.length; index++) {
			node= nodes[index];
			project= RefactoringASTParser.getCompilationUnit(node).getJavaProject();
			if (project != null) {
				final List fields= getReferencingFields(node, project);
				for (int offset= 0; offset < fields.size(); offset++) {
					field= (IField) fields.get(offset);
					Set set= (Set) units.get(project);
					if (set == null) {
						set= new HashSet();
						units.put(project, set);
					}
					final ICompilationUnit unit= field.getCompilationUnit();
					if (unit != null)
						set.add(unit);
				}
			}
		}
	}

	/**
	 * Computes the compilation units of methods referencing the specified type occurrences.
	 * 
	 * @param units the compilation unit map (element type: <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
	 * @param nodes the ast nodes representing the type occurrences
	 * @throws JavaModelException if an error occurs
	 */
	protected final void getMethodReferencingCompilationUnits(final Map units, final ASTNode[] nodes) throws JavaModelException {
		ASTNode node= null;
		IMethod method= null;
		IJavaProject project= null;
		for (int index= 0; index < nodes.length; index++) {
			node= nodes[index];
			project= RefactoringASTParser.getCompilationUnit(node).getJavaProject();
			if (project != null) {
				method= getReferencingMethod(node);
				if (method != null) {
					Set set= (Set) units.get(project);
					if (set == null) {
						set= new HashSet();
						units.put(project, set);
					}
					final ICompilationUnit unit= method.getCompilationUnit();
					if (unit != null)
						set.add(unit);
				}
			}
		}
	}

	/**
	 * Computes the compilation units referencing the subtype to replace.
	 * 
	 * @param type the subtype
	 * @param monitor the progress monitor to use
	 * @param status the refactoring status
	 * @return the referenced compilation units (element type: <code>&ltIJavaProject, Collection&ltSearchResultGroup&gt&gt</code>)
	 * @throws JavaModelException if an error occurs
	 */
	protected final Map getReferencingCompilationUnits(final IType type, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
		try {
			monitor.beginTask("", 1); //$NON-NLS-1$
			monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
			final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2();
			engine.setOwner(fOwner);
			engine.setFiltering(true, true);
			engine.setStatus(status);
			engine.setScope(RefactoringScopeFactory.create(type));
			engine.setPattern(SearchPattern.createPattern(type, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE));
			engine.searchPattern(new SubProgressMonitor(monitor, 1));
			return engine.getAffectedProjects();
		} finally {
			monitor.done();
		}
	}

	/**
	 * Returns the fields which reference the specified ast node.
	 * 
	 * @param node the ast node
	 * @param project the java project
	 * @return the referencing fields
	 * @throws JavaModelException if an error occurs
	 */
	protected final List getReferencingFields(final ASTNode node, final IJavaProject project) throws JavaModelException {
		List result= Collections.EMPTY_LIST;
		if (node instanceof Type) {
			final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
			if (parent instanceof FieldDeclaration) {
				final List fragments= ((FieldDeclaration) parent).fragments();
				result= new ArrayList(fragments.size());
				VariableDeclarationFragment fragment= null;
				for (final Iterator iterator= fragments.iterator(); iterator.hasNext();) {
					fragment= (VariableDeclarationFragment) iterator.next();
					final IField field= getCorrespondingField(fragment);
					if (field != null)
						result.add(field);
				}
			}
		}
		return result;
	}

	/**
	 * Returns the method which references the specified ast node.
	 * 
	 * @param node the ast node
	 * @return the referencing method
	 * @throws JavaModelException if an error occurs
	 */
	protected final IMethod getReferencingMethod(final ASTNode node) throws JavaModelException {
		if (node instanceof Type) {
			final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
			if (parent instanceof MethodDeclaration) {
				final IMethodBinding binding= ((MethodDeclaration) parent).resolveBinding();
				if (binding != null) {
					final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(node);
					final IJavaElement element= unit.getElementAt(node.getStartPosition());
					if (element instanceof IMethod)
						return (IMethod) element;
				}
			}
		}
		return null;
	}

	/**
	 * Returns whether type occurrences in instanceof's should be rewritten.
	 * 
	 * @return <code>true</code> if they are rewritten, <code>false</code> otherwise
	 */
	public final boolean isInstanceOf() {
		return fInstanceOf;
	}

	/**
	 * Performs the first pass of processing the affected compilation units.
	 * 
	 * @param creator the constraints creator to use
	 * @param units the compilation unit map (element type: <code>&ltIJavaProject, Set&ltICompilationUnit&gt&gt</code>)
	 * @param groups the search result group map (element type: <code>&ltICompilationUnit, SearchResultGroup&gt</code>)
	 * @param unit the compilation unit of the subtype
	 * @param node the compilation unit node of the subtype
	 */
	protected final void performFirstPass(final SuperTypeConstraintsCreator creator, final Map units, final Map groups, final ICompilationUnit unit, final CompilationUnit node) {
		node.setProperty(RefactoringASTParser.SOURCE_PROPERTY, unit);
		node.accept(creator);
		final SearchResultGroup group= (SearchResultGroup) groups.get(unit);
		if (group != null) {
			final ASTNode[] nodes= ASTNodeSearchUtil.getAstNodes(group.getSearchResults(), node);
			try {
				getMethodReferencingCompilationUnits(units, nodes);
				getFieldReferencingCompilationUnits(units, nodes);
			} catch (JavaModelException exception) {
				JavaPlugin.log(exception);
			}
		}
	}

	/**
	 * Performs the second pass of processing the affected compilation units.
	 * 
	 * @param creator the constraints creator to use
	 * @param unit the compilation unit of the subtype
	 * @param node the compilation unit node of the subtype
	 */
	protected final void performSecondPass(final SuperTypeConstraintsCreator creator, final ICompilationUnit unit, final CompilationUnit node) {
		node.setProperty(RefactoringASTParser.SOURCE_PROPERTY, unit);
		node.accept(creator);
	}

	/**
	 * Creates the necessary text edits to replace the subtype occurrence by a supertype.
	 * 
	 * @param range the compilation unit range
	 * @param estimate the type estimate
	 * @param requestor the ast requestor to use
	 * @param rewrite the compilation unit rewrite to use
	 * @param copy the compilation unit node of the working copy ast
	 * @param replacements the set of variable binding keys of formal parameters which must be replaced
	 * @param group the text edit group to use
	 */
	protected final void rewriteTypeOccurrence(final CompilationUnitRange range, final TType estimate, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final CompilationUnit copy, final Set replacements, final TextEditGroup group) {
		ASTNode node= null;
		IBinding binding= null;
		final CompilationUnit target= rewrite.getRoot();
		node= NodeFinder.perform(copy, range.getSourceRange());
		if (node != null) {
			node= ASTNodes.getNormalizedNode(node).getParent();
			if (node instanceof VariableDeclaration) {
				binding= ((VariableDeclaration) node).resolveBinding();
				node= target.findDeclaringNode(binding.getKey());
				if (node instanceof SingleVariableDeclaration) {
					rewriteTypeOccurrence(estimate, rewrite, ((SingleVariableDeclaration) node).getType(), group);
					if (node.getParent() instanceof MethodDeclaration) {
						binding= ((VariableDeclaration) node).resolveBinding();
						if (binding != null)
							replacements.add(binding.getKey());
					}
				}
			} else if (node instanceof VariableDeclarationStatement) {
				binding= ((VariableDeclaration) ((VariableDeclarationStatement) node).fragments().get(0)).resolveBinding();
				node= target.findDeclaringNode(binding.getKey());
				if (node instanceof VariableDeclarationFragment)
					rewriteTypeOccurrence(estimate, rewrite, ((VariableDeclarationStatement) ((VariableDeclarationFragment) node).getParent()).getType(), group);
			} else if (node instanceof MethodDeclaration) {
				binding= ((MethodDeclaration) node).resolveBinding();
				node= target.findDeclaringNode(binding.getKey());
				if (node instanceof MethodDeclaration)
					rewriteTypeOccurrence(estimate, rewrite, ((MethodDeclaration) node).getReturnType2(), group);
			} else if (node instanceof FieldDeclaration) {
				binding= ((VariableDeclaration) ((FieldDeclaration) node).fragments().get(0)).resolveBinding();
				node= target.findDeclaringNode(binding.getKey());
				if (node instanceof VariableDeclarationFragment) {
					node= node.getParent();
					if (node instanceof FieldDeclaration)
						rewriteTypeOccurrence(estimate, rewrite, ((FieldDeclaration) node).getType(), group);
				}
			} else if (node instanceof ArrayType) {
				final ASTNode type= node;
				while (node != null && !(node instanceof MethodDeclaration) && !(node instanceof VariableDeclarationFragment))
					node= node.getParent();
				if (node != null) {
					final int delta= node.getStartPosition() + node.getLength() - type.getStartPosition();
					if (node instanceof MethodDeclaration)
						binding= ((MethodDeclaration) node).resolveBinding();
					else if (node instanceof VariableDeclarationFragment)
						binding= ((VariableDeclarationFragment) node).resolveBinding();
					if (binding != null) {
						node= target.findDeclaringNode(binding.getKey());
						if (node instanceof MethodDeclaration || node instanceof VariableDeclarationFragment) {
							node= NodeFinder.perform(target, node.getStartPosition() + node.getLength() - delta, 0);
							if (node instanceof SimpleName)
								rewriteTypeOccurrence(estimate, rewrite, node, group);
						}
					}
				}
			} else if (node instanceof QualifiedName) {
				final ASTNode name= node;
				while (node != null && !(node instanceof MethodDeclaration) && !(node instanceof VariableDeclarationFragment))
					node= node.getParent();
				if (node != null) {
					final int delta= node.getStartPosition() + node.getLength() - name.getStartPosition();
					if (node instanceof MethodDeclaration)
						binding= ((MethodDeclaration) node).resolveBinding();
					else if (node instanceof VariableDeclarationFragment)
						binding= ((VariableDeclarationFragment) node).resolveBinding();
					if (binding != null) {
						node= target.findDeclaringNode(binding.getKey());
						if (node instanceof SimpleName || node instanceof MethodDeclaration || node instanceof VariableDeclarationFragment) {
							node= NodeFinder.perform(target, node.getStartPosition() + node.getLength() - delta, 0);
							if (node instanceof SimpleName)
								rewriteTypeOccurrence(estimate, rewrite, node, group);
						}
					}
				}
			} else if (node instanceof CastExpression) {
				final ASTNode expression= node;
				while (node != null && !(node instanceof MethodDeclaration))
					node= node.getParent();
				if (node != null) {
					final int delta= node.getStartPosition() + node.getLength() - expression.getStartPosition();
					binding= ((MethodDeclaration) node).resolveBinding();
					node= target.findDeclaringNode(binding.getKey());
					if (node instanceof MethodDeclaration) {
						node= NodeFinder.perform(target, node.getStartPosition() + node.getLength() - delta, 0);
						if (node instanceof CastExpression)
							rewriteTypeOccurrence(estimate, rewrite, ((CastExpression) node).getType(), group);
					}
				}
			}
		}
	}

	/**
	 * Creates the necessary text edits to replace the subtype occurrence by a supertype.
	 * 
	 * @param estimate the type estimate
	 * @param rewrite the ast rewrite to use
	 * @param node the ast node to rewrite
	 * @param group the text edit group to use
	 */
	protected final void rewriteTypeOccurrence(final TType estimate, final CompilationUnitRewrite rewrite, final ASTNode node, final TextEditGroup group) {
		rewrite.getImportRemover().registerRemovedNode(node);
		rewrite.getASTRewrite().replace(node, createCorrespondingNode(rewrite, estimate), group);
	}

	/**
	 * Creates the necessary text edits to replace the subtype occurrence by a supertype.
	 * 
	 * @param manager the text change manager to use
	 * @param requestor the ast requestor to use
	 * @param rewrite the compilation unit rewrite of the subtype (not in working copy mode)
	 * @param unit the compilation unit
	 * @param node the compilation unit node
	 * @param replacements the set of variable binding keys of formal parameters which must be replaced
	 * @throws CoreException if the change could not be generated
	 */
	protected abstract void rewriteTypeOccurrences(TextChangeManager manager, ASTRequestor requestor, CompilationUnitRewrite rewrite, ICompilationUnit unit, CompilationUnit node, final Set replacements) throws CoreException;

	/**
	 * Creates the necessary text edits to replace the subtype occurrences by a supertype.
	 * 
	 * @param manager the text change manager to use
	 * @param sourceRewrite the compilation unit rewrite of the subtype (not in working copy mode)
	 * @param sourceRequestor the ast requestor of the subtype, or <code>null</code>
	 * @param subUnit the compilation unit of the subtype, or <code>null</code>
	 * @param subNode the compilation unit node of the subtype, or <code>null</code>
	 * @param replacements the set of variable binding keys of formal parameters which must be replaced
	 * @param status the refactoring status
	 * @param monitor the progress monitor to use
	 */
	protected final void rewriteTypeOccurrences(final TextChangeManager manager, final ASTRequestor sourceRequestor, final CompilationUnitRewrite sourceRewrite, final ICompilationUnit subUnit, final CompilationUnit subNode, final Set replacements, final RefactoringStatus status, final IProgressMonitor monitor) {
		if (fTypeOccurrences != null) {
			final Set units= new HashSet(fTypeOccurrences.keySet());
			if (subUnit != null)
				units.remove(subUnit);
			final Map projects= new HashMap();
			Collection collection= null;
			IJavaProject project= null;
			ICompilationUnit current= null;
			for (final Iterator iterator= units.iterator(); iterator.hasNext();) {
				current= (ICompilationUnit) iterator.next();
				project= current.getJavaProject();
				collection= (Collection) projects.get(project);
				if (collection == null) {
					collection= new ArrayList();
					projects.put(project, collection);
				}
				collection.add(current);
			}
			final ASTParser parser= ASTParser.newParser(AST.JLS3);
			final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
			try {
				final Set keySet= projects.keySet();
				subMonitor.beginTask("", keySet.size()); //$NON-NLS-1$
				subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
				for (final Iterator iterator= keySet.iterator(); iterator.hasNext();) {
					project= (IJavaProject) iterator.next();
					collection= (Collection) projects.get(project);
					parser.setWorkingCopyOwner(fOwner);
					parser.setResolveBindings(true);
					parser.setProject(project);
					parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
					final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 1);
					try {
						subsubMonitor.beginTask("", collection.size()); //$NON-NLS-1$
						subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
						parser.createASTs((ICompilationUnit[]) collection.toArray(new ICompilationUnit[collection.size()]), new String[0], new ASTRequestor() {

							public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
								try {
									if (sourceRewrite != null)
										rewriteTypeOccurrences(manager, this, sourceRewrite, unit, node, replacements);
								} catch (CoreException exception) {
									status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
								} finally {
									subsubMonitor.worked(1);
								}
							}

							public final void acceptBinding(final String key, final IBinding binding) {
								// Do nothing
							}
						}, subsubMonitor);
					} finally {
						subsubMonitor.done();
					}
				}
			} finally {
				subMonitor.done();
			}
			try {
				if (subUnit != null && subNode != null && sourceRewrite != null && sourceRequestor != null)
					rewriteTypeOccurrences(manager, sourceRequestor, sourceRewrite, subUnit, subNode, replacements);
			} catch (CoreException exception) {
				status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
			}
		}
	}

	/**
	 * Determines whether type occurrences in instanceof's should be rewritten.
	 * 
	 * @param rewrite <code>true</code> to rewrite them, <code>false</code> otherwise
	 */
	public final void setInstanceOf(final boolean rewrite) {
		fInstanceOf= rewrite;
	}

	/**
	 * Solves the supertype constraints to replace subtype by a supertype.
	 * 
	 * @param subUnit the compilation unit of the subtype, or <code>null</code>
	 * @param subNode the compilation unit node of the subtype, or <code>null</code>
	 * @param subType the java element of the subtype
	 * @param subBinding the type binding of the subtype to replace
	 * @param superBinding the type binding of the supertype to use as replacement
	 * @param monitor the progress monitor to use
	 * @param status the refactoring status
	 * @throws JavaModelException if an error occurs
	 */
	protected final void solveSuperTypeConstraints(final ICompilationUnit subUnit, final CompilationUnit subNode, final IType subType, final ITypeBinding subBinding, final ITypeBinding superBinding, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
		Assert.isNotNull(subType);
		Assert.isNotNull(subBinding);
		Assert.isNotNull(superBinding);
		Assert.isNotNull(monitor);
		Assert.isNotNull(status);
		int level= 3;
		TypeEnvironment environment= new TypeEnvironment();
		final SuperTypeConstraintsModel model= new SuperTypeConstraintsModel(environment, environment.create(subBinding), environment.create(superBinding));
		final SuperTypeConstraintsCreator creator= new SuperTypeConstraintsCreator(model, fInstanceOf);
		try {
			monitor.beginTask("", 3); //$NON-NLS-1$
			monitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
			final Map firstPass= getReferencingCompilationUnits(subType, new SubProgressMonitor(monitor, 1), status);
			final Map secondPass= new HashMap();
			IJavaProject project= null;
			Collection collection= null;
			try {
				final ASTParser parser= ASTParser.newParser(AST.JLS3);
				Object element= null;
				ICompilationUnit current= null;
				SearchResultGroup group= null;
				SearchMatch[] matches= null;
				final Map groups= new HashMap();
				for (final Iterator outer= firstPass.keySet().iterator(); outer.hasNext();) {
					project= (IJavaProject) outer.next();
					if (level == 3 && !JavaModelUtil.is50OrHigher(project))
						level= 2;
					collection= (Collection) firstPass.get(project);
					if (collection != null) {
						for (final Iterator inner= collection.iterator(); inner.hasNext();) {
							group= (SearchResultGroup) inner.next();
							matches= group.getSearchResults();
							for (int index= 0; index < matches.length; index++) {
								element= matches[index].getElement();
								if (element instanceof IMember) {
									current= ((IMember) element).getCompilationUnit();
									if (current != null)
										groups.put(current, group);
								}
							}
						}
					}
				}
				Set units= null;
				final Set processed= new HashSet();
				if (subUnit != null)
					processed.add(subUnit);
				model.beginCreation();
				IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
				try {
					final Set keySet= firstPass.keySet();
					subMonitor.beginTask("", keySet.size()); //$NON-NLS-1$
					subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
					for (final Iterator outer= keySet.iterator(); outer.hasNext();) {
						project= (IJavaProject) outer.next();
						collection= (Collection) firstPass.get(project);
						if (collection != null) {
							units= new HashSet(collection.size());
							for (final Iterator inner= collection.iterator(); inner.hasNext();) {
								group= (SearchResultGroup) inner.next();
								matches= group.getSearchResults();
								for (int index= 0; index < matches.length; index++) {
									element= matches[index].getElement();
									if (element instanceof IMember) {
										current= ((IMember) element).getCompilationUnit();
										if (current != null)
											units.add(current);
									}
								}
							}
							final List batches= new ArrayList(units);
							final int size= batches.size();
							final int iterations= ((size - 1) / SIZE_BATCH) + 1;
							final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 1);
							subsubMonitor.beginTask("", iterations); //$NON-NLS-1$
							subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
							final Map options= RefactoringASTParser.getCompilerOptions(project);
							for (int index= 0; index < iterations; index++) {
								final List iteration= batches.subList(index * SIZE_BATCH, Math.min(size, (index + 1) * SIZE_BATCH));
								parser.setWorkingCopyOwner(fOwner);
								parser.setResolveBindings(true);
								parser.setProject(project);
								parser.setCompilerOptions(options);
								final IProgressMonitor subsubsubMonitor= new SubProgressMonitor(subsubMonitor, 1);
								try {
									final int count= iteration.size();
									subsubsubMonitor.beginTask("", count); //$NON-NLS-1$
									subsubsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
									parser.createASTs((ICompilationUnit[]) iteration.toArray(new ICompilationUnit[count]), new String[0], new ASTRequestor() {

										public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
											try {
												subsubsubMonitor.subTask(unit.getElementName());
												if (!processed.contains(unit)) {
													performFirstPass(creator, secondPass, groups, unit, node);
													processed.add(unit);
												}
											} finally {
												subsubsubMonitor.worked(1);
											}
										}

										public final void acceptBinding(final String key, final IBinding binding) {
											// Do nothing
										}
									}, subsubsubMonitor);
								} finally {
									subsubsubMonitor.done();
								}
							}
						}
					}
				} finally {
					firstPass.clear();
					subMonitor.done();
				}
				if (subUnit != null && subNode != null)
					performFirstPass(creator, secondPass, groups, subUnit, subNode);
				subMonitor= new SubProgressMonitor(monitor, 1);
				try {
					final Set keySet= secondPass.keySet();
					subMonitor.beginTask("", keySet.size()); //$NON-NLS-1$
					subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
					for (final Iterator iterator= keySet.iterator(); iterator.hasNext();) {
						project= (IJavaProject) iterator.next();
						if (level == 3 && !JavaModelUtil.is50OrHigher(project))
							level= 2;
						collection= (Collection) secondPass.get(project);
						if (collection != null) {
							parser.setWorkingCopyOwner(fOwner);
							parser.setResolveBindings(true);
							parser.setProject(project);
							parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
							final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 1);
							try {
								subsubMonitor.beginTask("", collection.size()); //$NON-NLS-1$
								subsubMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating);
								parser.createASTs((ICompilationUnit[]) collection.toArray(new ICompilationUnit[collection.size()]), new String[0], new ASTRequestor() {

									public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
										try {
											subsubMonitor.subTask(unit.getElementName());
											if (!processed.contains(unit))
												performSecondPass(creator, unit, node);
										} finally {
											subsubMonitor.worked(1);
										}
									}

									public final void acceptBinding(final String key, final IBinding binding) {
										// Do nothing
									}
								}, subsubMonitor);
							} finally {
								subsubMonitor.done();
							}
						}
					}
				} finally {
					secondPass.clear();
					subMonitor.done();
				}
			} finally {
				model.endCreation();
				model.setCompliance(level);
			}
			final SuperTypeConstraintsSolver solver= createContraintSolver(model);
			solver.solveConstraints();
			fTypeOccurrences= solver.getTypeOccurrences();
			fObsoleteCasts= solver.getObsoleteCasts();
		} finally {
			monitor.done();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean canEnableComment() {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	public final String getComment() {
		return fComment;
	}

	/**
	 * {@inheritDoc}
	 */
	public final void setComment(final String comment) {
		fComment= comment;
	}
}

Back to the top