Search in sources :

Example 46 with Function

use of com.intellij.util.Function in project kotlin by JetBrains.

the class ResolveSession method getTopLevelClassifierDescriptors.

@Override
@NotNull
@ReadOnly
public Collection<ClassifierDescriptor> getTopLevelClassifierDescriptors(@NotNull FqName fqName, @NotNull final LookupLocation location) {
    if (fqName.isRoot())
        return Collections.emptyList();
    PackageMemberDeclarationProvider provider = declarationProviderFactory.getPackageMemberDeclarationProvider(fqName.parent());
    if (provider == null)
        return Collections.emptyList();
    Collection<ClassifierDescriptor> result = new SmartList<ClassifierDescriptor>();
    result.addAll(ContainerUtil.mapNotNull(provider.getClassOrObjectDeclarations(fqName.shortName()), new Function<KtClassLikeInfo, ClassifierDescriptor>() {

        @Override
        public ClassDescriptor fun(KtClassLikeInfo classLikeInfo) {
            if (classLikeInfo instanceof KtClassOrObjectInfo) {
                //noinspection RedundantCast
                return getClassDescriptor(((KtClassOrObjectInfo) classLikeInfo).getCorrespondingClassOrObject(), location);
            } else if (classLikeInfo instanceof KtScriptInfo) {
                return getScriptDescriptor(((KtScriptInfo) classLikeInfo).getScript());
            } else {
                throw new IllegalStateException("Unexpected " + classLikeInfo + " of type " + classLikeInfo.getClass().getName());
            }
        }
    }));
    result.addAll(ContainerUtil.map(provider.getTypeAliasDeclarations(fqName.shortName()), new Function<KtTypeAlias, ClassifierDescriptor>() {

        @Override
        public ClassifierDescriptor fun(KtTypeAlias alias) {
            return (ClassifierDescriptor) lazyDeclarationResolver.resolveToDescriptor(alias);
        }
    }));
    return result;
}
Also used : Function(com.intellij.util.Function) KtClassLikeInfo(org.jetbrains.kotlin.resolve.lazy.data.KtClassLikeInfo) PackageMemberDeclarationProvider(org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider) KtScriptInfo(org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo) SmartList(org.jetbrains.kotlin.utils.SmartList) KtClassOrObjectInfo(org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo) ReadOnly(org.jetbrains.annotations.ReadOnly) NotNull(org.jetbrains.annotations.NotNull)

Example 47 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class PyExtractSuperclassHelper method extractSuperclass.

static void extractSuperclass(final PyClass clazz, @NotNull Collection<PyMemberInfo<PyElement>> selectedMemberInfos, final String superBaseName, final String targetFile) {
    final Project project = clazz.getProject();
    //We will need to change it probably while param may be read-only
    //noinspection AssignmentToMethodParameter
    selectedMemberInfos = new ArrayList<>(selectedMemberInfos);
    final RefactoringEventData beforeData = new RefactoringEventData();
    beforeData.addElements(JBIterable.from(selectedMemberInfos).transform((Function<PyMemberInfo<PyElement>, PsiElement>) info -> info.getMember()).toList());
    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(getRefactoringId(), beforeData);
    // PY-12171
    final PyMemberInfo<PyElement> objectMember = MembersManager.findMember(selectedMemberInfos, ALLOW_OBJECT);
    if (LanguageLevel.forElement(clazz).isPy3K() && !isObjectParentDeclaredExplicitly(clazz)) {
        // Remove object from list if Py3
        if (objectMember != null) {
            selectedMemberInfos.remove(objectMember);
        }
    } else {
        // Always add object if < Py3
        if (objectMember == null) {
            final PyMemberInfo<PyElement> object = MembersManager.findMember(clazz, ALLOW_OBJECT);
            if (object != null) {
                selectedMemberInfos.add(object);
            }
        }
    }
    final String text = "class " + superBaseName + ":\n  pass" + "\n";
    PyClass newClass = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyClass.class, text);
    newClass = placeNewClass(project, newClass, clazz, targetFile);
    MembersManager.moveAllMembers(selectedMemberInfos, clazz, newClass);
    if (!newClass.getContainingFile().equals(clazz.getContainingFile())) {
        // To remove unneeded imports only if user used different file
        PyClassRefactoringUtil.optimizeImports(clazz.getContainingFile());
    }
    PyClassRefactoringUtil.addSuperclasses(project, clazz, null, newClass);
    final RefactoringEventData afterData = new RefactoringEventData();
    afterData.addElement(newClass);
    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(getRefactoringId(), afterData);
}
Also used : PyNames(com.jetbrains.python.PyNames) Arrays(java.util.Arrays) JBIterable(com.intellij.util.containers.JBIterable) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) RefactoringEventListener(com.intellij.refactoring.listeners.RefactoringEventListener) VirtualFileManager(com.intellij.openapi.vfs.VirtualFileManager) ArrayList(java.util.ArrayList) PyClassRefactoringUtil(com.jetbrains.python.refactoring.classes.PyClassRefactoringUtil) Comparing(com.intellij.openapi.util.Comparing) Project(com.intellij.openapi.project.Project) com.jetbrains.python.psi(com.jetbrains.python.psi) FileUtil(com.intellij.openapi.util.io.FileUtil) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) Logger(com.intellij.openapi.diagnostic.Logger) ProjectRootManager(com.intellij.openapi.roots.ProjectRootManager) PythonFileType(com.jetbrains.python.PythonFileType) VfsUtilCore(com.intellij.openapi.vfs.VfsUtilCore) Collection(java.util.Collection) IOException(java.io.IOException) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) MembersManager(com.jetbrains.python.refactoring.classes.membersManager.MembersManager) Nullable(org.jetbrains.annotations.Nullable) Predicate(com.google.common.base.Predicate) Function(com.intellij.util.Function) ApplicationManagerEx(com.intellij.openapi.application.ex.ApplicationManagerEx) com.intellij.psi(com.intellij.psi) PathUtil(com.intellij.util.PathUtil) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) PyMemberInfo(com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo) Project(com.intellij.openapi.project.Project) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) PyMemberInfo(com.jetbrains.python.refactoring.classes.membersManager.PyMemberInfo)

