View | Details | Raw Unified | Return to bug 432147 | Differences between
and this patch

Collapse All | Expand All

(-)a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java (-21 / +55 lines)
Lines 2-15 Link Here
2
 * Copyright (c) 2000, 2014 IBM Corporation and others.
2
 * Copyright (c) 2000, 2014 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     Timo Kinnunen - Contribution for bug 432147 - [refactoring] Extract Constant displays error message on name of local variable
9
 *     IBM Corporation - initial API and implementation
10
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.internal.corext.refactoring.code;
12
package org.eclipse.jdt.internal.corext.refactoring.code;
12
13
13
import java.util.ArrayList;
14
import java.util.ArrayList;
14
import java.util.Arrays;
15
import java.util.Arrays;
15
import java.util.HashMap;
16
import java.util.HashMap;
Lines 52-65 Link Here
52
import org.eclipse.jdt.core.dom.Expression;
53
import org.eclipse.jdt.core.dom.Expression;
53
import org.eclipse.jdt.core.dom.FieldDeclaration;
54
import org.eclipse.jdt.core.dom.FieldDeclaration;
54
import org.eclipse.jdt.core.dom.IBinding;
55
import org.eclipse.jdt.core.dom.IBinding;
55
import org.eclipse.jdt.core.dom.IExtendedModifier;
56
import org.eclipse.jdt.core.dom.IExtendedModifier;
56
import org.eclipse.jdt.core.dom.IMethodBinding;
57
import org.eclipse.jdt.core.dom.IMethodBinding;
57
import org.eclipse.jdt.core.dom.ITypeBinding;
58
import org.eclipse.jdt.core.dom.ITypeBinding;
58
import org.eclipse.jdt.core.dom.IVariableBinding;
59
import org.eclipse.jdt.core.dom.IVariableBinding;
60
import org.eclipse.jdt.core.dom.Initializer;
59
import org.eclipse.jdt.core.dom.Javadoc;
61
import org.eclipse.jdt.core.dom.Javadoc;
60
import org.eclipse.jdt.core.dom.MethodDeclaration;
62
import org.eclipse.jdt.core.dom.MethodDeclaration;
61
import org.eclipse.jdt.core.dom.Modifier;
63
import org.eclipse.jdt.core.dom.Modifier;
62
import org.eclipse.jdt.core.dom.SimpleName;
64
import org.eclipse.jdt.core.dom.SimpleName;
63
import org.eclipse.jdt.core.dom.Statement;
65
import org.eclipse.jdt.core.dom.Statement;
64
import org.eclipse.jdt.core.dom.SwitchStatement;
66
import org.eclipse.jdt.core.dom.SwitchStatement;
65
import org.eclipse.jdt.core.dom.Type;
67
import org.eclipse.jdt.core.dom.Type;
Lines 122-135 Link Here
122
124
123
	//------ settings ---------//
125
	//------ settings ---------//
124
	private String fFieldName;
126
	private String fFieldName;
125
	private int fVisibility; 	/*see Modifier*/
127
	private int fVisibility; 	/*see Modifier*/
126
	private boolean fDeclareStatic;
128
	private boolean fDeclareStatic;
127
	private boolean fDeclareFinal;
129
	private boolean fDeclareFinal;
128
	private int fInitializeIn; /*see INITIALIZE_IN_* constraints */
130
	private int fInitializeIn; /*see INITIALIZE_IN_* constraints */
131
	private boolean fInitializeAsConstantIfPossible= false;
129
132
130
	//------ fields used for computations ---------//
133
	//------ fields used for computations ---------//
131
    private CompilationUnit fCompilationUnitNode;
134
    private CompilationUnit fCompilationUnitNode;
132
    private VariableDeclaration fTempDeclarationNode;
135
    private VariableDeclaration fTempDeclarationNode;
133
	//------ analysis ---------//
136
	//------ analysis ---------//
134
	private boolean fInitializerUsesLocalTypes;
137
	private boolean fInitializerUsesLocalTypes;
