Search in sources :

Example 1 with PyResolveContext

use of com.jetbrains.python.psi.resolve.PyResolveContext in project intellij-community by JetBrains.

the class PyTypingTypeProvider method tryResolving.

@NotNull
private static List<PsiElement> tryResolving(@NotNull PyExpression expression, @NotNull TypeEvalContext context) {
    final List<PsiElement> elements = Lists.newArrayList();
    if (expression instanceof PyReferenceExpression) {
        final PyReferenceExpression referenceExpr = (PyReferenceExpression) expression;
        final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context);
        final PsiPolyVariantReference reference = referenceExpr.getReference(resolveContext);
        final List<PsiElement> resolved = PyUtil.multiResolveTopPriority(reference);
        for (PsiElement element : resolved) {
            if (element instanceof PyFunction) {
                final PyFunction function = (PyFunction) element;
                if (PyUtil.isInit(function)) {
                    final PyClass cls = function.getContainingClass();
                    if (cls != null) {
                        elements.add(cls);
                        continue;
                    }
                }
            }
            final String name = element != null ? getQualifiedName(element) : null;
            if (name != null && OPAQUE_NAMES.contains(name)) {
                elements.add(element);
                continue;
            }
            if (element instanceof PyTargetExpression) {
                final PyTargetExpression targetExpr = (PyTargetExpression) element;
                // XXX: Requires switching from stub to AST
                final PyExpression assignedValue = targetExpr.findAssignedValue();
                if (assignedValue != null) {
                    elements.add(assignedValue);
                    continue;
                }
            }
            if (element != null) {
                elements.add(element);
            }
        }
    }
    return !elements.isEmpty() ? elements : Collections.singletonList(expression);
}
Also used : PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PsiElement(com.intellij.psi.PsiElement) PsiPolyVariantReference(com.intellij.psi.PsiPolyVariantReference) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with PyResolveContext

use of com.jetbrains.python.psi.resolve.PyResolveContext in project intellij-community by JetBrains.

the class PyUnusedLocalInspectionVisitor method isRangeIteration.

private boolean isRangeIteration(@NotNull PyForStatement forStatement) {
    final PyExpression source = forStatement.getForPart().getSource();
    if (!(source instanceof PyCallExpression)) {
        return false;
    }
    final PyCallExpression expr = (PyCallExpression) source;
    if (expr.isCalleeText("range", "xrange")) {
        final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext);
        final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(forStatement);
        return ContainerUtil.exists(expr.multiResolveCalleeFunction(resolveContext), builtinCache::isBuiltin);
    }
    return false;
}
Also used : PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PyBuiltinCache(com.jetbrains.python.psi.impl.PyBuiltinCache)

Example 3 with PyResolveContext

use of com.jetbrains.python.psi.resolve.PyResolveContext in project intellij-community by JetBrains.

the class PyReplaceTupleWithListQuickFix method applyFix.

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    assert element instanceof PyAssignmentStatement;
    PyExpression[] targets = ((PyAssignmentStatement) element).getTargets();
    if (targets.length == 1 && targets[0] instanceof PySubscriptionExpression) {
        PySubscriptionExpression subscriptionExpression = (PySubscriptionExpression) targets[0];
        if (subscriptionExpression.getOperand() instanceof PyReferenceExpression) {
            PyReferenceExpression referenceExpression = (PyReferenceExpression) subscriptionExpression.getOperand();
            final TypeEvalContext context = TypeEvalContext.userInitiated(project, element.getContainingFile());
            final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context);
            element = referenceExpression.followAssignmentsChain(resolveContext).getElement();
            if (element instanceof PyParenthesizedExpression) {
                final PyExpression expression = ((PyParenthesizedExpression) element).getContainedExpression();
                replaceWithListLiteral(element, (PyTupleExpression) expression);
            } else if (element instanceof PyTupleExpression) {
                replaceWithListLiteral(element, (PyTupleExpression) element);
            }
        }
    }
}
Also used : PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PsiElement(com.intellij.psi.PsiElement) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext)

Example 4 with PyResolveContext

use of com.jetbrains.python.psi.resolve.PyResolveContext in project intellij-community by JetBrains.

the class PyRemoveParameterQuickFix method applyFix.

public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement parameter = descriptor.getPsiElement();
    assert parameter instanceof PyParameter;
    final PyFunction function = PsiTreeUtil.getParentOfType(parameter, PyFunction.class);
    if (function != null) {
        final PyResolveContext resolveContext = PyResolveContext.noImplicits();
        StreamEx.of(PyRefactoringUtil.findUsages(function, false)).map(UsageInfo::getElement).nonNull().map(PsiElement::getParent).select(PyCallExpression.class).flatMap(callExpression -> callExpression.multiMapArguments(resolveContext).stream()).flatMap(mapping -> mapping.getMappedParameters().entrySet().stream()).filter(entry -> entry.getValue() == parameter).forEach(entry -> entry.getKey().delete());
        final PyStringLiteralExpression docStringExpression = function.getDocStringExpression();
        final String parameterName = ((PyParameter) parameter).getName();
        if (docStringExpression != null && parameterName != null) {
            PyDocstringGenerator.forDocStringOwner(function).withoutParam(parameterName).buildAndInsert();
        }
    }
    parameter.delete();
}
Also used : PyBundle(com.jetbrains.python.PyBundle) PyStringLiteralExpression(com.jetbrains.python.psi.PyStringLiteralExpression) UsageInfo(com.intellij.usageView.UsageInfo) PyParameter(com.jetbrains.python.psi.PyParameter) PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PyRefactoringUtil(com.jetbrains.python.refactoring.PyRefactoringUtil) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) PyCallExpression(com.jetbrains.python.psi.PyCallExpression) ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) StreamEx(one.util.streamex.StreamEx) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PyDocstringGenerator(com.jetbrains.python.documentation.docstrings.PyDocstringGenerator) NotNull(org.jetbrains.annotations.NotNull) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) PyFunction(com.jetbrains.python.psi.PyFunction) PyFunction(com.jetbrains.python.psi.PyFunction) PyStringLiteralExpression(com.jetbrains.python.psi.PyStringLiteralExpression) PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PsiElement(com.intellij.psi.PsiElement) PyParameter(com.jetbrains.python.psi.PyParameter)

