Search in sources :

Example 11 with TypeEvalContext

use of com.jetbrains.python.psi.types.TypeEvalContext in project intellij-community by JetBrains.

the class PyLineMarkerProvider method getMethodMarker.

@Nullable
private static LineMarkerInfo<PsiElement> getMethodMarker(final PsiElement element, final PyFunction function) {
    if (PyNames.INIT.equals(function.getName())) {
        return null;
    }
    final TypeEvalContext context = TypeEvalContext.codeAnalysis(element.getProject(), (function != null ? function.getContainingFile() : null));
    final PsiElement superMethod = PySuperMethodsSearch.search(function, context).findFirst();
    if (superMethod != null) {
        PyClass superClass = null;
        if (superMethod instanceof PyFunction) {
            superClass = ((PyFunction) superMethod).getContainingClass();
        }
        // TODO: show "implementing" instead of "overriding" icon for Python implementations of Java interface methods
        return new LineMarkerInfo<PsiElement>(element, element.getTextRange().getStartOffset(), AllIcons.Gutter.OverridingMethod, Pass.LINE_MARKERS, superClass == null ? null : new TooltipProvider("Overrides method in " + superClass.getName()), ourSuperMethodNavigator);
    }
    return null;
}
Also used : PyClass(com.jetbrains.python.psi.PyClass) LineMarkerInfo(com.intellij.codeInsight.daemon.LineMarkerInfo) PyFunction(com.jetbrains.python.psi.PyFunction) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PsiElement(com.intellij.psi.PsiElement) Nullable(org.jetbrains.annotations.Nullable)

Example 12 with TypeEvalContext

use of com.jetbrains.python.psi.types.TypeEvalContext in project intellij-community by JetBrains.

the class PyDictKeyNamesCompletionContributor method addDictConstructorKeys.

/**
   * add keys to completion result from dict constructor
   */
private static void addDictConstructorKeys(final PyCallExpression dictConstructor, final CompletionResultSet result) {
    final PyExpression callee = dictConstructor.getCallee();
    if (callee == null)
        return;
    final String name = callee.getText();
    if ("dict".equals(name)) {
        final TypeEvalContext context = TypeEvalContext.codeCompletion(callee.getProject(), callee.getContainingFile());
        final PyType type = context.getType(dictConstructor);
        if (type != null && type.isBuiltin()) {
            final PyArgumentList list = dictConstructor.getArgumentList();
            if (list == null)
                return;
            final PyExpression[] argumentList = list.getArguments();
            for (final PyExpression argument : argumentList) {
                if (argument instanceof PyKeywordArgument) {
                    result.addElement(createElement("'" + ((PyKeywordArgument) argument).getKeyword() + "'"));
                }
            }
        }
    }
}
Also used : PyType(com.jetbrains.python.psi.types.PyType) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext)

Example 13 with TypeEvalContext

use of com.jetbrains.python.psi.types.TypeEvalContext in project intellij-community by JetBrains.

the class IntroduceHandler method generateSuggestedNames.

protected Collection<String> generateSuggestedNames(PyExpression expression) {
    Collection<String> candidates = new LinkedHashSet<String>() {

        @Override
        public boolean add(String s) {
            if (PyNames.isReserved(s)) {
                return false;
            }
            return super.add(s);
        }
    };
    String text = expression.getText();
    final Pair<PsiElement, TextRange> selection = expression.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE);
    if (selection != null) {
        text = selection.getSecond().substring(selection.getFirst().getText());
    }
    if (expression instanceof PyCallExpression) {
        final PyExpression callee = ((PyCallExpression) expression).getCallee();
        if (callee != null) {
            text = callee.getText();
        }
    }
    if (text != null) {
        candidates.addAll(NameSuggesterUtil.generateNames(text));
    }
    final TypeEvalContext context = TypeEvalContext.userInitiated(expression.getProject(), expression.getContainingFile());
    PyType type = context.getType(expression);
    if (type != null && type != PyNoneType.INSTANCE) {
        String typeName = type.getName();
        if (typeName != null) {
            if (type.isBuiltin()) {
                typeName = typeName.substring(0, 1);
            }
            candidates.addAll(NameSuggesterUtil.generateNamesByType(typeName));
        }
    }
    final PyKeywordArgument kwArg = PsiTreeUtil.getParentOfType(expression, PyKeywordArgument.class);
    if (kwArg != null && kwArg.getValueExpression() == expression) {
        candidates.add(kwArg.getKeyword());
    }
    Optional.ofNullable(PsiTreeUtil.getParentOfType(expression, PyArgumentList.class)).map(PyArgumentList::getCallExpression).ifPresent(call -> StreamEx.of(call.multiMapArguments(PyResolveContext.noImplicits())).map(mapping -> mapping.getMappedParameters().get(expression)).nonNull().map(PyNamedParameter::getName).forEach(candidates::add));
    return candidates;
}
Also used : TextRange(com.intellij.openapi.util.TextRange) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyType(com.jetbrains.python.psi.types.PyType)