135
	private boolean fTempTypeUsesClassTypeVariables;
138
	private boolean fTempTypeUsesClassTypeVariables;
Lines 253-289 Link Here
253
	}
256
	}
254
257
255
	public boolean canEnableSettingFinal(){
258
	public boolean canEnableSettingFinal(){
256
		if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
259
		if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
257
			return  canEnableSettingDeclareInConstructors() && ! tempHasAssignmentsOtherThanInitialization();
260
			return  canEnableSettingDeclareInConstructors() && ! tempHasAssignmentsOtherThanInitialization();
258
		else if (fInitializeIn == INITIALIZE_IN_FIELD)
261
		else if (fInitializeIn == INITIALIZE_IN_FIELD)
259
			return  canEnableSettingDeclareInFieldDeclaration() && ! tempHasAssignmentsOtherThanInitialization();
262
			return  canEnableSettingDeclareInFieldDeclaration() && ! tempHasAssignmentsOtherThanInitialization();
260
		else	if (getMethodDeclaration().isConstructor())
263
		else if (isDeclaredInConstructor() || isDeclaredInInitializer())
261
			return  !tempHasAssignmentsOtherThanInitialization();
264
			return  !tempHasAssignmentsOtherThanInitialization();
262
		else
265
		else
263
			return false;
266
			return false;
264
	}
267
	}
265
268
266
    private boolean tempHasAssignmentsOtherThanInitialization() {
269
    private boolean tempHasAssignmentsOtherThanInitialization() {
267
    	TempAssignmentFinder assignmentFinder= new TempAssignmentFinder(fTempDeclarationNode);
270
    	TempAssignmentFinder assignmentFinder= new TempAssignmentFinder(fTempDeclarationNode);
268
    	fCompilationUnitNode.accept(assignmentFinder);
271
    	fCompilationUnitNode.accept(assignmentFinder);
269
		return assignmentFinder.hasAssignments();
272
		return assignmentFinder.hasAssignments();
270
    }
273
    }
271
274
272
	public boolean canEnableSettingDeclareInConstructors(){
275
	public boolean canEnableSettingDeclareInConstructors(){
273
		return ! fDeclareStatic &&
276
		return ! fDeclareStatic &&
274
				! fInitializerUsesLocalTypes &&
277
				! fInitializerUsesLocalTypes &&
275
				! getMethodDeclaration().isConstructor() &&
278
				! isDeclaredInConstructor() &&
276
				! isDeclaredInAnonymousClass() &&
279
				! isDeclaredInAnonymousClass() &&
277
				! isTempDeclaredInStaticMethod() &&
280
				! isTempDeclaredInStaticMethod() &&
278
				tempHasInitializer();
281
				tempHasInitializer();
279
	}
282
	}
280
283
284
	private boolean isDeclaredInConstructor() {
285
		BodyDeclaration methodDeclaration= getBodyDeclaration();
286
		if(methodDeclaration instanceof MethodDeclaration) {
287
			return ((MethodDeclaration) methodDeclaration).isConstructor();
288
		}
289
		return false;
290
	}
291
292
	private boolean isDeclaredInInitializer() {
293
		BodyDeclaration initializerDeclaration= getBodyDeclaration();
294
		return initializerDeclaration instanceof Initializer;
295
	}
296
281
	public boolean canEnableSettingDeclareInMethod(){
297
	public boolean canEnableSettingDeclareInMethod(){
282
		return ! fDeclareFinal &&
298
		return (! fDeclareFinal || isDeclaredInInitializer()) &&
283
				tempHasInitializer();
299
				tempHasInitializer();
284
	}
300
	}
285
    private boolean tempHasInitializer() {
301
    private boolean tempHasInitializer() {
286
        return getTempInitializer() != null;
302
        return getTempInitializer() != null;
287
    }
303
    }
288
304
289
	public boolean canEnableSettingDeclareInFieldDeclaration(){
305
	public boolean canEnableSettingDeclareInFieldDeclaration(){
Lines 291-309 Link Here
291
	}
307
	}
