private PsiClass findClassPreferringMyScope(String className) { JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject); PsiClass result = psiFacade.findClass(className, mySearchScope); return result != null ? result : psiFacade.findClass(className, GlobalSearchScope.allScope(myProject)); }
@Nullable public static PsiQualifiedReference getClassReferenceToShorten( @NotNull final PsiClass refClass, final boolean addImports, @NotNull final PsiQualifiedReference reference) { PsiClass parentClass = refClass.getContainingClass(); if (parentClass != null) { JavaPsiFacade facade = JavaPsiFacade.getInstance(parentClass.getProject()); final PsiResolveHelper resolveHelper = facade.getResolveHelper(); if (resolveHelper.isAccessible(refClass, reference, null) && isSafeToShortenReference(reference.getReferenceName(), reference, refClass)) { return reference; } if (!CodeStyleSettingsManager.getSettings(reference.getProject()) .INSERT_INNER_CLASS_IMPORTS) { final PsiElement qualifier = reference.getQualifier(); if (qualifier instanceof PsiQualifiedReference) { return getClassReferenceToShorten( parentClass, addImports, (PsiQualifiedReference) qualifier); } return null; } } if (addImports && !((PsiImportHolder) reference.getContainingFile()).importClass(refClass)) return null; if (!isSafeToShortenReference(reference, refClass)) return null; return reference; }
public static boolean proveArrayTypeDistinct(Project project, PsiArrayType type, PsiType bound) { final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); final Set<PsiClass> possibleClasses = new HashSet<PsiClass>(); possibleClasses.add(facade.findClass(CommonClassNames.JAVA_IO_SERIALIZABLE, searchScope)); possibleClasses.add(facade.findClass(CommonClassNames.JAVA_LANG_CLONEABLE, searchScope)); possibleClasses.add(facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, searchScope)); if (type.getArrayDimensions() == bound.getArrayDimensions()) { final PsiType componentType = type.getComponentType(); final PsiType boundComponentType = ((PsiArrayType) bound).getComponentType(); if (boundComponentType instanceof PsiClassType && componentType instanceof PsiClassType) { return proveExtendsBoundsDistinct( boundComponentType, componentType, ((PsiClassType) boundComponentType).resolve(), ((PsiClassType) componentType).resolve()); } else { return !bound.equals(type); } } else if (bound.getArrayDimensions() + 1 == type.getArrayDimensions() && bound.getDeepComponentType() instanceof PsiClassType) { return !possibleClasses.contains(((PsiClassType) bound.getDeepComponentType()).resolve()); } else if (bound.getArrayDimensions() == type.getArrayDimensions() + 1 && type.getDeepComponentType() instanceof PsiClassType) { return !possibleClasses.contains(((PsiClassType) type.getDeepComponentType()).resolve()); } else if (bound instanceof PsiClassType) { return !possibleClasses.contains(((PsiClassType) bound).resolve()); } else if (bound instanceof PsiWildcardType) { final PsiType boundBound = ((PsiWildcardType) bound).getBound(); return boundBound != null && !boundBound.equals(type); } return true; }
private static boolean canBePrivate( PsiMethod method, Collection<PsiReference> references, Collection<? extends PsiElement> deleted, final PsiElement[] allElementsToDelete) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { return false; } PsiManager manager = method.getManager(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); final PsiElementFactory factory = facade.getElementFactory(); final PsiModifierList privateModifierList; try { final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID); privateModifierList = newMethod.getModifierList(); privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true); } catch (IncorrectOperationException e) { LOG.assertTrue(false); return false; } for (PsiReference reference : references) { final PsiElement element = reference.getElement(); if (!isInside(element, allElementsToDelete) && !isInside(element, deleted) && !facade .getResolveHelper() .isAccessible(method, privateModifierList, element, null, null)) { return false; } } return true; }
@Override public void visitBinaryExpression(PsiBinaryExpression expression) { final IElementType tokenType = expression.getOperationTokenType(); if (JavaTokenType.OROR != tokenType) { return; } final PsiExpression lhs = expression.getLOperand(); final PsiExpression rhs = expression.getROperand(); final Pair<PsiReferenceExpression, PsiExpression> pair1 = getReferenceExpressionPair(lhs); final Pair<PsiReferenceExpression, PsiExpression> pair2 = getReferenceExpressionPair(rhs); if (pair1 == null || pair2 == null) { return; } final PsiExpression expression1 = pair1.getSecond(); final PsiExpression expression2 = pair2.getSecond(); if (expression1 == null || expression2 == null) { return; } final Project project = expression1.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiConstantEvaluationHelper constantEvaluationHelper = psiFacade.getConstantEvaluationHelper(); final Object constant1 = constantEvaluationHelper.computeConstantExpression(expression1); final Object constant2 = constantEvaluationHelper.computeConstantExpression(expression2); if (constant1 == null || constant2 == null || constant1 == constant2) { return; } final PsiReferenceExpression referenceExpression1 = pair1.getFirst(); final PsiReferenceExpression referenceExpression2 = pair2.getFirst(); if (referenceExpression1.resolve() == referenceExpression2.resolve()) { registerError(expression); } }
@NotNull private static PsiElement findPackage(String qualifiedName, Project project) { JavaPsiFacade javaFacade = JavaPsiFacade.getInstance(project); PsiPackage javaFacadePackage = javaFacade.findPackage(qualifiedName); assertNotNull("Package wasn't found: " + qualifiedName, javaFacadePackage); return javaFacadePackage; }
private static PsiSubstitutor obtainFinalSubstitutor( PsiClass superClass, PsiSubstitutor superSubstitutor, PsiSubstitutor derivedSubstitutor, boolean inRawContext) { if (inRawContext) { Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject()); superSubstitutor = factory.createRawSubstitutor( derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()])); } Map<PsiTypeParameter, PsiType> map = null; for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) { PsiType type = superSubstitutor.substitute(typeParameter); final PsiType t = derivedSubstitutor.substitute(type); if (map == null) { map = new THashMap<PsiTypeParameter, PsiType>(); } map.put(typeParameter, t); } return map == null ? PsiSubstitutor.EMPTY : JavaPsiFacade.getInstance(superClass.getProject()) .getElementFactory() .createSubstitutor(map); }
private boolean isTrivial(PsiMethod method) { final PsiCodeBlock body = method.getBody(); if (body == null) { return true; } final PsiStatement[] statements = body.getStatements(); if (statements.length == 0) { return true; } final Project project = method.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiConstantEvaluationHelper evaluationHelper = psiFacade.getConstantEvaluationHelper(); for (PsiStatement statement : statements) { if (!(statement instanceof PsiIfStatement)) { return false; } final PsiIfStatement ifStatement = (PsiIfStatement) statement; final PsiExpression condition = ifStatement.getCondition(); final Object result = evaluationHelper.computeConstantExpression(condition); if (result == null || !result.equals(Boolean.FALSE)) { return false; } } return true; }
public FieldConflictsResolver(String name, PsiCodeBlock scope) { myScope = scope; if (myScope == null) { myField = null; myReferenceExpressions = null; return; } JavaPsiFacade facade = JavaPsiFacade.getInstance(myScope.getProject()); final PsiVariable oldVariable = facade.getResolveHelper().resolveAccessibleReferencedVariable(name, myScope); myField = oldVariable instanceof PsiField ? (PsiField) oldVariable : null; if (!(oldVariable instanceof PsiField)) { myReferenceExpressions = null; return; } myReferenceExpressions = new ArrayList<PsiReferenceExpression>(); for (PsiReference reference : ReferencesSearch.search(myField, new LocalSearchScope(myScope), false)) { final PsiElement element = reference.getElement(); if (element instanceof PsiReferenceExpression) { final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) element; if (referenceExpression.getQualifierExpression() == null) { myReferenceExpressions.add(referenceExpression); } } } if (myField.hasModifierProperty(PsiModifier.STATIC)) { myQualifyingClass = myField.getContainingClass(); } }
/* Guesswork */ @Nullable private static PsiSubstitutor getInheritorSubstitutorForNewExpression( final PsiClass baseClass, final PsiClass inheritor, final PsiSubstitutor baseSubstitutor, final PsiElement context) { final Project project = baseClass.getProject(); JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiResolveHelper resolveHelper = facade.getResolveHelper(); PsiSubstitutor superSubstitutor = TypeConversionUtil.getClassSubstitutor(baseClass, inheritor, PsiSubstitutor.EMPTY); if (superSubstitutor == null) return null; PsiSubstitutor inheritorSubstitutor = PsiSubstitutor.EMPTY; for (PsiTypeParameter inheritorParameter : PsiUtil.typeParametersIterable(inheritor)) { for (PsiTypeParameter baseParameter : PsiUtil.typeParametersIterable(baseClass)) { final PsiType substituted = superSubstitutor.substitute(baseParameter); PsiType arg = baseSubstitutor.substitute(baseParameter); if (arg instanceof PsiWildcardType) arg = ((PsiWildcardType) arg).getBound(); PsiType substitution = resolveHelper.getSubstitutionForTypeParameter( inheritorParameter, substituted, arg, true, PsiUtil.getLanguageLevel(context)); if (PsiType.NULL.equals(substitution)) continue; if (substitution == null) { return facade.getElementFactory().createRawSubstitutor(inheritor); } inheritorSubstitutor = inheritorSubstitutor.put(inheritorParameter, substitution); break; } } return inheritorSubstitutor; }
public static boolean processImplicitImports( @NotNull PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place, @NotNull GroovyFile file) { JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject()); final DelegatingScopeProcessor packageSkipper = new DelegatingScopeProcessor(processor) { @Override public boolean execute(@NotNull PsiElement element, ResolveState state) { if (element instanceof PsiPackage) return true; return super.execute(element, state); } }; for (final String implicitlyImported : getImplicitlyImportedPackages(file)) { PsiPackage aPackage = facade.findPackage(implicitlyImported); if (aPackage == null) continue; if (!aPackage.processDeclarations(packageSkipper, state, lastParent, place)) { return false; } } GroovyPsiManager groovyPsiManager = GroovyPsiManager.getInstance(file.getProject()); for (String implicitlyImportedClass : GroovyFileBase.IMPLICITLY_IMPORTED_CLASSES) { PsiClass clazz = groovyPsiManager.findClassWithCache(implicitlyImportedClass, file.getResolveScope()); if (clazz != null && !ResolveUtil.processElement(processor, clazz, state)) return false; } return true; }
@Override public Result<PsiModifierList> compute() { List<PsiModifierList> list = new ArrayList<PsiModifierList>(); for (PsiDirectory directory : getDirectories()) { PsiFile file = directory.findFile(PACKAGE_INFO_FILE); if (file != null) { PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(file, PsiPackageStatement.class); if (stmt != null) { final PsiModifierList modifierList = stmt.getAnnotationList(); if (modifierList != null) { list.add(modifierList); } } } } final JavaPsiFacade facade = getFacade(); final GlobalSearchScope scope = allScope(); for (PsiClass aClass : facade.findClasses(getQualifiedName() + ".package-info", scope)) { ContainerUtil.addIfNotNull(aClass.getModifierList(), list); } return new Result<PsiModifierList>( list.isEmpty() ? null : new PsiCompositeModifierList(getManager(), list), OOCB_DEPENDENCY); }
public void updateThrowsList(PsiClassType exceptionType) { if (!getSuperMethods().isEmpty()) { for (RefMethod refSuper : getSuperMethods()) { ((RefMethodImpl) refSuper).updateThrowsList(exceptionType); } } else if (myUnThrownExceptions != null) { if (exceptionType == null) { myUnThrownExceptions = null; return; } PsiClass exceptionClass = exceptionType.resolve(); JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject()); for (int i = myUnThrownExceptions.size() - 1; i >= 0; i--) { String exceptionFqn = myUnThrownExceptions.get(i); PsiClass classType = facade.findClass( exceptionFqn, GlobalSearchScope.allScope(getRefManager().getProject())); if (InheritanceUtil.isInheritorOrSelf(exceptionClass, classType, true) || InheritanceUtil.isInheritorOrSelf(classType, exceptionClass, true)) { myUnThrownExceptions.remove(i); } } if (myUnThrownExceptions.isEmpty()) myUnThrownExceptions = null; } }
public static PsiType getType(@NotNull PsiClassObjectAccessExpression classAccessExpression) { GlobalSearchScope resolveScope = classAccessExpression.getResolveScope(); PsiManager manager = classAccessExpression.getManager(); final PsiClass classClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Class", resolveScope); if (classClass == null) { return new PsiClassReferenceType( new LightClassReference(manager, "Class", "java.lang.Class", resolveScope), null); } if (!PsiUtil.isLanguageLevel5OrHigher(classAccessExpression)) { // Raw java.lang.Class return JavaPsiFacade.getInstance(manager.getProject()) .getElementFactory() .createType(classClass); } PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; PsiType operandType = classAccessExpression.getOperand().getType(); if (operandType instanceof PsiPrimitiveType && !PsiType.NULL.equals(operandType)) { if (PsiType.VOID.equals(operandType)) { operandType = JavaPsiFacade.getInstance(manager.getProject()) .getElementFactory() .createTypeByFQClassName("java.lang.Void", classAccessExpression.getResolveScope()); } else { operandType = ((PsiPrimitiveType) operandType).getBoxedType(classAccessExpression); } } final PsiTypeParameter[] typeParameters = classClass.getTypeParameters(); if (typeParameters.length == 1) { substitutor = substitutor.put(typeParameters[0], operandType); } return new PsiImmediateClassType(classClass, substitutor); }
private static String compoundLambdaOrMethodReference( PsiParameter parameter, PsiExpression expression, String samQualifiedName, PsiType[] samParamTypes) { String result = ""; final Project project = parameter.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass functionClass = psiFacade.findClass(samQualifiedName, GlobalSearchScope.allScope(project)); for (int i = 0; i < samParamTypes.length; i++) { if (samParamTypes[i] instanceof PsiPrimitiveType) { samParamTypes[i] = ((PsiPrimitiveType) samParamTypes[i]).getBoxedType(expression); } } final PsiClassType functionalInterfaceType = functionClass != null ? psiFacade.getElementFactory().createType(functionClass, samParamTypes) : null; final PsiParameter[] parameters = {parameter}; final String methodReferenceText = LambdaCanBeMethodReferenceInspection.convertToMethodReference( expression, parameters, functionalInterfaceType, null); if (methodReferenceText != null) { LOG.assertTrue(functionalInterfaceType != null); result += "(" + functionalInterfaceType.getCanonicalText() + ")" + methodReferenceText; } else { result += parameter.getName() + " -> " + expression.getText(); } return result; }
@Override public boolean canHandle(RunConfiguration configuration, Project project) { if (!(configuration instanceof JUnitConfiguration)) { return false; } else { JUnitConfiguration.Data data = ((JUnitConfiguration) configuration).getPersistentData(); String mainClassName = data.getMainClassName(); String methodName = data.getMethodName(); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); PsiClass referencedClass = psiFacade.findClass(mainClassName, GlobalSearchScope.allScope(project)); PsiFile containingFile = referencedClass.getContainingFile(); FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); if (methodName == null) { fileEditorManager.openFile(containingFile.getVirtualFile(), true); } else { PsiMethod[] methodsByName = referencedClass.findMethodsByName(methodName, false); fileEditorManager.openEditor( new OpenFileDescriptor( project, containingFile.getVirtualFile(), methodsByName[0].getTextOffset()), true); } return true; } }
public AddModuleDependencyFix( Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) { final PsiElement psiElement = reference.getElement(); final Project project = psiElement.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.add(classModule); } } myCurrentModule = currentModule; myClassVFile = classVFile; myClasses = classes; myReference = reference; }
public void _testCollectedPsiWithChangedDocument() throws IOException { VirtualFile dir = getVirtualFile(createTempDirectory()); PsiTestUtil.addSourceContentToRoots(myModule, dir); final VirtualFile vFile = createChildData(dir, "Foo.java"); VfsUtil.saveText(vFile, "class Foo {}"); final GlobalSearchScope scope = GlobalSearchScope.allScope(getProject()); final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject()); assertNotNull(facade.findClass("Foo", scope)); ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(vFile); assertNotNull(psiFile); Document document = FileDocumentManager.getInstance().getDocument(vFile); document.deleteString(0, document.getTextLength()); assertNotNull(facade.findClass("Foo", scope)); psiFile = null; PlatformTestUtil.tryGcSoftlyReachableObjects(); assertNull( ((PsiManagerEx) PsiManager.getInstance(getProject())) .getFileManager() .getCachedPsiFile(vFile)); // should be assertNull(facade.findClass("Foo", scope)); // or the file should not be allowed to be gc'ed facade.findClass("Foo", scope).getText(); } }); }
@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; }
private static boolean isIndexOfCall(@NotNull PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); if (!HardcodedMethodConstants.INDEX_OF.equals(methodName)) { return false; } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return false; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null) { return false; } final PsiType qualifierType = qualifier.getType(); if (qualifierType == null) { return false; } final Project project = expression.getProject(); final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass javaUtilListClass = psiFacade.findClass(CommonClassNames.JAVA_UTIL_LIST, projectScope); if (javaUtilListClass == null) { return false; } final PsiElementFactory factory = psiFacade.getElementFactory(); final PsiClassType javaUtilListType = factory.createType(javaUtilListClass); return javaUtilListType.isAssignableFrom(qualifierType); }
private static PsiType genNewListBy(PsiType genericOwner, PsiManager manager) { PsiClass list = JavaPsiFacade.getInstance(manager.getProject()) .findClass(JAVA_UTIL_LIST, genericOwner.getResolveScope()); PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); if (list == null) return factory.createTypeFromText(JAVA_UTIL_LIST, null); return factory.createType(list, PsiUtil.extractIterableTypeParameter(genericOwner, false)); }
private static PsiClassType createDefaultConsumerType(Project project, PsiParameter parameter) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass consumerClass = psiFacade.findClass("java.util.function.Consumer", GlobalSearchScope.allScope(project)); return consumerClass != null ? psiFacade.getElementFactory().createType(consumerClass, parameter.getType()) : null; }
public static PsiClass findClass(Project project, String className) { JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); PsiClass viewClass = psiFacade.findClass(className, new EverythingGlobalScope(project)); if (viewClass == null) { throw new GenerateViewPresenterAction.CancellationException("Class not found: " + className); } return viewClass; }
private JavaResolveResult advancedResolveInner(final PsiElement psiElement, final String qName) { final PsiManager manager = psiElement.getManager(); final GlobalSearchScope scope = getScope(); if (myIndex == myJavaClassReferenceSet.getReferences().length - 1) { final PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope); if (aClass != null) { return new ClassCandidateInfo(aClass, PsiSubstitutor.EMPTY, false, psiElement); } else { if (!JavaClassReferenceProvider.ADVANCED_RESOLVE.getBooleanValue(getOptions())) { return JavaResolveResult.EMPTY; } } } PsiElement resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findPackage(qName); if (resolveResult == null) { resolveResult = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope); } if (myInStaticImport && resolveResult == null) { resolveResult = resolveMember(qName, manager, getElement().getResolveScope()); } if (resolveResult == null) { PsiFile containingFile = psiElement.getContainingFile(); if (containingFile instanceof PsiJavaFile) { if (containingFile instanceof JspFile) { containingFile = containingFile.getViewProvider().getPsi(StdLanguages.JAVA); if (containingFile == null) return JavaResolveResult.EMPTY; } final ClassResolverProcessor processor = new ClassResolverProcessor(getCanonicalText(), psiElement); containingFile.processDeclarations(processor, ResolveState.initial(), null, psiElement); if (processor.getResult().length == 1) { final JavaResolveResult javaResolveResult = processor.getResult()[0]; if (javaResolveResult != JavaResolveResult.EMPTY && getOptions() != null) { final Boolean value = JavaClassReferenceProvider.RESOLVE_QUALIFIED_CLASS_NAME.getValue(getOptions()); final PsiClass psiClass = (PsiClass) javaResolveResult.getElement(); if (value != null && value.booleanValue() && psiClass != null) { final String qualifiedName = psiClass.getQualifiedName(); if (!qName.equals(qualifiedName)) { return JavaResolveResult.EMPTY; } } } return javaResolveResult; } } } return resolveResult != null ? new CandidateInfo(resolveResult, PsiSubstitutor.EMPTY, false, false, psiElement) : JavaResolveResult.EMPTY; }
private boolean checkAccessibility(final PsiClass aClass) { // We don't care about accessibility in javadoc if (JavaResolveUtil.isInJavaDoc(myPlace)) { return true; } if (PsiImplUtil.isInServerPage(aClass.getContainingFile())) { PsiFile file = FileContextUtil.getContextFile(myPlace); if (PsiImplUtil.isInServerPage(file)) { return true; } } boolean accessible = true; if (aClass instanceof PsiTypeParameter) { accessible = !myStaticContext; } PsiManager manager = aClass.getManager(); if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) { PsiElement parent = aClass.getParent(); while (true) { PsiElement parentScope = parent.getParent(); if (parentScope instanceof PsiJavaFile) break; parent = parentScope; if (!(parentScope instanceof PsiClass)) break; } if (parent instanceof PsiDeclarationStatement) { parent = parent.getParent(); } accessible = false; for (PsiElement placeParent = myPlace; placeParent != null; placeParent = placeParent.getContext()) { if (manager.areElementsEquivalent(placeParent, parent)) accessible = true; } } final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) { accessible = false; if (myPlace != null && facade.arePackagesTheSame(aClass, myPlace)) { accessible = true; } else { if (aClass.getContainingClass() != null) { accessible = myAccessClass == null || myPlace != null && facade.getResolveHelper().isAccessible(aClass, myPlace, myAccessClass); } } } if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) { if (myPlace == null || !facade.arePackagesTheSame(aClass, myPlace)) { accessible = false; } } return accessible; }
private static boolean changeClassTypeArgument( PsiMethod myMethod, Project project, PsiType superReturnType, PsiClass superClass, Editor editor, PsiType returnType) { if (superClass == null || !superClass.hasTypeParameters()) return true; final PsiClass superReturnTypeClass = PsiUtil.resolveClassInType(superReturnType); if (superReturnTypeClass == null || !(superReturnTypeClass instanceof PsiTypeParameter || superReturnTypeClass.hasTypeParameters())) return true; final PsiClass derivedClass = myMethod.getContainingClass(); if (derivedClass == null) return true; final PsiReferenceParameterList referenceParameterList = findTypeArgumentsList(superClass, derivedClass); if (referenceParameterList == null) return true; final PsiElement resolve = ((PsiJavaCodeReferenceElement) referenceParameterList.getParent()).resolve(); if (!(resolve instanceof PsiClass)) return true; final PsiClass baseClass = (PsiClass) resolve; if (returnType instanceof PsiPrimitiveType) { returnType = ((PsiPrimitiveType) returnType).getBoxedType(derivedClass); } final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, baseClass, PsiSubstitutor.EMPTY); final PsiType superReturnTypeInBaseClassType = superClassSubstitutor.substitute(superReturnType); final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(project).getResolveHelper(); final PsiSubstitutor psiSubstitutor = resolveHelper.inferTypeArguments( PsiTypesUtil.filterUnusedTypeParameters( superReturnTypeInBaseClassType, baseClass.getTypeParameters()), new PsiType[] {superReturnTypeInBaseClassType}, new PsiType[] {returnType}, PsiUtil.getLanguageLevel(superClass)); final TypeMigrationRules rules = new TypeMigrationRules(); final PsiSubstitutor compoundSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, derivedClass, PsiSubstitutor.EMPTY) .putAll(psiSubstitutor); rules.setBoundScope(new LocalSearchScope(derivedClass)); TypeMigrationProcessor.runHighlightingTypeMigration( project, editor, rules, referenceParameterList, JavaPsiFacade.getElementFactory(project).createType(baseClass, compoundSubstitutor)); return false; }
@Nullable @Override protected List<ClosureParameterInfo> getParameterInfos( InsertionContext context, PsiMethod method, PsiSubstitutor substitutor, Document document, int offset, PsiElement parent) { final String name = method.getName(); if (!"eachWithIndex".equals(name)) return null; if (method instanceof GrGdkMethod) method = ((GrGdkMethod) method).getStaticMethod(); final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) return null; final String qname = containingClass.getQualifiedName(); if (!GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(qname)) return null; final PsiParameter[] parameters = method.getParameterList().getParameters(); if (parameters.length != 2) return null; final PsiType type = parameters[0].getType(); final PsiType collection = substitutor.substitute(type); final PsiType iterable = getIteratedType(parent, collection); if (iterable != null) { return Arrays.asList( new ClosureParameterInfo(iterable.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } if (InheritanceUtil.isInheritor(collection, CommonClassNames.JAVA_UTIL_MAP)) { final PsiType[] typeParams = ((PsiClassType) collection).getParameters(); final Project project = context.getProject(); final PsiClass entry = JavaPsiFacade.getInstance(project) .findClass("java.util.Map.Entry", parent.getResolveScope()); if (entry == null) return null; final PsiClassType entryType = JavaPsiFacade.getElementFactory(project).createType(entry, typeParams); return Arrays.asList( new ClosureParameterInfo(entryType.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } return Arrays.asList( new ClosureParameterInfo(collection.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); }
@Nullable public static PsiClass getBaseClass(GrTypeDefinition grType) { if (grType.isEnum()) { return JavaPsiFacade.getInstance(grType.getProject()) .findClass(CommonClassNames.JAVA_LANG_ENUM, grType.getResolveScope()); } else { return JavaPsiFacade.getInstance(grType.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, grType.getResolveScope()); } }
public static boolean variableNameResolvesToTarget( @NotNull String variableName, @NotNull PsiVariable target, @NotNull PsiElement context) { final Project project = context.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiResolveHelper resolveHelper = psiFacade.getResolveHelper(); final PsiVariable variable = resolveHelper.resolveAccessibleReferencedVariable(variableName, context); return target.equals(variable); }
public static boolean addStaticImport( @NotNull String qualifierClass, @NonNls @NotNull String memberName, @NotNull PsiElement context) { if (!nameCanBeStaticallyImported(qualifierClass, memberName, context)) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritor(containingClass, qualifierClass)) { return true; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement != null) { return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, qualifierClass); if (onDemandImportStatement != null && !hasOnDemandImportStaticConflict(qualifierClass, memberName, context)) { return true; } final Project project = context.getProject(); final GlobalSearchScope scope = context.getResolveScope(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass aClass = psiFacade.findClass(qualifierClass, scope); if (aClass == null) { return false; } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return false; } final List<PsiImportStaticStatement> imports = getMatchingImports(importList, qualifiedName); final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); if (imports.size() < codeStyleSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND) { importList.add(elementFactory.createImportStaticStatement(aClass, memberName)); } else { for (PsiImportStaticStatement importStatement : imports) { importStatement.delete(); } importList.add(elementFactory.createImportStaticStatement(aClass, "*")); } return true; }