Example 48 with Function

use of com.intellij.util.Function in project intellij-community by JetBrains.

the class PyChangeSignatureTest method testAnnotationsForStarredParametersAreNotShownInDialog.

// PY-14774
public void testAnnotationsForStarredParametersAreNotShownInDialog() throws Exception {
    runWithLanguageLevel(LanguageLevel.PYTHON30, () -> {
        myFixture.configureByText(PythonFileType.INSTANCE, "def func(a, b:int, *args: tuple, c:list, d:str='foo', ** kwargs:dict):\n" + "    pass");
        final PyFunction function = (PyFunction) new PyChangeSignatureHandler().findTargetMember(myFixture.getFile(), myFixture.getEditor());
        assertNotNull(function);
        final List<String> expected = Arrays.asList("a", "b", "*args", "c", "d", "**kwargs");
        final List<PyParameterInfo> parameters = new PyMethodDescriptor(function).getParameters();
        assertEquals(expected, ContainerUtil.map(parameters, info -> info.getOldName()));
    });
}
Also used : Arrays(java.util.Arrays) PyBundle(com.jetbrains.python.PyBundle) BaseRefactoringProcessor(com.intellij.refactoring.BaseRefactoringProcessor) ContainerUtil(com.intellij.util.containers.ContainerUtil) LanguageLevel(com.jetbrains.python.psi.LanguageLevel) TestDataPath(com.intellij.testFramework.TestDataPath) PyTestCase(com.jetbrains.python.fixtures.PyTestCase) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) DocStringFormat(com.jetbrains.python.documentation.docstrings.DocStringFormat) Function(com.intellij.util.Function) Disposer(com.intellij.openapi.util.Disposer) Project(com.intellij.openapi.project.Project) PythonFileType(com.jetbrains.python.PythonFileType) PyFunction(com.jetbrains.python.psi.PyFunction) PyFunction(com.jetbrains.python.psi.PyFunction)

Example 49 with Function

use of com.intellij.util.Function in project kotlin by JetBrains.

the class KtParsingTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    initApplication();
    ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName());
    Extensions.registerAreaClass("IDEA_PROJECT", null);
    myProject = new MockProjectEx(getTestRootDisposable());
    myPsiManager = new MockPsiManager(myProject);
    myFileFactory = new PsiFileFactoryImpl(myPsiManager);
    MutablePicoContainer appContainer = getApplication().getPicoContainer();
    registerComponentInstance(appContainer, MessageBus.class, MessageBusFactory.newMessageBus(getApplication()));
    registerComponentInstance(appContainer, SchemesManagerFactory.class, new MockSchemesManagerFactory());
    final MockEditorFactory editorFactory = new MockEditorFactory();
    registerComponentInstance(appContainer, EditorFactory.class, editorFactory);
    registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(new Function<CharSequence, Document>() {

        @Override
        public Document fun(CharSequence charSequence) {
            return editorFactory.createDocument(charSequence);
        }
    }, HARD_REF_TO_DOCUMENT_KEY));
    registerComponentInstance(appContainer, PsiDocumentManager.class, new MockPsiDocumentManager());
    registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl());
    registerApplicationService(DefaultASTFactory.class, new CoreASTFactory());
    registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl());
    registerApplicationService(ProgressManager.class, new CoreProgressManager());
    myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager)));
    myProject.registerService(PsiManager.class, myPsiManager);
    this.registerExtensionPoint(FileTypeFactory.FILE_TYPE_FACTORY_EP, FileTypeFactory.class);
    for (ParserDefinition definition : myDefinitions) {
        addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition);
    }
    if (myDefinitions.length > 0) {
        configureFromParserDefinition(myDefinitions[0], myFileExt);
    }
    // That's for reparse routines
    final PomModelImpl pomModel = new PomModelImpl(myProject);
    myProject.registerService(PomModel.class, pomModel);
    new TreeAspect(pomModel);
}
Also used : MutablePicoContainer(org.picocontainer.MutablePicoContainer) CoreProgressManager(com.intellij.openapi.progress.impl.CoreProgressManager) MockFileDocumentManagerImpl(com.intellij.mock.MockFileDocumentManagerImpl) TreeAspect(com.intellij.pom.tree.TreeAspect) CachedValuesManagerImpl(com.intellij.util.CachedValuesManagerImpl) CoreASTFactory(com.intellij.core.CoreASTFactory) PsiBuilderFactoryImpl(com.intellij.lang.impl.PsiBuilderFactoryImpl) Function(com.intellij.util.Function) PsiCachedValuesFactory(com.intellij.psi.impl.PsiCachedValuesFactory) ProgressManager(com.intellij.openapi.progress.ProgressManager) CoreProgressManager(com.intellij.openapi.progress.impl.CoreProgressManager) ReferenceProvidersRegistryImpl(com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl) PsiFileFactoryImpl(com.intellij.psi.impl.PsiFileFactoryImpl) PomModelImpl(com.intellij.pom.core.impl.PomModelImpl) ComponentAdapter(org.picocontainer.ComponentAdapter)