292
308
293
    private Expression getTempInitializer() {
309
    private Expression getTempInitializer() {
294
    	return fTempDeclarationNode.getInitializer();
310
    	return fTempDeclarationNode.getInitializer();
295
    }
311
    }
296
312
297
    private boolean isTempDeclaredInStaticMethod() {
313
    private boolean isTempDeclaredInStaticMethod() {
298
    	return Modifier.isStatic(getMethodDeclaration().getModifiers());
314
    	return Modifier.isStatic(getBodyDeclaration().getModifiers());
299
    }
315
    }
300
316
301
    private MethodDeclaration getMethodDeclaration(){
317
    private BodyDeclaration getBodyDeclaration(){
302
    	return (MethodDeclaration)ASTNodes.getParent(fTempDeclarationNode, MethodDeclaration.class);
318
    	return (BodyDeclaration)ASTNodes.getParent(fTempDeclarationNode, BodyDeclaration.class);
303
    }
319
    }
304
320
305
    private boolean isDeclaredInAnonymousClass() {
321
    private boolean isDeclaredInAnonymousClass() {
306
    	return null != ASTNodes.getParent(fTempDeclarationNode, AnonymousClassDeclaration.class);
322
    	return null != ASTNodes.getParent(fTempDeclarationNode, AnonymousClassDeclaration.class);
307
    }
323
    }
