public Collection<PsiElement> getAdditionalElementsToDelete( @NotNull final PsiElement element, @NotNull final Collection<PsiElement> allElementsToDelete, final boolean askUser) { if (element instanceof PsiField) { PsiField field = (PsiField) element; final Project project = element.getProject(); String propertyName = JavaCodeStyleManager.getInstance(project) .variableNameToPropertyName(field.getName(), VariableKind.FIELD); PsiClass aClass = field.getContainingClass(); if (aClass != null) { boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic); if (getters != null) { final List<PsiMethod> validGetters = new ArrayList<>(1); for (PsiMethod getter : getters) { if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) { validGetters.add(getter); } } getters = validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]); } PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false); if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical()) setter = null; if (askUser && (getters != null || setter != null)) { final String message = RefactoringMessageUtil.getGetterSetterMessage( field.getName(), RefactoringBundle.message("delete.title"), getters != null ? getters[0] : null, setter); if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog( project, message, RefactoringBundle.message("safe.delete.title"), Messages.getQuestionIcon()) != Messages.YES) { getters = null; setter = null; } } List<PsiElement> elements = new ArrayList<>(); if (setter != null) elements.add(setter); if (getters != null) Collections.addAll(elements, getters); return elements; } } return null; }
@Override protected boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) { final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); myExtractEnumProcessor.findEnumConstantConflicts(refUsages); if (!DestinationFolderComboBox.isAccessible( myProject, sourceClass.getContainingFile().getVirtualFile(), myClass.getContainingFile().getContainingDirectory().getVirtualFile())) { conflicts.putValue( sourceClass, "Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true)); } ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { myClass.delete(); } }); final Project project = sourceClass.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass existingClass = JavaPsiFacade.getInstance(project).findClass(getQualifiedName(), scope); if (existingClass != null) { conflicts.putValue( existingClass, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message("there.already.exists.a.class.with.the.chosen.name")); } if (!myGenerateAccessors) { calculateInitializersConflicts(conflicts); final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass(); final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass(); final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<PsiField>(); fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter()); fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter()); for (PsiField field : fieldsNeedingGetter) { conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter"); } final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<PsiField>(); fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter()); fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter()); for (PsiField field : fieldsNeedingSetter) { conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter"); } } checkConflicts(refUsages, conflicts); return showConflicts(conflicts, refUsages.get()); }
@Nullable static HighlightInfo checkFinalFieldInitialized(@NotNull PsiField field) { if (!field.hasModifierProperty(PsiModifier.FINAL)) return null; if (isFieldInitializedAfterObjectConstruction(field)) return null; String description = JavaErrorMessages.message("variable.not.initialized", field.getName()); TextRange range = HighlightNamesUtil.getFieldDeclarationTextRange(field); HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) .range(range) .descriptionAndTooltip(description) .create(); QuickFixAction.registerQuickFixAction( highlightInfo, HighlightMethodUtil.getFixRange(field), QUICK_FIX_FACTORY.createCreateConstructorParameterFromFieldFix(field)); QuickFixAction.registerQuickFixAction( highlightInfo, HighlightMethodUtil.getFixRange(field), QUICK_FIX_FACTORY.createInitializeFinalFieldInConstructorFix(field)); final PsiClass containingClass = field.getContainingClass(); if (containingClass != null && !containingClass.isInterface()) { QuickFixAction.registerQuickFixAction( highlightInfo, QUICK_FIX_FACTORY.createModifierListFix(field, PsiModifier.FINAL, false, false)); } QuickFixAction.registerQuickFixAction( highlightInfo, QUICK_FIX_FACTORY.createAddVariableInitializerFix(field)); return highlightInfo; }
private static PsiField convertFieldToLanguage(PsiField field, Language language) { if (field.getLanguage().equals(language)) { return field; } return JVMElementFactories.getFactory(language, field.getProject()) .createField(field.getName(), field.getType()); }
@Override public void visitField(PsiField field) { // There is a possible case that more than one field is declared for the same type like 'int i, // j;'. We want to process only // the first one then. PsiElement fieldPrev = getPreviousNonWsComment(field.getPrevSibling(), 0); if (fieldPrev instanceof PsiJavaToken && ((PsiJavaToken) fieldPrev).getTokenType() == JavaTokenType.COMMA) { return; } // There is a possible case that fields which share the same type declaration are located on // different document lines, e.g.: // int i1, // i2; // We want to consider only the first declaration then but need to expand its range to all // affected lines (up to semicolon). TextRange range = field.getTextRange(); PsiElement child = field.getLastChild(); boolean needSpecialProcessing = true; if (isSemicolon(child)) { needSpecialProcessing = false; } else if (child instanceof PsiComment) { // There is a possible field definition like below: // int f; // my comment. // The comment goes into field PSI here, that's why we need to handle it properly. PsiElement prev = getPreviousNonWsComment(child, range.getStartOffset()); needSpecialProcessing = prev != null && !isSemicolon(prev); } if (needSpecialProcessing) { for (PsiElement e = field.getNextSibling(); e != null; e = e.getNextSibling()) { if (e instanceof PsiWhiteSpace || e instanceof PsiComment) { // Skip white space and comment continue; } else if (e instanceof PsiJavaToken) { if (((PsiJavaToken) e).getTokenType() == JavaTokenType.COMMA) { // Skip comma continue; } else { break; } } else if (e instanceof PsiField) { PsiElement c = e.getLastChild(); if (c != null) { c = getPreviousNonWsComment(c, range.getStartOffset()); } // Stop if current field ends by a semicolon. if (c instanceof PsiErrorElement // Incomplete field without trailing semicolon || (c instanceof PsiJavaToken && ((PsiJavaToken) c).getTokenType() == JavaTokenType.SEMICOLON)) { range = TextRange.create(range.getStartOffset(), c.getTextRange().getEndOffset()); } else { continue; } } break; } } JavaElementArrangementEntry entry = createNewEntry(field, range, FIELD, field.getName(), true); processEntry(entry, field, field.getInitializer()); }
public static void checkFieldConflicts( @Nullable PsiClass aClass, String newName, final Map<PsiElement, String> conflicts) { PsiField existingField = aClass != null ? aClass.findFieldByName(newName, true) : null; if (existingField != null) { if (aClass.equals(existingField.getContainingClass())) { String className = aClass instanceof PsiAnonymousClass ? RefactoringBundle.message("current.class") : RefactoringUIUtil.getDescription(aClass, false); final String conflict = RefactoringBundle.message( "field.0.is.already.defined.in.the.1", existingField.getName(), className); conflicts.put(existingField, conflict); } else { // method somewhere in base class if (!existingField.hasModifierProperty(PsiModifier.PRIVATE)) { String fieldInfo = PsiFormatUtil.formatVariable( existingField, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.TYPE_AFTER, PsiSubstitutor.EMPTY); String className = RefactoringUIUtil.getDescription(existingField.getContainingClass(), false); final String descr = RefactoringBundle.message( "field.0.will.hide.field.1.of.the.base.class", newName, fieldInfo, className); conflicts.put(existingField, descr); } } } }
private void processUsagesForMethod( final boolean deleteMethodHierarchy, PsiMethod method, int[] paramPermutation, String getterName, PsiMethod delegatedMethod, List<FixableUsageInfo> usages) { for (PsiReference reference : ReferencesSearch.search(method)) { final PsiElement referenceElement = reference.getElement(); final PsiMethodCallExpression call = (PsiMethodCallExpression) referenceElement.getParent(); final String access; if (call.getMethodExpression().getQualifierExpression() == null) { access = field.getName(); } else { access = getterName + "()"; if (getter == null) { getter = GenerateMembersUtil.generateGetterPrototype(field); } } usages.add( new InlineDelegatingCall(call, paramPermutation, access, delegatedMethod.getName())); } if (deleteMethodHierarchy) { usages.add(new DeleteMethod(method)); } }
@Override public LightRef asLightUsage(@NotNull PsiElement element, @NotNull ByteArrayEnumerator names) { if (mayBeVisibleOutsideOwnerFile(element)) { if (element instanceof PsiField) { final PsiField field = (PsiField) element; final PsiClass aClass = field.getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); final String name = field.getName(); if (name == null || jvmOwnerName == null) return null; return new LightRef.JavaLightFieldRef(id(jvmOwnerName, names), id(name, names)); } else if (element instanceof PsiMethod) { final PsiClass aClass = ((PsiMethod) element).getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); if (jvmOwnerName == null) return null; final PsiMethod method = (PsiMethod) element; final String name = method.isConstructor() ? "<init>" : method.getName(); final int parametersCount = method.getParameterList().getParametersCount(); return new LightRef.JavaLightMethodRef( id(jvmOwnerName, names), id(name, names), parametersCount); } else if (element instanceof PsiClass) { final String jvmClassName = ClassUtil.getJVMClassName((PsiClass) element); if (jvmClassName != null) { return new LightRef.JavaLightClassRef(id(jvmClassName, names)); } } } return null; }
private static String gettext(PsiField field, PsiType uiComponentType) { return UIDesignerBundle.message( "action.change.field.type", field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()); }
private static PsiAnnotationMemberValue[] readFromClass( @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) { PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName); PsiType fromClassType = fromClassAttr instanceof PsiClassObjectAccessExpression ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType() : null; PsiClass fromClass = fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null; if (fromClass == null) return null; String fqn = fromClass.getQualifiedName(); if (fqn == null) return null; List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>(); for (PsiField field : fromClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.PUBLIC) || !field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) continue; PsiType fieldType = field.getType(); if (!Comparing.equal(fieldType, type)) continue; PsiAssignmentExpression e = (PsiAssignmentExpression) JavaPsiFacade.getElementFactory(field.getProject()) .createExpressionFromText("x=" + fqn + "." + field.getName(), field); PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression(); constants.add(refToField); } if (constants.isEmpty()) return null; return constants.toArray(new PsiAnnotationMemberValue[constants.size()]); }
private void checkEnumConstant(String expectedName, PsiField field) { assertTrue(field instanceof PsiEnumConstant); assertEquals(expectedName, field.getName()); assertTrue(field.hasModifierProperty(PsiModifier.PUBLIC)); assertTrue(field.hasModifierProperty(PsiModifier.FINAL)); assertTrue(field.hasModifierProperty(PsiModifier.STATIC)); }
@NonNls private static String computeConstantBooleanText(PsiExpression expression) { if (!(expression instanceof PsiReferenceExpression)) { return null; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression; final PsiElement target = referenceExpression.resolve(); if (!(target instanceof PsiField)) { return null; } final PsiField field = (PsiField) target; final PsiClass containingClass = field.getContainingClass(); if (containingClass == null) { return null; } final String qualifiedName = containingClass.getQualifiedName(); if (!CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)) { return null; } @NonNls final String name = field.getName(); if ("TRUE".equals(name)) { return "true"; } else if ("FALSE".equals(name)) { return "false"; } else { return null; } }
/** Create fields for injections inside main class */ protected void generateFields() { for (Iterator<Element> iterator = mElements.iterator(); iterator.hasNext(); ) { Element element = iterator.next(); if (!element.used) { iterator.remove(); continue; } // remove duplicate field PsiField[] fields = mClass.getFields(); boolean duplicateField = false; for (PsiField field : fields) { String name = field.getName(); if (name != null && name.equals(element.getFieldName())) { duplicateField = true; break; } } if (duplicateField) { iterator.remove(); continue; } mClass.add( mFactory.createFieldFromText( "private " + element.name + " " + element.getFieldName() + ";", mClass)); } }
public VariableLookupItem(PsiField field, boolean shouldImport) { super(field, field.getName()); myHelper = new MemberLookupHelper(field, field.getContainingClass(), shouldImport, false); if (!shouldImport) { forceQualify(); } }
@Override public PsiField findFieldByName(@NonNls String name, boolean checkBases) { final PsiField[] fields = getFields(); for (final PsiField field : fields) { if (name.equals(field.getName())) return field; } return null; }
/** * judge field exists * * @param part * @return */ private boolean fieldExist(ViewPart part) { PsiField[] fields = mClass.getAllFields(); for (PsiField field : fields) { if (field.getName().equals(part.getName())) { return true; } } return false; }
private boolean existsFieldWithName(String name) { final PsiField[] allFields = sourceClass.getAllFields(); for (PsiField field : allFields) { if (name.equals(field.getName()) && !fields.contains(field)) { return true; } } return false; }
@NotNull private Field fieldToField(@NotNull PsiField field, PsiClass psiClass) { Set<String> modifiers = modifiersListToModifiersSet(field.getModifierList()); if (field instanceof PsiEnumConstant) // TODO: remove instanceof { return new EnumConstant( new IdentifierImpl(field.getName()), // TODO modifiers, typeToType(field.getType()), elementToElement(((PsiEnumConstant) field).getArgumentList())); } return new Field( new IdentifierImpl(field.getName()), // TODO modifiers, typeToType(field.getType(), ConverterUtil.isAnnotatedAsNotNull(field.getModifierList())), createSureCallOnlyForChain(field.getInitializer(), field.getType()), // TODO: add modifiers countWritingAccesses(field, psiClass)); }
private static PsiStatement addInitializationToConstructors( PsiLocalVariable local, PsiField field, PsiMethod enclosingConstructor, PsiElementFactory factory) throws IncorrectOperationException { PsiClass aClass = field.getContainingClass(); PsiMethod[] constructors = aClass.getConstructors(); PsiStatement assignment = createAssignment(local, field.getName(), factory); boolean added = false; for (PsiMethod constructor : constructors) { if (constructor == enclosingConstructor) continue; PsiCodeBlock body = constructor.getBody(); if (body == null) continue; PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { PsiStatement first = statements[0]; if (first instanceof PsiExpressionStatement) { PsiExpression expression = ((PsiExpressionStatement) first).getExpression(); if (expression instanceof PsiMethodCallExpression) { @NonNls String text = ((PsiMethodCallExpression) expression).getMethodExpression().getText(); if ("this".equals(text)) { continue; } if ("super".equals(text) && enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addAfter(assignment, first); } } } if (enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addBefore(assignment, first); } } assignment = (PsiStatement) body.add(assignment); added = true; } if (!added && enclosingConstructor == null) { if (aClass instanceof PsiAnonymousClass) { final PsiClassInitializer classInitializer = (PsiClassInitializer) aClass.addAfter(factory.createClassInitializer(), field); assignment = (PsiStatement) classInitializer.getBody().add(assignment); } else { PsiMethod constructor = (PsiMethod) aClass.add(factory.createConstructor()); assignment = (PsiStatement) constructor.getBody().add(assignment); } } if (enclosingConstructor == null) local.delete(); return assignment; }
@Override public void findExistingNameConflicts( PsiElement element, String newName, MultiMap<PsiElement, String> conflicts) { if (element instanceof PsiCompiledElement) return; if (element instanceof PsiField) { PsiField refactoredField = (PsiField) element; if (newName.equals(refactoredField.getName())) return; ConflictsUtil.checkFieldConflicts(refactoredField.getContainingClass(), newName, conflicts); } }
public static PsiMethod generateSetterPrototype( PsiField field, final PsiClass containingClass, boolean returnSelf) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); String name = field.getName(); boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); VariableKind kind = codeStyleManager.getVariableKind(field); String propertyName = codeStyleManager.variableNameToPropertyName(name, kind); String setName = suggestSetterName(project, field); try { PsiMethod setMethod = factory.createMethod( setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter param = factory.createParameter(parameterName, field.getType()); annotateWithNullableStuff(field, factory, param); setMethod.getParameterList().add(param); PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); @NonNls StringBuffer buffer = new StringBuffer(); buffer.append("{\n"); if (name.equals(parameterName)) { if (!isStatic) { buffer.append("this."); } else { String className = containingClass.getName(); if (className != null) { buffer.append(className); buffer.append("."); } } } buffer.append(name); buffer.append("="); buffer.append(parameterName); buffer.append(";\n"); if (returnSelf) { buffer.append("return this;\n"); } buffer.append("}"); PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null); setMethod.getBody().replace(body); setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod); return setMethod; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
/** * Create a new {@link FieldElement} object. * * @param field the {@link com.intellij.psi.PsiField} to get the information from. * @return a new {@link FieldElement} object. */ public static FieldElement newFieldElement(PsiField field, boolean useAccessor) { FieldElement fe = new FieldElement(); fe.setName(field.getName()); final PsiMethod getterForField = useAccessor ? PropertyUtil.findGetterForField(field) : null; fe.setAccessor(getterForField != null ? getterForField.getName() + "()" : field.getName()); if (PsiAdapter.isConstantField(field)) fe.setConstant(true); if (PsiAdapter.isEnumField(field)) fe.setEnum(true); PsiModifierList modifiers = field.getModifierList(); if (modifiers != null) { if (modifiers.hasModifierProperty(PsiModifier.TRANSIENT)) fe.setModifierTransient(true); if (modifiers.hasModifierProperty(PsiModifier.VOLATILE)) fe.setModifierVolatile(true); } PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); PsiType type = field.getType(); setElementInfo(fe, factory, type, modifiers); return fe; }
public ChangeFieldTypeFix(GuiEditor uiEditor, PsiField field, PsiType uiComponentType) { super( uiEditor, MessageFormat.format( UIDesignerBundle.message("action.change.field.type"), field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()), null); myField = field; myNewType = uiComponentType; }
public static boolean isFieldEquivalentTo(@NotNull PsiField field, PsiElement another) { if (!(another instanceof PsiField)) return false; String name1 = field.getName(); if (name1 == null) return false; if (!another.isValid()) return false; String name2 = ((PsiField) another).getName(); if (!name1.equals(name2)) return false; PsiClass aClass1 = field.getContainingClass(); PsiClass aClass2 = ((PsiField) another).getContainingClass(); return aClass1 != null && aClass2 != null && field.getManager().areElementsEquivalent(aClass1, aClass2); }
@NotNull private Map<String, PsiField> getFieldsMap() { PsiField[] fields = getFields(); if (fields.length == 0) return Collections.emptyMap(); Map<String, PsiField> cachedFields = new THashMap<String, PsiField>(); for (PsiField field : fields) { String name = field.getName(); if (!(field instanceof ExternallyDefinedPsiElement) || !cachedFields.containsKey(name)) { cachedFields.put(name, field); } } return cachedFields; }
@Nullable public static PsiField findFieldByName( GrTypeDefinition grType, String name, boolean checkBases, boolean includeSynthetic) { if (!checkBases) { for (PsiField field : CollectClassMembersUtil.getFields(grType, includeSynthetic)) { if (name.equals(field.getName())) return field; } return null; } Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType, includeSynthetic); final CandidateInfo info = fieldsMap.get(name); return info == null ? null : (PsiField) info.getElement(); }
private static void addFieldsUsages( final PsiClass aClass, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) { if (options.isIncludeInherited) { final PsiManager manager = aClass.getManager(); PsiField[] fields = aClass.getAllFields(); FieldsLoop: for (int i = 0; i < fields.length; i++) { final PsiField field = fields[i]; // filter hidden fields for (int j = 0; j < i; j++) { if (Comparing.strEqual(field.getName(), fields[j].getName())) continue FieldsLoop; } final PsiClass fieldClass = field.getContainingClass(); if (manager.areElementsEquivalent(fieldClass, aClass)) { addElementUsages(fields[i], results, options); } else { ReferencesSearch.search( new ReferencesSearch.SearchParameters( field, options.searchScope, false, options.fastTrack)) .forEach( new ReadActionProcessor<PsiReference>() { @Override public boolean processInReadAction(final PsiReference reference) { addResultFromReference( reference, fieldClass, manager, aClass, results, options); return true; } }); } } } else { PsiField[] fields = ApplicationManager.getApplication() .runReadAction( new Computable<PsiField[]>() { @Override public PsiField[] compute() { return aClass.getFields(); } }); for (PsiField field : fields) { addElementUsages(field, results, options); } } }
private PsiMethod generateMethodPrototype(PsiField field) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); String propertyName = codeStyleManager.variableNameToPropertyName( field.getName(), codeStyleManager.getVariableKind(field)); String methodName = methodNameGenerator.generateMethodNameFor(propertyName); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiMethod withMethod = generateMethodFor(field, methodName, parameterName, elementFactory); generateMethodBodyFor(withMethod, propertyName, parameterName, elementFactory); return withMethod; }
public boolean satisfiedBy(PsiElement element) { if (!(element instanceof PsiSwitchStatement)) { return false; } final PsiSwitchStatement switchStatement = (PsiSwitchStatement) element; final PsiCodeBlock body = switchStatement.getBody(); if (body == null) { return false; } final PsiExpression expression = switchStatement.getExpression(); if (expression == null) { return false; } final PsiType type = expression.getType(); if (!(type instanceof PsiClassType)) { return false; } final PsiClass enumClass = ((PsiClassType) type).resolve(); if (enumClass == null || !enumClass.isEnum()) { return false; } final PsiField[] fields = enumClass.getFields(); final Set<String> enumElements = new HashSet<String>(fields.length); for (final PsiField field : fields) { final PsiType fieldType = field.getType(); if (fieldType.equals(type)) { final String fieldName = field.getName(); enumElements.add(fieldName); } } final PsiStatement[] statements = body.getStatements(); for (PsiStatement statement : statements) { if (statement instanceof PsiSwitchLabelStatement) { final PsiSwitchLabelStatement labelStatement = (PsiSwitchLabelStatement) statement; final PsiExpression value = labelStatement.getCaseValue(); if (value != null) { final String valueText = value.getText(); enumElements.remove(valueText); } } } if (enumElements.isEmpty()) { return false; } return !ErrorUtil.containsError(element); }
@NotNull private Set<String> addAllRestrictedProperties() { if (myRefExpr.getQualifier() != null) { return Collections.emptySet(); } Set<String> propertyNames = new HashSet<String>(); for (GrTypeDefinition containingClass = PsiTreeUtil.getParentOfType(myRefExpr, GrTypeDefinition.class); containingClass != null; containingClass = PsiTreeUtil.getParentOfType(containingClass, GrTypeDefinition.class)) { for (PsiField field : containingClass.getFields()) { propertyNames.add(field.getName()); } } return propertyNames; }