Example 5 with PyResolveContext

use of com.jetbrains.python.psi.resolve.PyResolveContext in project intellij-community by JetBrains.

the class PyMoveFileHandler method retargetUsages.

@Override
public void retargetUsages(List<UsageInfo> usages, Map<PsiElement, PsiElement> oldToNewMap) {
    final Set<PsiFile> updatedFiles = new HashSet<>();
    for (UsageInfo usage : usages) {
        final PsiElement usageElement = usage.getElement();
        if (usageElement != null) {
            final PsiNamedElement movedElement = usageElement.getCopyableUserData(REFERENCED_ELEMENT);
            usageElement.putCopyableUserData(REFERENCED_ELEMENT, null);
            if (movedElement != null) {
                final PsiFile usageFile = usageElement.getContainingFile();
                final PyImportStatementBase importStmt = PsiTreeUtil.getParentOfType(usageElement, PyImportStatementBase.class);
                // TODO: Retarget qualified expressions in docstrings
                if (importStmt != null) {
                    if (usageFile.getUserData(ORIGINAL_FILE_LOCATION) != null) {
                        // Leave relative imports as they are after #updateRelativeImportsInModule
                        final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(usageFile.getProject(), usageFile);
                        final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(typeEvalContext);
                        if (ContainerUtil.getFirstItem(PyUtil.multiResolveTopPriority(usageElement, resolveContext)) == movedElement) {
                            continue;
                        }
                    }
                    updatedFiles.add(usageFile);
                    final boolean usageInsideImportElement = PsiTreeUtil.getParentOfType(usageElement, PyImportElement.class) != null;
                    if (usageInsideImportElement) {
                        // or simple unqualified import of the module (import module).
                        if (PyClassRefactoringUtil.updateUnqualifiedImportOfElement(importStmt, movedElement)) {
                            continue;
                        }
                    }
                    final QualifiedName newElementName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
                    if (importStmt instanceof PyFromImportStatement) {
                        if (!usageInsideImportElement) {
                            replaceRelativeImportSourceWithQualifiedExpression((PyFromImportStatement) importStmt, newElementName);
                        }
                    } else {
                        replaceWithQualifiedExpression(usageElement, newElementName);
                    }
                } else if (usageElement instanceof PyReferenceExpression) {
                    updatedFiles.add(usageFile);
                    if (((PyReferenceExpression) usageElement).isQualified()) {
                        final QualifiedName newQualifiedName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
                        replaceWithQualifiedExpression(usageElement, newQualifiedName);
                    } else {
                        final QualifiedName newName = QualifiedName.fromComponents(PyClassRefactoringUtil.getOriginalName(movedElement));
                        replaceWithQualifiedExpression(usageElement, newName);
                    }
                }
            }
        }
    }
    if (!updatedFiles.isEmpty()) {
        final PyImportOptimizer optimizer = new PyImportOptimizer();
        for (PsiFile file : updatedFiles) {
            final boolean injectedFragment = InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file);
            if (!injectedFragment) {
                optimizer.processFile(file).run();
            }
        }
    }
}
Also used : PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) QualifiedName(com.intellij.psi.util.QualifiedName) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyImportOptimizer(com.jetbrains.python.codeInsight.imports.PyImportOptimizer) UsageInfo(com.intellij.usageView.UsageInfo)

Aggregations

PyResolveContext (com.jetbrains.python.psi.resolve.PyResolveContext)27 PsiElement (com.intellij.psi.PsiElement)12 NotNull (org.jetbrains.annotations.NotNull)11 Nullable (org.jetbrains.annotations.Nullable)11 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)6 com.jetbrains.python.psi (com.jetbrains.python.psi)6 ContainerUtil (com.intellij.util.containers.ContainerUtil)5 RatedResolveResult (com.jetbrains.python.psi.resolve.RatedResolveResult)5 TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)5 java.util (java.util)5 LookupElement (com.intellij.codeInsight.lookup.LookupElement)4 Extensions (com.intellij.openapi.extensions.Extensions)4 PsiFile (com.intellij.psi.PsiFile)4 ArrayUtil (com.intellij.util.ArrayUtil)4 Processor (com.intellij.util.Processor)4 PyNames (com.jetbrains.python.PyNames)4 Collectors (java.util.stream.Collectors)4 Sets (com.google.common.collect.Sets)3 Pair (com.intellij.openapi.util.Pair)3 QualifiedName (com.intellij.psi.util.QualifiedName)3