308
324
309
    /*
325
    /*
Lines 318-332 Link Here
318
			return result;
334
			return result;
319
335
320
		initAST(pm);
336
		initAST(pm);
321
337
322
		if (fTempDeclarationNode == null)
338
		if (fTempDeclarationNode == null)
323
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_select_declaration);
339
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_select_declaration);
324
340
325
		if (! Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class))
341
		if (! Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class) && !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class) )
326
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_only_declared_in_methods);
342
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_only_declared_in_methods);
327
343
328
		if (isMethodParameter())
344
		if (isMethodParameter())
329
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_method_parameters);
345
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_method_parameters);
330
346
331
		if (isTempAnExceptionInCatchBlock())
347
		if (isTempAnExceptionInCatchBlock())
332
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions);
348
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions);
Lines 344-365 Link Here
344
		if (!fSelfInitializing)
360
		if (!fSelfInitializing)
345
			initializeDefaults();
361
			initializeDefaults();
346
		return result;
362
		return result;
347
	}
363
	}
348
364
349
    private void initializeDefaults() {
365
    private void initializeDefaults() {
350
        fVisibility= Modifier.PRIVATE;
366
        fVisibility= Modifier.PRIVATE;
351
        fDeclareStatic= Modifier.isStatic(getMethodDeclaration().getModifiers());
367
        fDeclareStatic= Modifier.isStatic(getBodyDeclaration().getModifiers());
352
        fDeclareFinal= false;
368
		if (fInitializeAsConstantIfPossible) {
353
        if (canEnableSettingDeclareInMethod())
369
			if(canEnableSettingDeclareInFieldDeclaration())
354
	        fInitializeIn= INITIALIZE_IN_METHOD;
370
		        fInitializeIn= INITIALIZE_IN_FIELD;
355
	    else if (canEnableSettingDeclareInFieldDeclaration())
371
			else if (canEnableSettingDeclareInMethod())
356
	        fInitializeIn= INITIALIZE_IN_FIELD;
372
		        fInitializeIn= INITIALIZE_IN_METHOD;
357
	    else if (canEnableSettingDeclareInConstructors())
373
		    else if (canEnableSettingDeclareInConstructors())
358
	        fInitializeIn= INITIALIZE_IN_CONSTRUCTOR;
374
		        fInitializeIn= INITIALIZE_IN_CONSTRUCTOR;
375
		} else {
376
			if (canEnableSettingDeclareInMethod())
377
				fInitializeIn= INITIALIZE_IN_METHOD;
378
			else if (canEnableSettingDeclareInFieldDeclaration())
379
				fInitializeIn= INITIALIZE_IN_FIELD;
380
			else if (canEnableSettingDeclareInConstructors())
381
				fInitializeIn= INITIALIZE_IN_CONSTRUCTOR;
382
		}
383
        fDeclareFinal= fInitializeAsConstantIfPossible && canEnableSettingFinal();
359
    }
384
    }
360
385
361
	public String[] guessFieldNames() {
386
	public String[] guessFieldNames() {
362
		String rawTempName= StubUtility.getBaseName(fTempDeclarationNode.resolveBinding(), fCu.getJavaProject());
387
		String rawTempName= StubUtility.getBaseName(fTempDeclarationNode.resolveBinding(), fCu.getJavaProject());
363
		String[] excludedNames= getNamesOfFieldsInDeclaringType();
388
		String[] excludedNames= getNamesOfFieldsInDeclaringType();
364
		int dim= ASTNodes.getDimensions(fTempDeclarationNode);
389
		int dim= ASTNodes.getDimensions(fTempDeclarationNode);
365
		return StubUtility.getFieldNameSuggestions(fCu.getJavaProject(), rawTempName, dim, getModifiers(), excludedNames);
390
		return StubUtility.getFieldNameSuggestions(fCu.getJavaProject(), rawTempName, dim, getModifiers(), excludedNames);
Lines 397-411 Link Here
397
	}
422
	}
398
423
399
    private void checkTempInitializerForLocalTypeUsage() {
424
    private void checkTempInitializerForLocalTypeUsage() {
400
    	Expression initializer= fTempDeclarationNode.getInitializer();
425
    	Expression initializer= fTempDeclarationNode.getInitializer();
401
    	if (initializer == null)
426
    	if (initializer == null)
402
	        return;
427
	        return;
403
428
404
		IMethodBinding declaringMethodBinding= getMethodDeclaration().resolveBinding();
429
		IMethodBinding declaringMethodBinding= getMethodBinding();
405
		ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
430
		ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
406
	    LocalTypeAndVariableUsageAnalyzer localTypeAnalyer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
431
	    LocalTypeAndVariableUsageAnalyzer localTypeAnalyer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
407
	    initializer.accept(localTypeAnalyer);
432
	    initializer.accept(localTypeAnalyer);
408
	    fInitializerUsesLocalTypes= ! localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
433
	    fInitializerUsesLocalTypes= ! localTypeAnalyer.getUsageOfEnclosingNodes().isEmpty();
409
    }
434
    }
410
435
411
    private RefactoringStatus checkTempTypeForLocalTypeUsage(){
436
    private RefactoringStatus checkTempTypeForLocalTypeUsage(){
Lines 413-436 Link Here
413
    	if (vds == null)
438
    	if (vds == null)
414
    		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
439
    		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
415
    	Type type= 	vds.getType();
440
    	Type type= 	vds.getType();
416
    	ITypeBinding binding= type.resolveBinding();
441
    	ITypeBinding binding= type.resolveBinding();
417
    	if (binding == null)
442
    	if (binding == null)
418
    		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
443
    		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
419
444
420
		IMethodBinding declaringMethodBinding= getMethodDeclaration().resolveBinding();
445
		IMethodBinding declaringMethodBinding= getMethodBinding();
421
		ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
446
		ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
422
		LocalTypeAndVariableUsageAnalyzer analyzer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
447
		LocalTypeAndVariableUsageAnalyzer analyzer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
423
		type.accept(analyzer);
448
		type.accept(analyzer);
424
		boolean usesLocalTypes= ! analyzer.getUsageOfEnclosingNodes().isEmpty();
449
		boolean usesLocalTypes= ! analyzer.getUsageOfEnclosingNodes().isEmpty();
425
		fTempTypeUsesClassTypeVariables= analyzer.getClassTypeVariablesUsed();
450
		fTempTypeUsesClassTypeVariables= analyzer.getClassTypeVariablesUsed();
426
		if (usesLocalTypes)
451
		if (usesLocalTypes)
427
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_uses_type_declared_locally);
452
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_uses_type_declared_locally);
428
		return null;
453
		return null;
429
    }
454
    }
455
456
	private IMethodBinding getMethodBinding() {
457
		BodyDeclaration methodDeclaration= getBodyDeclaration();
458
		return methodDeclaration != null && methodDeclaration instanceof MethodDeclaration ? ((MethodDeclaration) methodDeclaration).resolveBinding() : null;
459
	}
430
460
431
    private VariableDeclarationStatement getTempDeclarationStatement() {
461
    private VariableDeclarationStatement getTempDeclarationStatement() {
432
        return (VariableDeclarationStatement) ASTNodes.getParent(fTempDeclarationNode, VariableDeclarationStatement.class);
462
        return (VariableDeclarationStatement) ASTNodes.getParent(fTempDeclarationNode, VariableDeclarationStatement.class);
433
    }
463
    }
434
464
435
    private boolean isTempAnExceptionInCatchBlock() {
465
    private boolean isTempAnExceptionInCatchBlock() {
436
		return (fTempDeclarationNode.getParent() instanceof CatchClause);
466
		return (fTempDeclarationNode.getParent() instanceof CatchClause);
Lines 466-480 Link Here
466
    		pm.done();
496
    		pm.done();
467
    	}
497
    	}
468
    }
498
    }
469
499
470
    private RefactoringStatus checkClashesInConstructors() {
500
    private RefactoringStatus checkClashesInConstructors() {
471
		Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
501
		Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
472
		Assert.isTrue(!isDeclaredInAnonymousClass());
502
		Assert.isTrue(!isDeclaredInAnonymousClass());
473
		final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getMethodDeclaration().getParent();
503
		final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getBodyDeclaration().getParent();
474
		if (declaration instanceof TypeDeclaration) {
504
		if (declaration instanceof TypeDeclaration) {
475
			MethodDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
505
			MethodDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
476
			for (int i= 0; i < methods.length; i++) {
506
			for (int i= 0; i < methods.length; i++) {
477
				MethodDeclaration method= methods[i];
507
				MethodDeclaration method= methods[i];
478
				if (!method.isConstructor())
508
				if (!method.isConstructor())
479
					continue;
509
					continue;
480
				NameCollector nameCollector= new NameCollector(method) {
510
				NameCollector nameCollector= new NameCollector(method) {
Lines 509-523 Link Here
509
                }
539
                }
510
            }
540
            }
511
        }
541
        }
512
        return null;
542
        return null;
513
    }
543
    }
514
544
515
    private FieldDeclaration[] getFieldDeclarations() {
545
    private FieldDeclaration[] getFieldDeclarations() {
516
    	List<BodyDeclaration> bodyDeclarations= ASTNodes.getBodyDeclarations(getMethodDeclaration().getParent());
546
    	List<BodyDeclaration> bodyDeclarations= ASTNodes.getBodyDeclarations(getBodyDeclaration().getParent());
517
    	List<FieldDeclaration> fields= new ArrayList<FieldDeclaration>(1);
547
    	List<FieldDeclaration> fields= new ArrayList<FieldDeclaration>(1);
518
    	for (Iterator<BodyDeclaration> iter= bodyDeclarations.iterator(); iter.hasNext();) {
548
    	for (Iterator<BodyDeclaration> iter= bodyDeclarations.iterator(); iter.hasNext();) {
519
	        Object each= iter.next();
549
	        Object each= iter.next();
520
	        if (each instanceof FieldDeclaration)
550
	        if (each instanceof FieldDeclaration)
521
	        	fields.add((FieldDeclaration) each);
551
	        	fields.add((FieldDeclaration) each);
522
        }
552
        }
523
        return fields.toArray(new FieldDeclaration[fields.size()]);
553
        return fields.toArray(new FieldDeclaration[fields.size()]);
Lines 575-589 Link Here
575
				rewrite.replace(occurence, newName, null);
605
				rewrite.replace(occurence, newName, null);
576
			}
606
			}
577
		}
607
		}
578
    }
608
    }
579
609
580
    private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
610
    private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
581
    	Assert.isTrue(! isDeclaredInAnonymousClass());
611
    	Assert.isTrue(! isDeclaredInAnonymousClass());
582
    	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getMethodDeclaration().getParent();
612
    	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration)getBodyDeclaration().getParent();
583
    	final MethodDeclaration[] constructors= getAllConstructors(declaration);
613
    	final MethodDeclaration[] constructors= getAllConstructors(declaration);
584
    	if (constructors.length == 0) {
614
    	if (constructors.length == 0) {
585
    		AST ast= rewrite.getAST();
615
    		AST ast= rewrite.getAST();
586
    		MethodDeclaration newConstructor= ast.newMethodDeclaration();
616
    		MethodDeclaration newConstructor= ast.newMethodDeclaration();
587
    		newConstructor.setConstructor(true);
617
    		newConstructor.setConstructor(true);
588
    		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
618
    		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
589
    		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
619
    		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
Lines 817-831 Link Here
817
        rewrite.remove(fragment, null);
847
        rewrite.remove(fragment, null);
818
        if (fragments.size() == 1)
848
        if (fragments.size() == 1)
819
			rewrite.remove(tempDeclarationStatement, null);
849
			rewrite.remove(tempDeclarationStatement, null);
820
    }
850
    }
821
851
822
    private void addFieldDeclaration(ASTRewrite rewrite) {
852
    private void addFieldDeclaration(ASTRewrite rewrite) {
823
    	FieldDeclaration[] fields= getFieldDeclarations();
853
    	FieldDeclaration[] fields= getFieldDeclarations();
824
    	ASTNode parent= getMethodDeclaration().getParent();
854
    	ASTNode parent= getBodyDeclaration().getParent();
825
    	ChildListPropertyDescriptor descriptor= ASTNodes.getBodyDeclarationsProperty(parent);
855
    	ChildListPropertyDescriptor descriptor= ASTNodes.getBodyDeclarationsProperty(parent);
826
    	int insertIndex;
856
    	int insertIndex;
827
    	if (fields.length == 0)
857
    	if (fields.length == 0)
828
    		insertIndex= 0;
858
    		insertIndex= 0;
829
    	else
859
    	else
830
    		insertIndex= ASTNodes.getBodyDeclarations(parent).indexOf(fields[fields.length - 1]) + 1;
860
    		insertIndex= ASTNodes.getBodyDeclarations(parent).indexOf(fields[fields.length - 1]) + 1;
831
861
Lines 979-986 Link Here
979
		return new RefactoringStatus();
1009
		return new RefactoringStatus();
980
	}
1010
	}
981
1011
982
1012
983
	public void setLinkedProposalModel(LinkedProposalModel model) {
1013
	public void setLinkedProposalModel(LinkedProposalModel model) {
984
		fLinkedProposalModel= model;
1014
		fLinkedProposalModel= model;
985
	}
1015
	}
1016
1017
	public void setInitializeAsConstantIfPossible(boolean value) {
1018
		fInitializeAsConstantIfPossible = value;
1019
	}
986
}
1020
}
(-)a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties (-2 / +2 lines)
Lines 134-148 Link Here
134
PullUpInputPage_pull_up1=Pull Up Methods
134
PullUpInputPage_pull_up1=Pull Up Methods
135
PullUpInputPage_exception=An unexpected exception occurred. See the error log for more details
135
PullUpInputPage_exception=An unexpected exception occurred. See the error log for more details
136
136
137
ExtractTempAction_label=Extract &Local Variable...
137
ExtractTempAction_label=Extract &Local Variable...
138
ExtractTempAction_extract_temp=Extract Local Variable
138
ExtractTempAction_extract_temp=Extract Local Variable
139
139
140
ConvertLocalToField_label=Con&vert Local Variable to Field...
140
ConvertLocalToField_label=Con&vert Local Variable to Field...
141
ConvertLocalToField_title=Convert Local Variable to Field
141
ConvertLocalToField_title=Convert Local Variable to Field or Constant
142
142
143
ExtractConstantAction_label=Extr&act Constant...
143
ExtractConstantAction_label=Extr&act Constant...
144
ExtractSuperTypeAction_label=Ex&tract Superclass...
144
ExtractSuperTypeAction_label=Ex&tract Superclass...
145
ExtractConstantAction_extract_constant=Extract Constant
145
ExtractConstantAction_extract_constant=Extract Constant
146
146
147
InlineTempAction_inline_temp=Inline Local Variable
147
InlineTempAction_inline_temp=Inline Local Variable
148
InlineTempAction_label=&Inline Local Variable...
148
InlineTempAction_label=&Inline Local Variable...
Lines 317-331 Link Here
317
MoveInstanceMethodPage_Method_name=New &method name:
317
MoveInstanceMethodPage_Method_name=New &method name:
318
MoveInstanceMethodPage_New_receiver=&New target for ''{0}'':
318
MoveInstanceMethodPage_New_receiver=&New target for ''{0}'':
319
MoveInstanceMethodPage_Receiver=Receiver
319
MoveInstanceMethodPage_Receiver=Receiver
320
MoveInstanceMethodPage_Type=Type
320
MoveInstanceMethodPage_Type=Type
321
MoveInstanceMethodPage_invalid_target=Target ''{0}'' is used in an assignment.
321
MoveInstanceMethodPage_invalid_target=Target ''{0}'' is used in an assignment.
322
322
323
PromoteTempInputPage_Field_declaration=Field decla&ration
323
PromoteTempInputPage_Field_declaration=Field decla&ration
324
PromoteTempInputPage_Current_method=&Current method
324
PromoteTempInputPage_Current_method=&Current block
325
PromoteTempInputPage_constructors=C&lass constructors
325
PromoteTempInputPage_constructors=C&lass constructors
326
PromoteTempInputPage_Field_name=F&ield name:
326
PromoteTempInputPage_Field_name=F&ield name:
327
PromoteTempInputPage_Initialize=Initialize in
327
PromoteTempInputPage_Initialize=Initialize in
328
PromoteTempInputPage_declare_static=&Declare field as \'static\'
328
PromoteTempInputPage_declare_static=&Declare field as \'static\'
329
PromoteTempInputPage_declare_final=Decl&are field as \'final\'
329
PromoteTempInputPage_declare_final=Decl&are field as \'final\'
330
330
331
UseSupertypeInputPage_Select_supertype=Select the supertype to use
331
UseSupertypeInputPage_Select_supertype=Select the supertype to use
(-)a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ExtractConstantAction.java (-1 / +39 lines)
Lines 2-34 Link Here
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
2
 * Copyright (c) 2000, 2011 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
7
 *
8
 * Contributors:
8
 * Contributors:
9
 *     Timo Kinnunen - Contribution for bug 432147 - [refactoring] Extract Constant displays error message on name of local variable
9
 *     IBM Corporation - initial API and implementation
10
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
 *******************************************************************************/