Example 14 with TypeEvalContext

use of com.jetbrains.python.psi.types.TypeEvalContext 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)

Example 15 with TypeEvalContext

use of com.jetbrains.python.psi.types.TypeEvalContext in project intellij-community by JetBrains.

the class PyParameterInfoHandler method findElementForParameterInfo.

@Override
@Nullable
public PyArgumentList findElementForParameterInfo(@NotNull CreateParameterInfoContext context) {
    final PyArgumentList argumentList = findArgumentList(context, -1);
    if (argumentList != null) {
        final PyCallExpression call = argumentList.getCallExpression();
        if (call != null) {
            final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(argumentList.getProject(), argumentList.getContainingFile());
            final PyResolveContext resolveContext = PyResolveContext.noImplicits().withRemote().withTypeEvalContext(typeEvalContext);
            final Object[] items = PyUtil.filterTopPriorityResults(call.multiResolveRatedCallee(resolveContext)).stream().map(ratedMarkedCallee -> Pair.createNonNull(call, ratedMarkedCallee.getMarkedCallee())).toArray();
            context.setItemsToShow(items);
            return argumentList;
        }
    }
    return null;
}
Also used : TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) com.intellij.lang.parameterInfo(com.intellij.lang.parameterInfo) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) LookupElement(com.intellij.codeInsight.lookup.LookupElement) ParamHelper(com.jetbrains.python.psi.impl.ParamHelper) TextRange(com.intellij.openapi.util.TextRange) PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) PyPsiUtils(com.jetbrains.python.psi.impl.PyPsiUtils) CodeInsightBundle(com.intellij.codeInsight.CodeInsightBundle) Nullable(org.jetbrains.annotations.Nullable) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Pair(com.intellij.openapi.util.Pair) PsiElement(com.intellij.psi.PsiElement) PsiFile(com.intellij.psi.PsiFile) XmlStringUtil(com.intellij.xml.util.XmlStringUtil) com.jetbrains.python.psi(com.jetbrains.python.psi) PyMarkedCallee(com.jetbrains.python.psi.PyCallExpression.PyMarkedCallee) PyCallExpressionHelper(com.jetbrains.python.psi.impl.PyCallExpressionHelper) NotNull(org.jetbrains.annotations.NotNull) CharArrayUtil(com.intellij.util.text.CharArrayUtil) PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)44 PyType (com.jetbrains.python.psi.types.PyType)15 PsiElement (com.intellij.psi.PsiElement)13 NotNull (org.jetbrains.annotations.NotNull)10 Nullable (org.jetbrains.annotations.Nullable)8 PyResolveContext (com.jetbrains.python.psi.resolve.PyResolveContext)6 PyClassLikeType (com.jetbrains.python.psi.types.PyClassLikeType)5 ArrayList (java.util.ArrayList)5 ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)4 com.jetbrains.python.psi (com.jetbrains.python.psi)4 TextRange (com.intellij.openapi.util.TextRange)3 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)3 XmlStringUtil (com.intellij.xml.util.XmlStringUtil)3 PyNames (com.jetbrains.python.PyNames)3 PyFunction (com.jetbrains.python.psi.PyFunction)3 PyClassType (com.jetbrains.python.psi.types.PyClassType)3 Lists (com.google.common.collect.Lists)2 Instruction (com.intellij.codeInsight.controlflow.Instruction)2 LookupElement (com.intellij.codeInsight.lookup.LookupElement)2 ASTNode (com.intellij.lang.ASTNode)2