Example 50 with Function

use of com.intellij.util.Function in project kotlin by JetBrains.

the class MemberMatching method typeParametersMatch.

static boolean typeParametersMatch(@NotNull KtTypeParameterListOwner typeParameterListOwner, @NotNull List<TypeParameterDescriptor> typeParameterDescriptors) {
    List<KtTypeParameter> decompiledParameters = typeParameterListOwner.getTypeParameters();
    if (decompiledParameters.size() != typeParameterDescriptors.size()) {
        return false;
    }
    Multimap<Name, String> decompiledParameterToBounds = HashMultimap.create();
    for (KtTypeParameter parameter : decompiledParameters) {
        KtTypeReference extendsBound = parameter.getExtendsBound();
        if (extendsBound != null) {
            decompiledParameterToBounds.put(parameter.getNameAsName(), extendsBound.getText());
        }
    }
    for (KtTypeConstraint typeConstraint : typeParameterListOwner.getTypeConstraints()) {
        KtSimpleNameExpression typeParameterName = typeConstraint.getSubjectTypeParameterName();
        assert typeParameterName != null;
        KtTypeReference bound = typeConstraint.getBoundTypeReference();
        assert bound != null;
        decompiledParameterToBounds.put(typeParameterName.getReferencedNameAsName(), bound.getText());
    }
    for (int i = 0; i < decompiledParameters.size(); i++) {
        KtTypeParameter decompiledParameter = decompiledParameters.get(i);
        TypeParameterDescriptor descriptor = typeParameterDescriptors.get(i);
        Name name = decompiledParameter.getNameAsName();
        assert name != null;
        if (!name.equals(descriptor.getName())) {
            return false;
        }
        Set<String> descriptorUpperBounds = Sets.newHashSet(ContainerUtil.map(descriptor.getUpperBounds(), new Function<KotlinType, String>() {

            @Override
            public String fun(KotlinType type) {
                return DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type);
            }
        }));
        KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor);
        Set<String> decompiledUpperBounds = decompiledParameterToBounds.get(descriptor.getName()).isEmpty() ? Sets.newHashSet(DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(builtIns.getDefaultBound())) : Sets.newHashSet(decompiledParameterToBounds.get(descriptor.getName()));
        if (!descriptorUpperBounds.equals(decompiledUpperBounds)) {
            return false;
        }
    }
    return true;
}
Also used : TypeParameterDescriptor(org.jetbrains.kotlin.descriptors.TypeParameterDescriptor) KotlinType(org.jetbrains.kotlin.types.KotlinType) Name(org.jetbrains.kotlin.name.Name) Function(com.intellij.util.Function) KotlinBuiltIns(org.jetbrains.kotlin.builtins.KotlinBuiltIns)

Aggregations

Function (com.intellij.util.Function)53 NotNull (org.jetbrains.annotations.NotNull)32 Nullable (org.jetbrains.annotations.Nullable)24 Project (com.intellij.openapi.project.Project)23 Logger (com.intellij.openapi.diagnostic.Logger)19 VirtualFile (com.intellij.openapi.vfs.VirtualFile)15 ContainerUtil (com.intellij.util.containers.ContainerUtil)15 List (java.util.List)15 StringUtil (com.intellij.openapi.util.text.StringUtil)12 Module (com.intellij.openapi.module.Module)11 com.intellij.psi (com.intellij.psi)11 java.util (java.util)10 ArrayList (java.util.ArrayList)10 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)9 ApplicationManager (com.intellij.openapi.application.ApplicationManager)8 PsiElement (com.intellij.psi.PsiElement)7 File (java.io.File)7 Messages (com.intellij.openapi.ui.Messages)6 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)6 IOException (java.io.IOException)6