11
package org.eclipse.jdt.ui.actions;
12
package org.eclipse.jdt.ui.actions;
12
13
13
import org.eclipse.jface.text.ITextSelection;
14
import org.eclipse.jface.text.ITextSelection;
14
15
15
import org.eclipse.ui.PlatformUI;
16
import org.eclipse.ui.PlatformUI;
16
17
18
import org.eclipse.jdt.core.ICompilationUnit;
19
import org.eclipse.jdt.core.JavaModelException;
20
import org.eclipse.jdt.core.SourceRange;
21
import org.eclipse.jdt.core.dom.ASTNode;
22
import org.eclipse.jdt.core.dom.CompilationUnit;
23
import org.eclipse.jdt.core.dom.SimpleName;
24
import org.eclipse.jdt.core.dom.VariableDeclaration;
25
26
import org.eclipse.jdt.internal.corext.dom.fragments.ASTFragmentFactory;
27
import org.eclipse.jdt.internal.corext.dom.fragments.IASTFragment;
17
import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester;
28
import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester;
18
import org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
29
import org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring;
30
import org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring;
31
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
32
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
19
33
20
import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper;
34
import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper;
21
35
22
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
36
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
37
import org.eclipse.jdt.internal.ui.JavaPlugin;
23
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
38
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
24
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
39
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
25
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
40
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
26
import org.eclipse.jdt.internal.ui.javaeditor.JavaTextSelection;
41
import org.eclipse.jdt.internal.ui.javaeditor.JavaTextSelection;
27
import org.eclipse.jdt.internal.ui.refactoring.ExtractConstantWizard;
42
import org.eclipse.jdt.internal.ui.refactoring.ExtractConstantWizard;
43
import org.eclipse.jdt.internal.ui.refactoring.PromoteTempWizard;
28
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
44
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
29
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
45
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
30
46
31
/**
47
/**
32
 * Extracts an expression into a constant field and replaces all occurrences of
48
 * Extracts an expression into a constant field and replaces all occurrences of
33
 * the expression with the new constant.
49
 * the expression with the new constant.
34
 *
50
 *
Lines 80-90 Link Here
80
	/* (non-Javadoc)
96
	/* (non-Javadoc)
81
	 * Method declared on SelectionDispatchAction
97
	 * Method declared on SelectionDispatchAction
82
	 */
