public void testEnum() throws Exception { setupLoadingFilter(); final PsiClass enumClass = myJavaFacade.findClass("enums.OurEnum", GlobalSearchScope.moduleScope(myModule)); assertNotNull(enumClass); assertTrue(enumClass.isEnum()); final PsiClass superClass = enumClass.getSuperClass(); assertNotNull(superClass); assertEquals("java.lang.Enum", superClass.getQualifiedName()); assertTrue(enumClass.isInheritor(superClass, false)); final PsiClassType[] superTypes = enumClass.getSuperTypes(); assertEquals(1, superTypes.length); assertEquals("java.lang.Enum<enums.OurEnum>", superTypes[0].getCanonicalText()); final PsiClass[] supers = enumClass.getSupers(); assertEquals(1, supers.length); assertEquals("java.lang.Enum", supers[0].getQualifiedName()); final PsiClassType[] extendsListTypes = enumClass.getExtendsListTypes(); assertEquals(1, extendsListTypes.length); assertEquals("java.lang.Enum<enums.OurEnum>", extendsListTypes[0].getCanonicalText()); final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, enumClass, PsiSubstitutor.EMPTY); assertEquals( "java.lang.Enum<enums.OurEnum>", myJavaFacade .getElementFactory() .createType(superClass, superClassSubstitutor) .getCanonicalText()); teardownLoadingFilter(); }
@Override public PsiType fun(GrSuperReferenceExpressionImpl ref) { final GrReferenceExpression qualifier = ref.getQualifier(); if (qualifier == null) { GroovyPsiElement context = PsiTreeUtil.getParentOfType(ref, GrTypeDefinition.class, GroovyFileBase.class); if (context instanceof GrTypeDefinition) { final PsiClass superClass = ((GrTypeDefinition) context).getSuperClass(); if (superClass != null) { return JavaPsiFacade.getInstance(ref.getProject()) .getElementFactory() .createType(superClass); } } else if (context instanceof GroovyFileBase) { PsiClass scriptClass = ((GroovyFileBase) context).getScriptClass(); if (scriptClass != null) { PsiClass superClass = scriptClass.getSuperClass(); if (superClass != null) { return JavaPsiFacade.getInstance(ref.getProject()) .getElementFactory() .createType(superClass); } } return GrClassImplUtil.getGroovyObjectType(ref); } } else { final PsiElement resolved = qualifier.resolve(); if (resolved instanceof PsiClass) { return ref.getSuperType((PsiClass) resolved); } } return null; }
@Nullable private static PsiMethod doFindMethodInSuperClassBySignatureInDerived( @NotNull PsiClass superClass, @NotNull PsiSubstitutor superSubstitutor, @NotNull MethodSignature signature, final boolean checkDeep) { final String name = signature.getName(); final PsiMethod[] methods = superClass.findMethodsByName(name, false); for (final PsiMethod method : methods) { if (isSubsignature(method.getSignature(superSubstitutor), signature)) { return method; } } if (checkDeep) { final PsiClass clazz = superClass.getSuperClass(); if (clazz != null && clazz != superClass) { PsiSubstitutor substitutor1 = TypeConversionUtil.getSuperClassSubstitutor(clazz, superClass, superSubstitutor); return doFindMethodInSuperClassBySignatureInDerived(clazz, substitutor1, signature, true); } } return null; }
public void testRunningAllInPackage() throws IOException, ExecutionException { Module module1 = getModule1(); GlobalSearchScope module1AndLibraries = GlobalSearchScope.moduleWithLibrariesScope(module1); PsiClass testCase = findClass(TestCase.class.getName(), module1AndLibraries); PsiClass psiClass = findTestA(module1); PsiClass psiClass2 = findTestA(getModule2()); PsiClass derivedTest = findClass(module1, "test1.DerivedTest"); PsiClass baseTestCase = findClass("junit.framework.ThirdPartyClass", module1AndLibraries); PsiClass testB = findClass(getModule3(), "test1.TestB"); assertNotNull(testCase); assertNotNull(derivedTest); assertNotNull(psiClass); assertTrue(psiClass.isInheritor(testCase, false)); assertEquals(baseTestCase, derivedTest.getSuperClass()); assertTrue(baseTestCase.isInheritor(testCase, true)); assertTrue(derivedTest.isInheritor(testCase, true)); PsiPackage psiPackage = JUnitUtil.getContainingPackage(psiClass); JUnitConfiguration configuration = createConfiguration(psiPackage, module1); JavaParameters parameters = checkCanRun(configuration); List<String> lines = extractAllInPackageTests(parameters, psiPackage); Assertion.compareUnordered( new Object[] { "", psiClass.getQualifiedName(), psiClass2.getQualifiedName(), derivedTest.getQualifiedName(), RT_INNER_TEST_NAME, testB.getQualifiedName() }, lines); }
/** * Creates a new {@link ClassElement} object. * * @param clazz class information. * @return a new {@link ClassElement} object. */ public static ClassElement newClassElement(PsiClass clazz) { ClassElement ce = new ClassElement(); // name ce.setName(clazz.getName()); ce.setQualifiedName(clazz.getQualifiedName()); // super PsiClass superClass = clazz.getSuperClass(); if (superClass != null && !CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) { ce.setSuperName(superClass.getName()); } // interfaces ce.setImplementNames(PsiAdapter.getImplementsClassnames(clazz)); // other ce.setEnum(clazz.isEnum()); ce.setDeprecated(clazz.isDeprecated()); ce.setException(PsiAdapter.isExceptionClass(clazz)); ce.setAbstract(clazz.hasModifierProperty(PsiModifier.ABSTRACT)); ce.setTypeParams(clazz.getTypeParameters().length); return ce; }
public void migrateClassTypeParameter( final PsiReferenceParameterList referenceParameterList, final PsiClassType migrationType) { final PsiClass psiClass = PsiTreeUtil.getParentOfType(referenceParameterList, PsiClass.class); LOG.assertTrue(psiClass != null); final PsiClass superClass = psiClass.getSuperClass(); LOG.assertTrue(superClass != null); myLabeler.getTypeEvaluator().setType(new TypeMigrationUsageInfo(superClass), migrationType); final Map<PsiElement, Pair<PsiReference[], PsiType>> roots = new HashMap<PsiElement, Pair<PsiReference[], PsiType>>(); markTypeParameterUsages(psiClass, migrationType, referenceParameterList, roots); final Set<PsiElement> processed = new HashSet<PsiElement>(); for (Map.Entry<PsiElement, Pair<PsiReference[], PsiType>> entry : roots.entrySet()) { final PsiElement member = entry.getKey(); final PsiType type = entry.getValue().second; if (member instanceof PsiParameter && ((PsiParameter) member).getDeclarationScope() instanceof PsiMethod) { myLabeler.migrateMethodCallExpressions(type, (PsiParameter) member, psiClass); } final PsiReference[] references = entry.getValue().first; for (PsiReference usage : references) { myLabeler.migrateRootUsageExpression(usage, processed); } } }
private static boolean instanceOf(final PsiClass jComponentClass, final String baseClassName) { for (PsiClass c = jComponentClass; c != null; c = c.getSuperClass()) { if (baseClassName.equals(c.getQualifiedName())) { return true; } } return false; }
@Nullable private static PsiMethod findNearestMethod(String name, @Nullable PsiClass cls) { if (cls == null) return null; for (PsiMethod method : cls.getMethods()) { if (method.getParameterList().getParametersCount() == 0 && method.getName().equals(name)) { return method.getModifierList().hasModifierProperty(PsiModifier.ABSTRACT) ? null : method; } } return findNearestMethod(name, cls.getSuperClass()); }
@Nullable private PsiType extractListTypeFromContainingClass( PsiElement element) { PsiClass listClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (listClass == null) { return null; } final PsiMethod[] getMethods = listClass.findMethodsByName("get", true); if (getMethods.length == 0) { return null; } final PsiType type = getMethods[0].getReturnType(); if (!(type instanceof PsiClassType)) { return null; } final PsiClassType classType = (PsiClassType)type; final PsiClass parameterClass = classType.resolve(); if (parameterClass == null) { return null; } PsiClass subClass = null; while (listClass != null && !listClass.hasTypeParameters()) { subClass = listClass; listClass = listClass.getSuperClass(); } if (listClass == null || subClass == null) { return TypeUtils.getObjectType(element); } final PsiTypeParameter[] typeParameters = listClass.getTypeParameters(); if (!parameterClass.equals(typeParameters[0])) { return TypeUtils.getObjectType(element); } final PsiReferenceList extendsList = subClass.getExtendsList(); if (extendsList == null) { return null; } final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); if (referenceElements.length == 0) { return null; } final PsiType[] types = referenceElements[0].getTypeParameters(); if (types.length == 0) { return TypeUtils.getObjectType(element); } return types[0]; }
private static void addParametersForSuper( @NotNull PsiClass typeDefinition, GrLightMethodBuilder fieldsConstructor, boolean superFields, boolean superProperties, Set<PsiClass> visited, Set<String> excludes) { PsiClass parent = typeDefinition.getSuperClass(); if (parent != null && visited.add(parent) && !GroovyCommonClassNames.GROOVY_OBJECT_SUPPORT.equals(parent.getQualifiedName())) { addParametersForSuper( parent, fieldsConstructor, superFields, superProperties, visited, excludes); addParameters(parent, fieldsConstructor, superProperties, superFields, true, excludes); } }
private static boolean superConstructorHasParameters(PsiMethod method) { final PsiClass psiClass = method.getContainingClass(); if (psiClass == null) { return false; } final PsiClass superClass = psiClass.getSuperClass(); if (superClass != null) { for (final PsiMethod psiMethod : superClass.getConstructors()) { final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(method.getProject()).getResolveHelper(); if (resolveHelper.isAccessible(psiMethod, method, null) && psiMethod.getParameterList().getParameters().length > 0) { return true; } } } return false; }
@Override @NotNull protected List<? extends GenerationInfo> generateMemberPrototypes( PsiClass aClass, ClassMember[] members) throws IncorrectOperationException { List<PsiMethod> baseConstructors = new ArrayList<PsiMethod>(); List<PsiField> fieldsVector = new ArrayList<PsiField>(); for (ClassMember member1 : members) { PsiElement member = ((PsiElementClassMember) member1).getElement(); if (member instanceof PsiMethod) { baseConstructors.add((PsiMethod) member); } else { fieldsVector.add((PsiField) member); } } PsiField[] fields = fieldsVector.toArray(new PsiField[fieldsVector.size()]); if (!baseConstructors.isEmpty()) { List<GenerationInfo> constructors = new ArrayList<GenerationInfo>(baseConstructors.size()); final PsiClass superClass = aClass.getSuperClass(); assert superClass != null; PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY); for (PsiMethod baseConstructor : baseConstructors) { if (substitutor != PsiSubstitutor.EMPTY) { baseConstructor = GenerateMembersUtil.substituteGenericMethod(baseConstructor, substitutor, aClass); } constructors.add( new PsiGenerationInfo( generateConstructorPrototype(aClass, baseConstructor, myCopyJavadoc, fields))); } return filterOutAlreadyInsertedConstructors(aClass, constructors); } final List<GenerationInfo> constructors = Collections.<GenerationInfo>singletonList( new PsiGenerationInfo(generateConstructorPrototype(aClass, null, false, fields))); return filterOutAlreadyInsertedConstructors(aClass, constructors); }
public static void addAvailableSystemScripts( final Collection<String> result, @NotNull Module module) { VirtualFile scriptRoot = null; GlobalSearchScope searchScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false); for (PsiClass aClass : JavaPsiFacade.getInstance(module.getProject()).findClasses("CreateApp_", searchScope)) { PsiClass superClass = aClass.getSuperClass(); if (superClass != null && GroovyCommonClassNames.GROOVY_LANG_SCRIPT.equals(superClass.getQualifiedName())) { PsiFile psiFile = aClass.getContainingFile(); if (psiFile != null) { VirtualFile file = psiFile.getVirtualFile(); if (file != null && file.getFileSystem() instanceof ArchiveFileSystem) { VirtualFile parent = file.getParent(); if (parent != null && parent.findChild("Console.class") != null) { scriptRoot = parent; break; } } } } } if (scriptRoot == null) return; Pattern scriptPattern = Pattern.compile("([A-Za-z0-9]+)_?\\.class"); for (VirtualFile file : scriptRoot.getChildren()) { Matcher matcher = scriptPattern.matcher(file.getName()); if (matcher.matches()) { result.add(GroovyNamesUtil.camelToSnake(matcher.group(1))); } } }
/** * spring bean reference annotator * * @param psiElement psi element * @param holder annotation holder */ public void annotate(PsiElement psiElement, AnnotationHolder holder) { if (!(psiElement instanceof PsiJavaFile)) { return; } // Get java classes for (PsiClass javaClass : ((PsiJavaFile) psiElement).getClasses()) { PsiClass superClass = javaClass.getSuperClass(); PsiField[] superClassFields = superClass != null ? superClass.getAllFields() : new PsiField[] {}; for (PsiField field : javaClass.getAllFields()) { // We don't need scan super class fields if (isContain(superClassFields, field)) { continue; } PsiModifierList modifierList = field.getModifierList(); if (modifierList == null) { continue; } for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { String qcName = psiAnnotation.getQualifiedName(); if (qcName == null || !qcName.startsWith("org.unitils.spring.annotation.")) { continue; } SpringManager springManager = SpringManager.getInstance(psiElement.getProject()); SpringModel springModel = springManager.getCombinedModel(ModuleUtil.findModuleForPsiElement(psiElement)); if (springModel == null) { continue; } // by type if (qcName.endsWith("SpringBeanByType")) { final PsiType type = field.getType(); if (!(type instanceof PsiClassType)) { continue; } final PsiClass typeClass = ((PsiClassType) type).resolve(); if (typeClass == null) { continue; } List<SpringBaseBeanPointer> springBaseBeanPointerList = springModel.findBeansByPsiClass(typeClass); if (springBaseBeanPointerList.size() > 0) { List<PsiElement> elements = new ArrayList<PsiElement>(); for (SpringBaseBeanPointer springBaseBeanPointer : springBaseBeanPointerList) { elements.add(springBaseBeanPointer.getPsiElement()); } NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON) .setTooltipText("Navigate to the spring bean declaration(s)") .setTargets(elements) .install(holder, field.getNameIdentifier()); } } // by name else { String beanName = field.getName(); if (qcName.endsWith("SpringBean")) { PsiAnnotationMemberValue attributeValue = psiAnnotation.findAttributeValue("value"); if (attributeValue != null && attributeValue.getText() != null) { beanName = attributeValue.getText().replace("\"", ""); } } if (beanName != null && StringUtil.isNotEmpty(beanName)) { SpringBeanPointer springBeanPointer = springModel.findBeanByName(beanName); if (springBeanPointer != null) { NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON) .setTooltipText("Navigate to the spring bean declaration(s)") .setTarget(springBeanPointer.getPsiElement()) .install(holder, field.getNameIdentifier()); } } } } } } }
@Override @Nullable protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) { if (aClass instanceof PsiAnonymousClass) { Messages.showMessageDialog( project, CodeInsightBundle.message("error.attempt.to.generate.constructor.for.anonymous.class"), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return null; } myCopyJavadoc = false; PsiMethod[] baseConstructors = null; PsiClass baseClass = aClass.getSuperClass(); if (baseClass != null) { ArrayList<PsiMethod> array = new ArrayList<PsiMethod>(); for (PsiMethod method : baseClass.getConstructors()) { if (JavaPsiFacade.getInstance(method.getProject()) .getResolveHelper() .isAccessible(method, aClass, null)) { array.add(method); } } if (!array.isEmpty()) { if (array.size() == 1) { baseConstructors = new PsiMethod[] {array.get(0)}; } else { final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); PsiMethodMember[] constructors = ContainerUtil.map2Array( array, PsiMethodMember.class, new Function<PsiMethod, PsiMethodMember>() { @Override public PsiMethodMember fun(final PsiMethod s) { return new PsiMethodMember(s, substitutor); } }); MemberChooser<PsiMethodMember> chooser = new MemberChooser<PsiMethodMember>(constructors, false, true, project); chooser.setTitle( CodeInsightBundle.message("generate.constructor.super.constructor.chooser.title")); chooser.show(); List<PsiMethodMember> elements = chooser.getSelectedElements(); if (elements == null || elements.isEmpty()) return null; baseConstructors = new PsiMethod[elements.size()]; for (int i = 0; i < elements.size(); i++) { final ClassMember member = elements.get(i); baseConstructors[i] = ((PsiMethodMember) member).getElement(); } myCopyJavadoc = chooser.isCopyJavadoc(); } } } ClassMember[] allMembers = getAllOriginalMembers(aClass); ClassMember[] members; if (allMembers.length == 0) { members = ClassMember.EMPTY_ARRAY; } else { members = chooseMembers(allMembers, true, false, project, null); if (members == null) return null; } if (baseConstructors != null) { ArrayList<ClassMember> array = new ArrayList<ClassMember>(); for (PsiMethod baseConstructor : baseConstructors) { array.add(new PsiMethodMember(baseConstructor)); } ContainerUtil.addAll(array, members); members = array.toArray(new ClassMember[array.size()]); } return members; }
public static PsiMethod generateConstructorPrototype( PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException { PsiManager manager = aClass.getManager(); JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject()); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject()); PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass); String modifier = PsiUtil.getMaximumModifierForMember(aClass, false); if (modifier != null) { PsiUtil.setModifierProperty(constructor, modifier, true); } if (baseConstructor != null) { PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements(); for (PsiJavaCodeReferenceElement ref : throwRefs) { constructor.getThrowsList().add(ref); } if (copyJavaDoc) { final PsiDocComment docComment = ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment(); if (docComment != null) { constructor.addAfter(docComment, null); } } } boolean isNotEnum = false; if (baseConstructor != null) { PsiClass superClass = aClass.getSuperClass(); LOG.assertTrue(superClass != null); if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) { isNotEnum = true; if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names PsiClass dummyClass = JVMElementFactories.requireFactory( baseConstructor.getLanguage(), baseConstructor.getProject()) .createClass("Dummy"); baseConstructor = (PsiMethod) dummyClass.add(baseConstructor); } PsiParameter[] params = baseConstructor.getParameterList().getParameters(); for (PsiParameter param : params) { PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass); GenerateMembersUtil.copyOrReplaceModifierList(param, newParam); constructor.getParameterList().add(newParam); } } } JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject()); final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName()); dummyConstructor.getParameterList().replace(constructor.getParameterList().copy()); List<PsiParameter> fieldParams = new ArrayList<PsiParameter>(); for (PsiField field : fields) { String fieldName = field.getName(); String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD); String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER); parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true); PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass); final NullableNotNullManager nullableManager = NullableNotNullManager.getInstance(field.getProject()); final String notNull = nullableManager.getNotNull(field); if (notNull != null) { parm.getModifierList() .addAfter(factory.createAnnotationFromText("@" + notNull, field), null); } constructor.getParameterList().add(parm); dummyConstructor.getParameterList().add(parm.copy()); fieldParams.add(parm); } ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage()); if (generator != null) { @NonNls StringBuilder buffer = new StringBuilder(); generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY); if (isNotEnum) { generator.generateSuperCallIfNeeded( buffer, baseConstructor.getParameterList().getParameters()); } generator.generateFieldInitialization( buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()])); generator.finish(buffer); PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass); constructor.getBody().replace(stub.getBody()); } constructor = (PsiMethod) codeStyleManager.reformat(constructor); return constructor; }