0001: /*******************************************************************************
0002: * Copyright (c) 2000, 2007 IBM Corporation and others.
0003: * All rights reserved. This program and the accompanying materials
0004: * are made available under the terms of the Eclipse Public License v1.0
0005: * which accompanies this distribution, and is available at
0006: * http://www.eclipse.org/legal/epl-v10.html
0007: *
0008: * Contributors:
0009: * IBM Corporation - initial API and implementation
0010: *******************************************************************************/package org.eclipse.jdt.internal.corext.refactoring.code;
0011:
0012: import java.util.ArrayList;
0013: import java.util.HashMap;
0014: import java.util.HashSet;
0015: import java.util.Iterator;
0016: import java.util.List;
0017: import java.util.Map;
0018: import java.util.Set;
0019: import java.util.StringTokenizer;
0020:
0021: import org.eclipse.text.edits.MalformedTreeException;
0022: import org.eclipse.text.edits.RangeMarker;
0023: import org.eclipse.text.edits.TextEdit;
0024: import org.eclipse.text.edits.TextEditGroup;
0025:
0026: import org.eclipse.core.runtime.Assert;
0027: import org.eclipse.core.runtime.CoreException;
0028: import org.eclipse.core.runtime.IProgressMonitor;
0029: import org.eclipse.core.runtime.OperationCanceledException;
0030: import org.eclipse.core.runtime.SubProgressMonitor;
0031:
0032: import org.eclipse.jface.text.BadLocationException;
0033: import org.eclipse.jface.text.Document;
0034: import org.eclipse.jface.text.IDocument;
0035: import org.eclipse.jface.text.IRegion;
0036: import org.eclipse.jface.text.TextUtilities;
0037:
0038: import org.eclipse.ltk.core.refactoring.Change;
0039: import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
0040: import org.eclipse.ltk.core.refactoring.RefactoringStatus;
0041: import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
0042:
0043: import org.eclipse.jdt.core.Flags;
0044: import org.eclipse.jdt.core.ICompilationUnit;
0045: import org.eclipse.jdt.core.IField;
0046: import org.eclipse.jdt.core.IJavaElement;
0047: import org.eclipse.jdt.core.IJavaProject;
0048: import org.eclipse.jdt.core.ISourceRange;
0049: import org.eclipse.jdt.core.JavaModelException;
0050: import org.eclipse.jdt.core.dom.AST;
0051: import org.eclipse.jdt.core.dom.ASTNode;
0052: import org.eclipse.jdt.core.dom.ASTParser;
0053: import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
0054: import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
0055: import org.eclipse.jdt.core.dom.ArrayCreation;
0056: import org.eclipse.jdt.core.dom.ArrayInitializer;
0057: import org.eclipse.jdt.core.dom.ArrayType;
0058: import org.eclipse.jdt.core.dom.Assignment;
0059: import org.eclipse.jdt.core.dom.BodyDeclaration;
0060: import org.eclipse.jdt.core.dom.CompilationUnit;
0061: import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
0062: import org.eclipse.jdt.core.dom.Expression;
0063: import org.eclipse.jdt.core.dom.FieldAccess;
0064: import org.eclipse.jdt.core.dom.FieldDeclaration;
0065: import org.eclipse.jdt.core.dom.IBinding;
0066: import org.eclipse.jdt.core.dom.IMethodBinding;
0067: import org.eclipse.jdt.core.dom.ITypeBinding;
0068: import org.eclipse.jdt.core.dom.IVariableBinding;
0069: import org.eclipse.jdt.core.dom.ImportDeclaration;
0070: import org.eclipse.jdt.core.dom.MethodInvocation;
0071: import org.eclipse.jdt.core.dom.Modifier;
0072: import org.eclipse.jdt.core.dom.Name;
0073: import org.eclipse.jdt.core.dom.ParenthesizedExpression;
0074: import org.eclipse.jdt.core.dom.QualifiedName;
0075: import org.eclipse.jdt.core.dom.SimpleName;
0076: import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
0077: import org.eclipse.jdt.core.dom.SuperMethodInvocation;
0078: import org.eclipse.jdt.core.dom.Type;
0079: import org.eclipse.jdt.core.dom.TypeDeclarationStatement;
0080: import org.eclipse.jdt.core.dom.VariableDeclaration;
0081: import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
0082: import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
0083: import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
0084: import org.eclipse.jdt.core.refactoring.IJavaRefactorings;
0085: import org.eclipse.jdt.core.refactoring.descriptors.InlineConstantDescriptor;
0086: import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
0087: import org.eclipse.jdt.core.search.IJavaSearchConstants;
0088: import org.eclipse.jdt.core.search.SearchMatch;
0089: import org.eclipse.jdt.core.search.SearchPattern;
0090:
0091: import org.eclipse.jdt.internal.corext.Corext;
0092: import org.eclipse.jdt.internal.corext.codemanipulation.ImportReferencesCollector;
0093: import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
0094: import org.eclipse.jdt.internal.corext.dom.ASTNodes;
0095: import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor;
0096: import org.eclipse.jdt.internal.corext.dom.NodeFinder;
0097: import org.eclipse.jdt.internal.corext.dom.fragments.ASTFragmentFactory;
0098: import org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment;
0099: import org.eclipse.jdt.internal.corext.refactoring.Checks;
0100: import org.eclipse.jdt.internal.corext.refactoring.IRefactoringSearchRequestor;
0101: import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment;
0102: import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
0103: import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringDescriptorUtil;
0104: import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
0105: import org.eclipse.jdt.internal.corext.refactoring.RefactoringScopeFactory;
0106: import org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine2;
0107: import org.eclipse.jdt.internal.corext.refactoring.SearchResultGroup;
0108: import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes;
0109: import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
0110: import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
0111: import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
0112: import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
0113: import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
0114: import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer;
0115: import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
0116: import org.eclipse.jdt.internal.corext.util.Messages;
0117: import org.eclipse.jdt.internal.corext.util.Strings;
0118:
0119: import org.eclipse.jdt.ui.JavaElementLabels;
0120:
0121: import org.eclipse.jdt.internal.ui.JavaPlugin;
0122:
0123: public class InlineConstantRefactoring extends ScriptableRefactoring {
0124:
0125: private static final String ATTRIBUTE_REPLACE = "replace"; //$NON-NLS-1$
0126: private static final String ATTRIBUTE_REMOVE = "remove"; //$NON-NLS-1$
0127:
0128: private static class InlineTargetCompilationUnit {
0129:
0130: private static class InitializerTraversal extends
0131: HierarchicalASTVisitor {
0132:
0133: private static boolean areInSameType(ASTNode one,
0134: ASTNode other) {
0135: ASTNode onesContainer = getContainingTypeDeclaration(one);
0136: ASTNode othersContainer = getContainingTypeDeclaration(other);
0137:
0138: if (onesContainer == null || othersContainer == null)
0139: return false;
0140:
0141: ITypeBinding onesContainerBinding = getTypeBindingForTypeDeclaration(onesContainer);
0142: ITypeBinding othersContainerBinding = getTypeBindingForTypeDeclaration(othersContainer);
0143:
0144: Assert.isNotNull(onesContainerBinding);
0145: Assert.isNotNull(othersContainerBinding);
0146:
0147: String onesKey = onesContainerBinding.getKey();
0148: String othersKey = othersContainerBinding.getKey();
0149:
0150: if (onesKey == null || othersKey == null)
0151: return false;
0152:
0153: return onesKey.equals(othersKey);
0154: }
0155:
0156: private static boolean isStaticAccess(SimpleName memberName) {
0157: IBinding binding = memberName.resolveBinding();
0158: Assert.isTrue(binding instanceof IVariableBinding
0159: || binding instanceof IMethodBinding
0160: || binding instanceof ITypeBinding);
0161:
0162: if (binding instanceof ITypeBinding)
0163: return true;
0164:
0165: if (binding instanceof IVariableBinding)
0166: return ((IVariableBinding) binding).isField();
0167:
0168: int modifiers = binding.getModifiers();
0169: return Modifier.isStatic(modifiers);
0170: }
0171:
0172: private static ASTNode getContainingTypeDeclaration(
0173: ASTNode node) {
0174: while (node != null
0175: && !(node instanceof AbstractTypeDeclaration)
0176: && !(node instanceof AnonymousClassDeclaration)) {
0177: node = node.getParent();
0178: }
0179: return node;
0180: }
0181:
0182: private static ITypeBinding getTypeBindingForTypeDeclaration(
0183: ASTNode declaration) {
0184: if (declaration instanceof AnonymousClassDeclaration)
0185: return ((AnonymousClassDeclaration) declaration)
0186: .resolveBinding();
0187:
0188: if (declaration instanceof AbstractTypeDeclaration)
0189: return ((AbstractTypeDeclaration) declaration)
0190: .resolveBinding();
0191:
0192: Assert.isTrue(false);
0193: return null;
0194: }
0195:
0196: private final Expression fInitializer;
0197: private ASTRewrite fInitializerRewrite;
0198: private final HashSet fStaticImportsInInitializer2;
0199:
0200: // cache:
0201: private Set fNamesDeclaredLocallyAtNewLocation;
0202:
0203: private final Expression fNewLocation;
0204: private final HashSet fStaticImportsInReference;
0205: private final CompilationUnitRewrite fNewLocationCuRewrite;
0206:
0207: public InitializerTraversal(Expression initializer,
0208: HashSet staticImportsInInitializer,
0209: Expression newLocation,
0210: HashSet staticImportsInReference,
0211: CompilationUnitRewrite newLocationCuRewrite) {
0212: fInitializer = initializer;
0213: fInitializerRewrite = ASTRewrite.create(initializer
0214: .getAST());
0215: fStaticImportsInInitializer2 = staticImportsInInitializer;
0216:
0217: fNewLocation = newLocation;
0218: fStaticImportsInReference = staticImportsInReference;
0219: fNewLocationCuRewrite = newLocationCuRewrite;
0220:
0221: perform(initializer);
0222: }
0223:
0224: /**
0225: * @param scope not a TypeDeclaration
0226: * @return Set containing Strings representing simple names
0227: */
0228: private Set getLocallyDeclaredNames(BodyDeclaration scope) {
0229: Assert
0230: .isTrue(!(scope instanceof AbstractTypeDeclaration));
0231:
0232: final Set result = new HashSet();
0233:
0234: if (scope instanceof FieldDeclaration)
0235: return result;
0236:
0237: scope.accept(new HierarchicalASTVisitor() {
0238:
0239: public boolean visit(AbstractTypeDeclaration node) {
0240: Assert
0241: .isTrue(node.getParent() instanceof TypeDeclarationStatement);
0242:
0243: result.add(node.getName().getIdentifier());
0244: return false;
0245: }
0246:
0247: public boolean visit(
0248: AnonymousClassDeclaration anonDecl) {
0249: return false;
0250: }
0251:
0252: public boolean visit(VariableDeclaration varDecl) {
0253: result.add(varDecl.getName().getIdentifier());
0254: return false;
0255: }
0256: });
0257: return result;
0258: }
0259:
0260: public ASTRewrite getInitializerRewrite() {
0261: return fInitializerRewrite;
0262: }
0263:
0264: private void perform(Expression initializer) {
0265: initializer.accept(this );
0266: if (initializer instanceof MethodInvocation
0267: || initializer instanceof SuperMethodInvocation) {
0268: addExplicitTypeArgumentsIfNecessary(initializer);
0269: }
0270: }
0271:
0272: private void addExplicitTypeArgumentsIfNecessary(
0273: Expression invocation) {
0274: if (Invocations
0275: .isResolvedTypeInferredFromExpectedType(invocation)) {
0276: ASTNode referenceContext = fNewLocation.getParent();
0277: if (!(referenceContext instanceof VariableDeclarationFragment
0278: || referenceContext instanceof SingleVariableDeclaration || referenceContext instanceof Assignment)) {
0279: IMethodBinding methodBinding = Invocations
0280: .resolveBinding(invocation);
0281: ITypeBinding[] typeArguments = methodBinding
0282: .getTypeArguments();
0283: ListRewrite typeArgsRewrite = fInitializerRewrite
0284: .getListRewrite(
0285: invocation,
0286: Invocations
0287: .getTypeArgumentsProperty(invocation));
0288: for (int i = 0; i < typeArguments.length; i++) {
0289: Type typeArgument = fNewLocationCuRewrite
0290: .getImportRewrite().addImport(
0291: typeArguments[i],
0292: fNewLocationCuRewrite
0293: .getAST());
0294: fNewLocationCuRewrite.getImportRemover()
0295: .registerAddedImports(typeArgument);
0296: typeArgsRewrite.insertLast(typeArgument,
0297: null);
0298: }
0299: }
0300: }
0301: }
0302:
0303: public boolean visit(FieldAccess fieldAccess) {
0304: fieldAccess.getExpression().accept(this );
0305: return false;
0306: }
0307:
0308: public boolean visit(MethodInvocation invocation) {
0309: if (invocation.getExpression() == null)
0310: qualifyUnqualifiedMemberNameIfNecessary(invocation
0311: .getName());
0312: else
0313: invocation.getExpression().accept(this );
0314:
0315: for (Iterator it = invocation.arguments().iterator(); it
0316: .hasNext();)
0317: ((Expression) it.next()).accept(this );
0318:
0319: return false;
0320: }
0321:
0322: public boolean visit(Name name) {
0323: SimpleName leftmost = getLeftmost(name);
0324:
0325: IBinding leftmostBinding = leftmost.resolveBinding();
0326: if (leftmostBinding instanceof IVariableBinding
0327: || leftmostBinding instanceof IMethodBinding
0328: || leftmostBinding instanceof ITypeBinding) {
0329: if (shouldUnqualify(leftmost))
0330: unqualifyMemberName(leftmost);
0331: else
0332: qualifyUnqualifiedMemberNameIfNecessary(leftmost);
0333: }
0334:
0335: if (leftmostBinding instanceof ITypeBinding) {
0336: String addedImport = fNewLocationCuRewrite
0337: .getImportRewrite().addImport(
0338: (ITypeBinding) leftmostBinding);
0339: fNewLocationCuRewrite.getImportRemover()
0340: .registerAddedImport(addedImport);
0341: }
0342:
0343: return false;
0344: }
0345:
0346: private void qualifyUnqualifiedMemberNameIfNecessary(
0347: SimpleName memberName) {
0348: if (shouldQualify(memberName))
0349: qualifyMemberName(memberName);
0350: }
0351:
0352: private boolean shouldUnqualify(SimpleName memberName) {
0353: if (areInSameType(memberName, fNewLocation))
0354: return !mayBeShadowedByLocalDeclaration(memberName);
0355:
0356: return false;
0357: }
0358:
0359: private void unqualifyMemberName(SimpleName memberName) {
0360: if (doesParentQualify(memberName))
0361: fInitializerRewrite.replace(memberName.getParent(),
0362: memberName, null);
0363: }
0364:
0365: private boolean shouldQualify(SimpleName memberName) {
0366: if (!areInSameType(fInitializer, fNewLocation))
0367: return true;
0368:
0369: return mayBeShadowedByLocalDeclaration(memberName);
0370: }
0371:
0372: private boolean mayBeShadowedByLocalDeclaration(
0373: SimpleName memberName) {
0374: return getNamesDeclaredLocallyAtNewLocation().contains(
0375: memberName.getIdentifier());
0376: }
0377:
0378: private Set getNamesDeclaredLocallyAtNewLocation() {
0379: if (fNamesDeclaredLocallyAtNewLocation != null)
0380: return fNamesDeclaredLocallyAtNewLocation;
0381:
0382: BodyDeclaration enclosingBodyDecl = (BodyDeclaration) ASTNodes
0383: .getParent(fNewLocation, BodyDeclaration.class);
0384: Assert
0385: .isTrue(!(enclosingBodyDecl instanceof AbstractTypeDeclaration));
0386:
0387: return fNamesDeclaredLocallyAtNewLocation = getLocallyDeclaredNames(enclosingBodyDecl);
0388: }
0389:
0390: private void qualifyMemberName(SimpleName memberName) {
0391: if (isStaticAccess(memberName)) {
0392: IBinding memberBinding = memberName
0393: .resolveBinding();
0394:
0395: if (memberBinding instanceof IVariableBinding
0396: || memberBinding instanceof IMethodBinding) {
0397: if (fStaticImportsInReference
0398: .contains(fNewLocation)) { // use static import if reference location used static import
0399: importStatically(memberName, memberBinding);
0400: return;
0401: } else if (fStaticImportsInInitializer2
0402: .contains(memberName)) { // use static import if already imported statically in initializer
0403: importStatically(memberName, memberBinding);
0404: return;
0405: }
0406: }
0407: qualifyToTopLevelClass(memberName); //otherwise: qualify and import non-static
0408: }
0409: }
0410:
0411: private void importStatically(SimpleName toImport,
0412: IBinding binding) {
0413: String newName = fNewLocationCuRewrite
0414: .getImportRewrite().addStaticImport(binding);
0415: fNewLocationCuRewrite.getImportRemover()
0416: .registerAddedStaticImport(binding);
0417:
0418: Name newReference = ASTNodeFactory.newName(
0419: fInitializerRewrite.getAST(), newName);
0420: fInitializerRewrite.replace(toImport, newReference,
0421: null);
0422: }
0423:
0424: private void qualifyToTopLevelClass(SimpleName toQualify) {
0425: ITypeBinding declaringClass = getDeclaringClassBinding(toQualify);
0426: if (declaringClass == null)
0427: return;
0428:
0429: Type newQualification = fNewLocationCuRewrite
0430: .getImportRewrite().addImport(declaringClass,
0431: fInitializerRewrite.getAST());
0432: fNewLocationCuRewrite.getImportRemover()
0433: .registerAddedImports(newQualification);
0434:
0435: SimpleName newToQualify = (SimpleName) fInitializerRewrite
0436: .createMoveTarget(toQualify);
0437: Type newType = fInitializerRewrite.getAST()
0438: .newQualifiedType(newQualification,
0439: newToQualify);
0440: fInitializerRewrite.replace(toQualify, newType, null);
0441: }
0442:
0443: private static ITypeBinding getDeclaringClassBinding(
0444: SimpleName memberName) {
0445:
0446: IBinding binding = memberName.resolveBinding();
0447: if (binding instanceof IMethodBinding)
0448: return ((IMethodBinding) binding)
0449: .getDeclaringClass();
0450:
0451: if (binding instanceof IVariableBinding)
0452: return ((IVariableBinding) binding)
0453: .getDeclaringClass();
0454:
0455: if (binding instanceof ITypeBinding)
0456: return ((ITypeBinding) binding).getDeclaringClass();
0457:
0458: Assert.isTrue(false);
0459: return null;
0460:
0461: }
0462:
0463: }
0464:
0465: private final Expression fInitializer;
0466: private final ICompilationUnit fInitializerUnit;
0467: private final VariableDeclarationFragment fOriginalDeclaration;
0468:
0469: /** The references in this compilation unit, represented as AST Nodes in the parsed representation of the compilation unit */
0470: private final Expression[] fReferences;
0471: private final VariableDeclarationFragment fDeclarationToRemove;
0472: private final CompilationUnitRewrite fCuRewrite;
0473: private final TightSourceRangeComputer fSourceRangeComputer;
0474: private final HashSet fStaticImportsInInitializer;
0475: private final boolean fIs15;
0476:
0477: private InlineTargetCompilationUnit(
0478: CompilationUnitRewrite cuRewrite, Name[] references,
0479: InlineConstantRefactoring refactoring,
0480: HashSet staticImportsInInitializer)
0481: throws JavaModelException {
0482: fInitializer = refactoring.getInitializer();
0483: fInitializerUnit = refactoring
0484: .getDeclaringCompilationUnit();
0485:
0486: fCuRewrite = cuRewrite;
0487: fSourceRangeComputer = new TightSourceRangeComputer();
0488: fCuRewrite.getASTRewrite().setTargetSourceRangeComputer(
0489: fSourceRangeComputer);
0490: if (refactoring.getRemoveDeclaration()
0491: && refactoring.getReplaceAllReferences()
0492: && cuRewrite.getCu().equals(fInitializerUnit))
0493: fDeclarationToRemove = refactoring.getDeclaration();
0494: else
0495: fDeclarationToRemove = null;
0496:
0497: fOriginalDeclaration = refactoring.getDeclaration();
0498:
0499: fReferences = new Expression[references.length];
0500: for (int i = 0; i < references.length; i++)
0501: fReferences[i] = getQualifiedReference(references[i]);
0502:
0503: fIs15 = JavaModelUtil.is50OrHigher(cuRewrite.getCu()
0504: .getJavaProject());
0505: fStaticImportsInInitializer = fIs15 ? staticImportsInInitializer
0506: : new HashSet(0);
0507: }
0508:
0509: private static Expression getQualifiedReference(Name fieldName) {
0510: if (doesParentQualify(fieldName))
0511: return (Expression) fieldName.getParent();
0512:
0513: return fieldName;
0514: }
0515:
0516: private static boolean doesParentQualify(Name fieldName) {
0517: ASTNode parent = fieldName.getParent();
0518: Assert.isNotNull(parent);
0519:
0520: if (parent instanceof FieldAccess
0521: && ((FieldAccess) parent).getName() == fieldName)
0522: return true;
0523:
0524: if (parent instanceof QualifiedName
0525: && ((QualifiedName) parent).getName() == fieldName)
0526: return true;
0527:
0528: if (parent instanceof MethodInvocation
0529: && ((MethodInvocation) parent).getName() == fieldName)
0530: return true;
0531:
0532: return false;
0533: }
0534:
0535: public CompilationUnitChange getChange() throws CoreException {
0536: for (int i = 0; i < fReferences.length; i++)
0537: inlineReference(fReferences[i]);
0538:
0539: removeConstantDeclarationIfNecessary();
0540:
0541: return fCuRewrite.createChange();
0542: }
0543:
0544: private void inlineReference(Expression reference)
0545: throws CoreException {
0546: ASTNode importDecl = ASTNodes.getParent(reference,
0547: ImportDeclaration.class);
0548: if (importDecl != null)
0549: return; // don't inline into static imports
0550:
0551: String modifiedInitializer = prepareInitializerForLocation(reference);
0552: if (modifiedInitializer == null)
0553: return;
0554:
0555: TextEditGroup msg = fCuRewrite
0556: .createGroupDescription(RefactoringCoreMessages.InlineConstantRefactoring_Inline);
0557: Expression newReference = (Expression) fCuRewrite
0558: .getASTRewrite().createStringPlaceholder(
0559: modifiedInitializer,
0560: reference.getNodeType());
0561:
0562: if (fInitializer instanceof ArrayInitializer) {
0563: ArrayCreation arrayCreation = fCuRewrite.getAST()
0564: .newArrayCreation();
0565: ArrayType arrayType = (ArrayType) ASTNodeFactory
0566: .newType(fCuRewrite.getAST(),
0567: fOriginalDeclaration);
0568: arrayCreation.setType(arrayType);
0569:
0570: ArrayInitializer newArrayInitializer = (ArrayInitializer) fCuRewrite
0571: .getASTRewrite().createStringPlaceholder(
0572: modifiedInitializer,
0573: ASTNode.ARRAY_INITIALIZER);
0574: arrayCreation.setInitializer(newArrayInitializer);
0575: newReference = arrayCreation;
0576:
0577: ITypeBinding typeToAddToImport = ASTNodes.getType(
0578: fOriginalDeclaration).resolveBinding();
0579: fCuRewrite.getImportRewrite().addImport(
0580: typeToAddToImport);
0581: fCuRewrite.getImportRemover().registerAddedImport(
0582: typeToAddToImport.getName());
0583: }
0584:
0585: if (shouldParenthesizeSubstitute(fInitializer, reference)) {
0586: ParenthesizedExpression parenthesized = fCuRewrite
0587: .getAST().newParenthesizedExpression();
0588: parenthesized.setExpression(newReference);
0589: newReference = parenthesized;
0590: }
0591: fCuRewrite.getASTRewrite().replace(reference, newReference,
0592: msg);
0593: fSourceRangeComputer.addTightSourceNode(reference);
0594: fCuRewrite.getImportRemover()
0595: .registerRemovedNode(reference);
0596: }
0597:
0598: private String prepareInitializerForLocation(Expression location)
0599: throws CoreException {
0600: HashSet staticImportsInReference = new HashSet();
0601: final IJavaProject project = fCuRewrite.getCu()
0602: .getJavaProject();
0603: if (fIs15)
0604: location
0605: .accept(new ImportReferencesCollector(project,
0606: null, new ArrayList(),
0607: staticImportsInReference));
0608: InitializerTraversal traversal = new InitializerTraversal(
0609: fInitializer, fStaticImportsInInitializer,
0610: location, staticImportsInReference, fCuRewrite);
0611: ASTRewrite initializerRewrite = traversal
0612: .getInitializerRewrite();
0613: IDocument document = new Document(fInitializerUnit
0614: .getBuffer().getContents()); // could reuse document when generating and applying undo edits
0615:
0616: final RangeMarker marker = new RangeMarker(fInitializer
0617: .getStartPosition(), fInitializer.getLength());
0618: TextEdit[] rewriteEdits = initializerRewrite.rewriteAST(
0619: document,
0620: fInitializerUnit.getJavaProject().getOptions(true))
0621: .removeChildren();
0622: marker.addChildren(rewriteEdits);
0623: try {
0624: marker.apply(document, TextEdit.UPDATE_REGIONS);
0625: String rewrittenInitializer = document.get(marker
0626: .getOffset(), marker.getLength());
0627: IRegion region = document.getLineInformation(document
0628: .getLineOfOffset(marker.getOffset()));
0629: int oldIndent = Strings.computeIndentUnits(document
0630: .get(region.getOffset(), region.getLength()),
0631: project);
0632: return Strings
0633: .changeIndent(
0634: rewrittenInitializer,
0635: oldIndent,
0636: project,
0637: "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
0638: } catch (MalformedTreeException e) {
0639: JavaPlugin.log(e);
0640: } catch (BadLocationException e) {
0641: JavaPlugin.log(e);
0642: }
0643: return fInitializerUnit.getBuffer().getText(
0644: fInitializer.getStartPosition(),
0645: fInitializer.getLength());
0646: }
0647:
0648: private static boolean shouldParenthesizeSubstitute(
0649: Expression substitute, Expression location) {
0650: if (substitute instanceof Assignment) // for esthetic reasons
0651: return true;
0652: else
0653: return ASTNodes.substituteMustBeParenthesized(
0654: substitute, location);
0655: }
0656:
0657: private void removeConstantDeclarationIfNecessary()
0658: throws CoreException {
0659: if (fDeclarationToRemove == null)
0660: return;
0661:
0662: FieldDeclaration parentDeclaration = (FieldDeclaration) fDeclarationToRemove
0663: .getParent();
0664: ASTNode toRemove;
0665: if (parentDeclaration.fragments().size() == 1)
0666: toRemove = parentDeclaration;
0667: else
0668: toRemove = fDeclarationToRemove;
0669:
0670: TextEditGroup msg = fCuRewrite
0671: .createGroupDescription(RefactoringCoreMessages.InlineConstantRefactoring_remove_declaration);
0672: fCuRewrite.getASTRewrite().remove(toRemove, msg);
0673: fCuRewrite.getImportRemover().registerRemovedNode(toRemove);
0674: }
0675: }
0676:
0677: // ---- End InlineTargetCompilationUnit ----------------------------------------------------------------------------------------------
0678:
0679: private static SimpleName getLeftmost(Name name) {
0680: if (name instanceof SimpleName)
0681: return (SimpleName) name;
0682:
0683: return getLeftmost(((QualifiedName) name).getQualifier());
0684: }
0685:
0686: private int fSelectionStart;
0687: private int fSelectionLength;
0688:
0689: private ICompilationUnit fSelectionCu;
0690: private CompilationUnitRewrite fSelectionCuRewrite;
0691: private Name fSelectedConstantName;
0692:
0693: private IField fField;
0694: private CompilationUnitRewrite fDeclarationCuRewrite;
0695: private VariableDeclarationFragment fDeclaration;
0696: private boolean fDeclarationSelected;
0697: private boolean fDeclarationSelectedChecked = false;
0698: private boolean fInitializerAllStaticFinal;
0699: private boolean fInitializerChecked = false;
0700:
0701: private boolean fRemoveDeclaration = false;
0702: private boolean fReplaceAllReferences = true;
0703:
0704: private CompilationUnitChange[] fChanges;
0705:
0706: /**
0707: * Creates a new inline constant refactoring.
0708: * <p>
0709: * This constructor is only used by <code>DelegateCreator</code>.
0710: * </p>
0711: *
0712: * @param field the field to inline
0713: */
0714: public InlineConstantRefactoring(IField field) {
0715: Assert.isNotNull(field);
0716: Assert.isTrue(!field.isBinary());
0717: fField = field;
0718: }
0719:
0720: /**
0721: * Creates a new inline constant refactoring.
0722: * @param unit the compilation unit, or <code>null</code> if invoked by scripting
0723: * @param node the compilation unit node, or <code>null</code> if invoked by scripting
0724: * @param selectionStart
0725: * @param selectionLength
0726: */
0727: public InlineConstantRefactoring(ICompilationUnit unit,
0728: CompilationUnit node, int selectionStart,
0729: int selectionLength) {
0730: Assert.isTrue(selectionStart >= 0);
0731: Assert.isTrue(selectionLength >= 0);
0732: fSelectionCu = unit;
0733: fSelectionStart = selectionStart;
0734: fSelectionLength = selectionLength;
0735: if (unit != null)
0736: initialize(unit, node);
0737: }
0738:
0739: private void initialize(ICompilationUnit cu, CompilationUnit node) {
0740: fSelectionCuRewrite = new CompilationUnitRewrite(cu, node);
0741: fSelectedConstantName = findConstantNameNode();
0742: }
0743:
0744: private Name findConstantNameNode() {
0745: ASTNode node = NodeFinder.perform(
0746: fSelectionCuRewrite.getRoot(), fSelectionStart,
0747: fSelectionLength);
0748: if (node == null)
0749: return null;
0750: if (node instanceof FieldAccess)
0751: node = ((FieldAccess) node).getName();
0752: if (node.getParent() instanceof EnumConstantDeclaration)
0753: return null;
0754: if (!(node instanceof Name))
0755: return null;
0756: Name name = (Name) node;
0757: IBinding binding = name.resolveBinding();
0758: if (!(binding instanceof IVariableBinding))
0759: return null;
0760: IVariableBinding variableBinding = (IVariableBinding) binding;
0761: if (!variableBinding.isField()
0762: || variableBinding.isEnumConstant())
0763: return null;
0764: int modifiers = binding.getModifiers();
0765: if (!(Modifier.isStatic(modifiers) && Modifier
0766: .isFinal(modifiers)))
0767: return null;
0768:
0769: return name;
0770: }
0771:
0772: public RefactoringStatus checkStaticFinalConstantNameSelected() {
0773: if (fSelectedConstantName == null)
0774: return RefactoringStatus
0775: .createStatus(
0776: RefactoringStatus.FATAL,
0777: RefactoringCoreMessages.InlineConstantRefactoring_static_final_field,
0778: null,
0779: Corext.getPluginId(),
0780: RefactoringStatusCodes.NOT_STATIC_FINAL_SELECTED,
0781: null);
0782:
0783: return new RefactoringStatus();
0784: }
0785:
0786: public String getName() {
0787: return RefactoringCoreMessages.InlineConstantRefactoring_name;
0788: }
0789:
0790: public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
0791: throws CoreException {
0792: try {
0793: pm.beginTask("", 3); //$NON-NLS-1$
0794:
0795: if (!fSelectionCu.isStructureKnown())
0796: return RefactoringStatus
0797: .createStatus(
0798: RefactoringStatus.FATAL,
0799: RefactoringCoreMessages.InlineConstantRefactoring_syntax_errors,
0800: null, Corext.getPluginId(),
0801: RefactoringStatusCodes.SYNTAX_ERRORS,
0802: null);
0803:
0804: RefactoringStatus result = checkStaticFinalConstantNameSelected();
0805: if (result.hasFatalError())
0806: return result;
0807:
0808: result.merge(findField());
0809: if (result.hasFatalError())
0810: return result;
0811: pm.worked(1);
0812:
0813: result.merge(findDeclaration());
0814: if (result.hasFatalError())
0815: return result;
0816: pm.worked(1);
0817:
0818: result.merge(checkInitializer());
0819: if (result.hasFatalError())
0820: return result;
0821: pm.worked(1);
0822:
0823: return result;
0824:
0825: } finally {
0826: pm.done();
0827: }
0828: }
0829:
0830: private RefactoringStatus findField() throws JavaModelException {
0831: fField = (IField) ((IVariableBinding) fSelectedConstantName
0832: .resolveBinding()).getJavaElement();
0833: if (fField != null && !fField.exists())
0834: return RefactoringStatus
0835: .createStatus(
0836: RefactoringStatus.FATAL,
0837: RefactoringCoreMessages.InlineConstantRefactoring_local_anonymous_unsupported,
0838: null,
0839: Corext.getPluginId(),
0840: RefactoringStatusCodes.LOCAL_AND_ANONYMOUS_NOT_SUPPORTED,
0841: null);
0842:
0843: return null;
0844: }
0845:
0846: private RefactoringStatus findDeclaration()
0847: throws JavaModelException {
0848: fDeclarationSelectedChecked = true;
0849: fDeclarationSelected = false;
0850: ASTNode parent = fSelectedConstantName.getParent();
0851: if (parent instanceof VariableDeclarationFragment) {
0852: VariableDeclarationFragment parentDeclaration = (VariableDeclarationFragment) parent;
0853: if (parentDeclaration.getName() == fSelectedConstantName) {
0854: fDeclarationSelected = true;
0855: fDeclarationCuRewrite = fSelectionCuRewrite;
0856: fDeclaration = (VariableDeclarationFragment) fSelectedConstantName
0857: .getParent();
0858: return null;
0859: }
0860: }
0861:
0862: VariableDeclarationFragment declaration = (VariableDeclarationFragment) fSelectionCuRewrite
0863: .getRoot().findDeclaringNode(
0864: fSelectedConstantName.resolveBinding());
0865: if (declaration != null) {
0866: fDeclarationCuRewrite = fSelectionCuRewrite;
0867: fDeclaration = declaration;
0868: return null;
0869: }
0870:
0871: if (fField.getCompilationUnit() == null)
0872: return RefactoringStatus
0873: .createStatus(
0874: RefactoringStatus.FATAL,
0875: RefactoringCoreMessages.InlineConstantRefactoring_binary_file,
0876: null,
0877: Corext.getPluginId(),
0878: RefactoringStatusCodes.DECLARED_IN_CLASSFILE,
0879: null);
0880:
0881: fDeclarationCuRewrite = new CompilationUnitRewrite(fField
0882: .getCompilationUnit());
0883: fDeclaration = ASTNodeSearchUtil
0884: .getFieldDeclarationFragmentNode(fField,
0885: fDeclarationCuRewrite.getRoot());
0886: return null;
0887: }
0888:
0889: private RefactoringStatus checkInitializer() {
0890: Expression initializer = getInitializer();
0891: if (initializer == null)
0892: return RefactoringStatus
0893: .createStatus(
0894: RefactoringStatus.FATAL,
0895: RefactoringCoreMessages.InlineConstantRefactoring_blank_finals,
0896: null,
0897: Corext.getPluginId(),
0898: RefactoringStatusCodes.CANNOT_INLINE_BLANK_FINAL,
0899: null);
0900:
0901: fInitializerAllStaticFinal = ConstantChecks
0902: .isStaticFinalConstant((IExpressionFragment) ASTFragmentFactory
0903: .createFragmentForFullSubtree(initializer));
0904: fInitializerChecked = true;
0905: return new RefactoringStatus();
0906: }
0907:
0908: private VariableDeclarationFragment getDeclaration()
0909: throws JavaModelException {
0910: return fDeclaration;
0911: }
0912:
0913: private Expression getInitializer() {
0914: return fDeclaration.getInitializer();
0915: }
0916:
0917: private ICompilationUnit getDeclaringCompilationUnit()
0918: throws JavaModelException {
0919: return fField.getCompilationUnit();
0920: }
0921:
0922: public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
0923: throws CoreException {
0924: RefactoringStatus result = new RefactoringStatus();
0925: pm.beginTask("", 3); //$NON-NLS-1$
0926:
0927: try {
0928: List/*<CompilationUnitChange>*/changes = new ArrayList();
0929: HashSet staticImportsInInitializer = new HashSet();
0930: ImportReferencesCollector importReferencesCollector = new ImportReferencesCollector(
0931: fField.getJavaProject(), null, new ArrayList(),
0932: staticImportsInInitializer);
0933: getInitializer().accept(importReferencesCollector);
0934:
0935: if (getReplaceAllReferences()) {
0936: SearchResultGroup[] searchResultGroups = findReferences(
0937: pm, result);
0938: for (int i = 0; i < searchResultGroups.length; i++) {
0939: if (pm.isCanceled())
0940: throw new OperationCanceledException();
0941: SearchResultGroup group = searchResultGroups[i];
0942: ICompilationUnit cu = group.getCompilationUnit();
0943:
0944: CompilationUnitRewrite cuRewrite = getCuRewrite(cu);
0945: Name[] references = extractReferenceNodes(group
0946: .getSearchResults(), cuRewrite.getRoot());
0947: InlineTargetCompilationUnit targetCompilationUnit = new InlineTargetCompilationUnit(
0948: cuRewrite, references, this ,
0949: staticImportsInInitializer);
0950: changes.add(targetCompilationUnit.getChange());
0951: }
0952:
0953: } else {
0954: Assert.isTrue(!isDeclarationSelected());
0955: InlineTargetCompilationUnit targetForOnlySelectedReference = new InlineTargetCompilationUnit(
0956: fSelectionCuRewrite,
0957: new Name[] { fSelectedConstantName }, this ,
0958: staticImportsInInitializer);
0959: changes.add(targetForOnlySelectedReference.getChange());
0960: }
0961:
0962: if (result.hasFatalError())
0963: return result;
0964:
0965: if (getRemoveDeclaration() && getReplaceAllReferences()) {
0966: boolean declarationRemoved = false;
0967: for (Iterator iter = changes.iterator(); iter.hasNext();) {
0968: CompilationUnitChange change = (CompilationUnitChange) iter
0969: .next();
0970: if (change.getCompilationUnit().equals(
0971: fDeclarationCuRewrite.getCu())) {
0972: declarationRemoved = true;
0973: break;
0974: }
0975: }
0976: if (!declarationRemoved) {
0977: InlineTargetCompilationUnit targetForDeclaration = new InlineTargetCompilationUnit(
0978: fDeclarationCuRewrite, new Name[0], this ,
0979: staticImportsInInitializer);
0980: CompilationUnitChange change = targetForDeclaration
0981: .getChange();
0982: if (change != null)
0983: changes.add(change);
0984: }
0985: }
0986:
0987: ICompilationUnit[] cus = new ICompilationUnit[changes
0988: .size()];
0989: for (int i = 0; i < changes.size(); i++) {
0990: CompilationUnitChange change = (CompilationUnitChange) changes
0991: .get(i);
0992: cus[i] = change.getCompilationUnit();
0993: }
0994: result.merge(Checks.validateModifiesFiles(ResourceUtil
0995: .getFiles(cus), getValidationContext()));
0996:
0997: pm.worked(1);
0998:
0999: fChanges = (CompilationUnitChange[]) changes
1000: .toArray(new CompilationUnitChange[changes.size()]);
1001:
1002: return result;
1003:
1004: } finally {
1005: fSelectionCuRewrite = null;
1006: fSelectedConstantName = null;
1007: fDeclarationCuRewrite = null;
1008: fDeclaration = null;
1009: pm.done();
1010: }
1011: }
1012:
1013: private Name[] extractReferenceNodes(SearchMatch[] searchResults,
1014: CompilationUnit cuNode) {
1015: Name[] references = new Name[searchResults.length];
1016: for (int i = 0; i < searchResults.length; i++)
1017: references[i] = (Name) NodeFinder.perform(cuNode,
1018: searchResults[i].getOffset(), searchResults[i]
1019: .getLength());
1020: return references;
1021: }
1022:
1023: private CompilationUnitRewrite getCuRewrite(ICompilationUnit cu) {
1024: CompilationUnitRewrite cuRewrite;
1025: if (cu.equals(fSelectionCu)) {
1026: cuRewrite = fSelectionCuRewrite;
1027: } else if (cu.equals(fField.getCompilationUnit())) {
1028: cuRewrite = fDeclarationCuRewrite;
1029: } else {
1030: cuRewrite = new CompilationUnitRewrite(cu);
1031: }
1032: return cuRewrite;
1033: }
1034:
1035: private SearchResultGroup[] findReferences(IProgressMonitor pm,
1036: RefactoringStatus status) throws JavaModelException {
1037: final RefactoringSearchEngine2 engine = new RefactoringSearchEngine2(
1038: SearchPattern.createPattern(fField,
1039: IJavaSearchConstants.REFERENCES));
1040: engine.setFiltering(true, true);
1041: engine.setScope(RefactoringScopeFactory.create(fField));
1042: engine.setStatus(status);
1043: engine.setRequestor(new IRefactoringSearchRequestor() {
1044: public SearchMatch acceptSearchMatch(SearchMatch match) {
1045: return match.isInsideDocComment() ? null : match;
1046: }
1047: });
1048: engine.searchPattern(new SubProgressMonitor(pm, 1));
1049: return (SearchResultGroup[]) engine.getResults();
1050: }
1051:
1052: public Change createChange(IProgressMonitor pm)
1053: throws CoreException {
1054: try {
1055: pm
1056: .beginTask(
1057: RefactoringCoreMessages.InlineConstantRefactoring_preview,
1058: 2);
1059: final Map arguments = new HashMap();
1060: String project = null;
1061: IJavaProject javaProject = fSelectionCu.getJavaProject();
1062: if (javaProject != null)
1063: project = javaProject.getElementName();
1064: int flags = RefactoringDescriptor.STRUCTURAL_CHANGE
1065: | JavaRefactoringDescriptor.JAR_REFACTORING
1066: | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
1067: try {
1068: if (!Flags.isPrivate(fField.getFlags()))
1069: flags |= RefactoringDescriptor.MULTI_CHANGE;
1070: } catch (JavaModelException exception) {
1071: JavaPlugin.log(exception);
1072: }
1073: final String description = Messages
1074: .format(
1075: RefactoringCoreMessages.InlineConstantRefactoring_descriptor_description_short,
1076: fField.getElementName());
1077: final String header = Messages
1078: .format(
1079: RefactoringCoreMessages.InlineConstantRefactoring_descriptor_description,
1080: new String[] {
1081: JavaElementLabels
1082: .getElementLabel(
1083: fField,
1084: JavaElementLabels.ALL_FULLY_QUALIFIED),
1085: JavaElementLabels
1086: .getElementLabel(
1087: fField.getParent(),
1088: JavaElementLabels.ALL_FULLY_QUALIFIED) });
1089: final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(
1090: project, this , header);
1091: comment
1092: .addSetting(Messages
1093: .format(
1094: RefactoringCoreMessages.InlineConstantRefactoring_original_pattern,
1095: JavaElementLabels
1096: .getElementLabel(
1097: fField,
1098: JavaElementLabels.ALL_FULLY_QUALIFIED)));
1099: if (fRemoveDeclaration)
1100: comment
1101: .addSetting(RefactoringCoreMessages.InlineConstantRefactoring_remove_declaration);
1102: if (fReplaceAllReferences)
1103: comment
1104: .addSetting(RefactoringCoreMessages.InlineConstantRefactoring_replace_references);
1105: final InlineConstantDescriptor descriptor = new InlineConstantDescriptor(
1106: project, description, comment.asString(),
1107: arguments, flags);
1108: arguments.put(
1109: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT,
1110: JavaRefactoringDescriptorUtil.elementToHandle(
1111: project, fSelectionCu));
1112: arguments
1113: .put(
1114: JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION,
1115: new Integer(fSelectionStart).toString()
1116: + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
1117: arguments.put(ATTRIBUTE_REMOVE, Boolean.valueOf(
1118: fRemoveDeclaration).toString());
1119: arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(
1120: fReplaceAllReferences).toString());
1121: return new DynamicValidationRefactoringChange(
1122: descriptor,
1123: RefactoringCoreMessages.InlineConstantRefactoring_inline,
1124: fChanges);
1125: } finally {
1126: pm.done();
1127: fChanges = null;
1128: }
1129: }
1130:
1131: private void checkInvariant() {
1132: if (isDeclarationSelected())
1133: Assert.isTrue(fReplaceAllReferences);
1134: }
1135:
1136: public boolean getRemoveDeclaration() {
1137: return fRemoveDeclaration;
1138: }
1139:
1140: public boolean getReplaceAllReferences() {
1141: checkInvariant();
1142: return fReplaceAllReferences;
1143: }
1144:
1145: public boolean isDeclarationSelected() {
1146: Assert.isTrue(fDeclarationSelectedChecked);
1147: return fDeclarationSelected;
1148: }
1149:
1150: public boolean isInitializerAllStaticFinal() {
1151: Assert.isTrue(fInitializerChecked);
1152: return fInitializerAllStaticFinal;
1153: }
1154:
1155: public void setRemoveDeclaration(boolean removeDeclaration) {
1156: fRemoveDeclaration = removeDeclaration;
1157: }
1158:
1159: public void setReplaceAllReferences(boolean replaceAllReferences) {
1160: fReplaceAllReferences = replaceAllReferences;
1161: checkInvariant();
1162: }
1163:
1164: public RefactoringStatus initialize(
1165: final RefactoringArguments arguments) {
1166: if (arguments instanceof JavaRefactoringArguments) {
1167: final JavaRefactoringArguments extended = (JavaRefactoringArguments) arguments;
1168: final String selection = extended
1169: .getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
1170: if (selection != null) {
1171: int offset = -1;
1172: int length = -1;
1173: final StringTokenizer tokenizer = new StringTokenizer(
1174: selection);
1175: if (tokenizer.hasMoreTokens())
1176: offset = Integer.valueOf(tokenizer.nextToken())
1177: .intValue();
1178: if (tokenizer.hasMoreTokens())
1179: length = Integer.valueOf(tokenizer.nextToken())
1180: .intValue();
1181: if (offset >= 0 && length >= 0) {
1182: fSelectionStart = offset;
1183: fSelectionLength = length;
1184: } else
1185: return RefactoringStatus
1186: .createFatalErrorStatus(Messages
1187: .format(
1188: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
1189: new Object[] {
1190: selection,
1191: JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION }));
1192: }
1193: final String handle = extended
1194: .getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
1195: if (handle != null) {
1196: final IJavaElement element = JavaRefactoringDescriptorUtil
1197: .handleToElement(extended.getProject(), handle,
1198: false);
1199: if (element == null || !element.exists())
1200: return createInputFatalStatus(element,
1201: IJavaRefactorings.INLINE_CONSTANT);
1202: else {
1203: if (element instanceof ICompilationUnit) {
1204: fSelectionCu = (ICompilationUnit) element;
1205: if (selection == null)
1206: return RefactoringStatus
1207: .createFatalErrorStatus(Messages
1208: .format(
1209: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1210: JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
1211: } else if (element instanceof IField) {
1212: final IField field = (IField) element;
1213: try {
1214: final ISourceRange range = field
1215: .getNameRange();
1216: if (range != null) {
1217: fSelectionStart = range.getOffset();
1218: fSelectionLength = range.getLength();
1219: } else
1220: return RefactoringStatus
1221: .createFatalErrorStatus(Messages
1222: .format(
1223: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1224: IJavaRefactorings.INLINE_CONSTANT));
1225: } catch (JavaModelException exception) {
1226: return createInputFatalStatus(element,
1227: IJavaRefactorings.INLINE_CONSTANT);
1228: }
1229: fSelectionCu = field.getCompilationUnit();
1230: } else
1231: return RefactoringStatus
1232: .createFatalErrorStatus(Messages
1233: .format(
1234: RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
1235: new Object[] {
1236: handle,
1237: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT }));
1238: final ASTParser parser = ASTParser
1239: .newParser(AST.JLS3);
1240: parser.setResolveBindings(true);
1241: parser.setSource(fSelectionCu);
1242: final CompilationUnit unit = (CompilationUnit) parser
1243: .createAST(null);
1244: initialize(fSelectionCu, unit);
1245: if (checkStaticFinalConstantNameSelected()
1246: .hasFatalError())
1247: return createInputFatalStatus(element,
1248: IJavaRefactorings.INLINE_CONSTANT);
1249: }
1250: } else
1251: return RefactoringStatus
1252: .createFatalErrorStatus(Messages
1253: .format(
1254: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1255: JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
1256: final String replace = extended
1257: .getAttribute(ATTRIBUTE_REPLACE);
1258: if (replace != null) {
1259: fReplaceAllReferences = Boolean.valueOf(replace)
1260: .booleanValue();
1261: } else
1262: return RefactoringStatus
1263: .createFatalErrorStatus(Messages
1264: .format(
1265: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1266: ATTRIBUTE_REPLACE));
1267: final String remove = extended
1268: .getAttribute(ATTRIBUTE_REMOVE);
1269: if (remove != null)
1270: fRemoveDeclaration = Boolean.valueOf(remove)
1271: .booleanValue();
1272: else
1273: return RefactoringStatus
1274: .createFatalErrorStatus(Messages
1275: .format(
1276: RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
1277: ATTRIBUTE_REMOVE));
1278: } else
1279: return RefactoringStatus
1280: .createFatalErrorStatus(RefactoringCoreMessages.InitializableRefactoring_inacceptable_arguments);
1281: return new RefactoringStatus();
1282: }
1283: }
|