98
	 */
83
	@Override
99
	@Override
84
	public void run(ITextSelection selection) {
100
	public void run(ITextSelection selection) {
85
		if (!ActionUtil.isEditable(fEditor))
101
		if (!ActionUtil.isEditable(fEditor))
86
			return;
102
			return;
87
		ExtractConstantRefactoring refactoring= new ExtractConstantRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection.getOffset(), selection.getLength());
103
		ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(fEditor);
104
		CompilationUnit cuNode= RefactoringASTParser.parseWithASTProvider(unit, true, null);
105
		int selectionStart= selection.getOffset();
106
		int selectionLength= selection.getLength();
107
		ExtractConstantRefactoring refactoring= new ExtractConstantRefactoring(cuNode, selectionStart, selectionLength);
108
		try {
109
			CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(unit, cuNode);
110
			SourceRange range= new SourceRange(selectionStart, selectionLength);
111
			IASTFragment ast= ASTFragmentFactory.createFragmentForSourceRange(range, cuRewrite.getRoot(), unit);
112
			ASTNode node= ast.getAssociatedNode();
113
			if (node instanceof SimpleName && node.getParent() instanceof VariableDeclaration) {
114
				ICompilationUnit cunit= SelectionConverter.getInputAsCompilationUnit(fEditor);
115
				PromoteTempToFieldRefactoring refactoring2= new PromoteTempToFieldRefactoring(cunit, selection.getOffset(), selection.getLength());
116
				refactoring2.setDeclareFinal(true);
117
				refactoring2.setDeclareStatic(true);
118
				refactoring2.setFieldName(refactoring.guessConstantName());
119
				refactoring2.setInitializeAsConstantIfPossible(true);
120
				new RefactoringStarter().activate(new PromoteTempWizard(refactoring2), getShell(), RefactoringMessages.ConvertLocalToField_title, RefactoringSaveHelper.SAVE_NOTHING);
121
				return;
122
			}
123
		} catch (JavaModelException e) {
124
			JavaPlugin.log(e);
125
		}
88
		new RefactoringStarter().activate(new ExtractConstantWizard(refactoring), getShell(), RefactoringMessages.ExtractConstantAction_extract_constant, RefactoringSaveHelper.SAVE_NOTHING);
126
		new RefactoringStarter().activate(new ExtractConstantWizard(refactoring), getShell(), RefactoringMessages.ExtractConstantAction_extract_constant, RefactoringSaveHelper.SAVE_NOTHING);
89
	}
127
	}
90
}
128
}

Return to bug 432147