Search in sources :

Example 6 with PyBuiltinCache

use of com.jetbrains.python.psi.impl.PyBuiltinCache in project intellij-community by JetBrains.

the class ConvertFormatOperatorToMethodIntention method doInvoke.

@Override
public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    final PsiElement elementAt = file.findElementAt(editor.getCaretModel().getOffset());
    final PyBinaryExpression element = PsiTreeUtil.getParentOfType(elementAt, PyBinaryExpression.class, false);
    if (element == null)
        return;
    final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
    final PyExpression rightExpression = sure(element).getRightExpression();
    if (rightExpression == null) {
        return;
    }
    final PyExpression rhs = PyPsiUtils.flattenParens(rightExpression);
    if (rhs == null)
        return;
    final String paramText = sure(rhs).getText();
    final TypeEvalContext context = TypeEvalContext.userInitiated(file.getProject(), file);
    final PyType rhsType = context.getType(rhs);
    String prefix = "";
    final LanguageLevel languageLevel = guessLanguageLevel(project);
    final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(rhs);
    if (!languageLevel.isPy3K() && PyTypeChecker.match(builtinCache.getUnicodeType(languageLevel), rhsType, context) && !PyTypeChecker.match(builtinCache.getBytesType(languageLevel), rhsType, context)) {
        prefix = "u";
    }
    final PyStringLiteralExpression leftExpression = (PyStringLiteralExpression) element.getLeftExpression();
    final Pair<StringBuilder, Boolean> converted = convertFormat(leftExpression, prefix);
    final StringBuilder target = converted.getFirst();
    final String separator = getSeparator(leftExpression);
    target.append(separator).append(".format");
    if (rhs instanceof PyReferenceExpression && rhsType instanceof PyTupleType) {
        target.append("(*").append(paramText).append(")");
    } else if (rhs instanceof PyCallExpression) {
        // potential dict(foo=1) -> format(foo=1)
        final PyCallExpression callExpression = (PyCallExpression) rhs;
        final PyExpression callee = callExpression.getCallee();
        final PyClassType classType = PyUtil.as(rhsType, PyClassType.class);
        if (classType != null && callee != null && isDictCall(callee, classType)) {
            target.append(sure(sure(callExpression.getArgumentList()).getNode()).getChars());
        } else {
            // just a call, reuse
            target.append("(");
            // map-by-name formatting was detected
            if (converted.getSecond())
                target.append("**");
            target.append(paramText).append(")");
        }
    } else if (rhsType instanceof PyCollectionType && "dict".equals(rhsType.getName())) {
        target.append("(**").append(paramText).append(")");
    } else
        // tuple is ok as is
        target.append("(").append(paramText).append(")");
    // Correctly handle multiline implicitly concatenated string literals (PY-9176)
    target.insert(0, '(').append(')');
    final PyExpression parenthesized = elementGenerator.createExpressionFromText(LanguageLevel.forElement(element), target.toString());
    element.replace(sure(((PyParenthesizedExpression) parenthesized).getContainedExpression()));
}
Also used : PyUtil.guessLanguageLevel(com.jetbrains.python.psi.PyUtil.guessLanguageLevel) PsiElement(com.intellij.psi.PsiElement) PyBuiltinCache(com.jetbrains.python.psi.impl.PyBuiltinCache)

Example 7 with PyBuiltinCache

use of com.jetbrains.python.psi.impl.PyBuiltinCache in project intellij-community by JetBrains.

the class PyStringConcatenationToFormatIntention method isAvailable.

public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!(file instanceof PyFile)) {
        return false;
    }
    PsiElement element = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyBinaryExpression.class, false);
    if (element == null) {
        return false;
    }
    while (element.getParent() instanceof PyBinaryExpression) {
        element = element.getParent();
    }
    final Collection<PyElementType> operators = getOperators((PyBinaryExpression) element);
    for (PyElementType operator : operators) {
        if (operator != PyTokenTypes.PLUS) {
            return false;
        }
    }
    final Collection<PyExpression> expressions = getSimpleExpressions((PyBinaryExpression) element);
    if (expressions.size() == 0) {
        return false;
    }
    final PyBuiltinCache cache = PyBuiltinCache.getInstance(element);
    for (PyExpression expression : expressions) {
        if (expression == null) {
            return false;
        }
        if (expression instanceof PyStringLiteralExpression)
            continue;
        final PyType type = TypeEvalContext.codeAnalysis(file.getProject(), file).getType(expression);
        final boolean isStringReference = PyTypeChecker.match(cache.getStringType(LanguageLevel.forElement(expression)), type, TypeEvalContext.codeAnalysis(file.getProject(), file)) && type != null;
        if (!isStringReference) {
            return false;
        }
    }
    if (LanguageLevel.forElement(element).isAtLeast(LanguageLevel.PYTHON27))
        setText(PyBundle.message("INTN.replace.plus.with.str.format"));
    else
        setText(PyBundle.message("INTN.replace.plus.with.format.operator"));
    return true;
}
Also used : PyType(com.jetbrains.python.psi.types.PyType) PsiElement(com.intellij.psi.PsiElement) PyBuiltinCache(com.jetbrains.python.psi.impl.PyBuiltinCache)

Example 8 with PyBuiltinCache

use of com.jetbrains.python.psi.impl.PyBuiltinCache 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 9 with PyBuiltinCache

use of com.jetbrains.python.psi.impl.PyBuiltinCache in project intellij-community by JetBrains.

the class PyChangeSignatureHandler method getSuperMethod.

@Nullable
protected static PyFunction getSuperMethod(@Nullable PyFunction function) {
    if (function == null) {
        return null;
    }
    final PyClass containingClass = function.getContainingClass();
    if (containingClass == null) {
        return function;
    }
    final PyFunction deepestSuperMethod = PySuperMethodsSearch.findDeepestSuperMethod(function);
    if (!deepestSuperMethod.equals(function)) {
        final PyClass baseClass = deepestSuperMethod.getContainingClass();
        final PyBuiltinCache cache = PyBuiltinCache.getInstance(baseClass);
        final String baseClassName = baseClass == null ? "" : baseClass.getName();
        if (cache.isBuiltin(baseClass)) {
            return function;
        }
        final String message = PyBundle.message("refactoring.change.signature.find.usages.of.base.class", function.getName(), containingClass.getName(), baseClassName);
        final int choice;
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            choice = Messages.YES;
        } else {
            choice = Messages.showYesNoCancelDialog(function.getProject(), message, REFACTORING_NAME, Messages.getQuestionIcon());
        }
        switch(choice) {
            case Messages.YES:
                return deepestSuperMethod;
            case Messages.NO:
                return function;
            default:
                return null;
        }
    }
    return function;
}
Also used : PyBuiltinCache(com.jetbrains.python.psi.impl.PyBuiltinCache) Nullable(org.jetbrains.annotations.Nullable)

Example 10 with PyBuiltinCache

use of com.jetbrains.python.psi.impl.PyBuiltinCache in project intellij by bazelbuild.

the class BlazePyBuiltinReferenceResolveProvider method resolveName.

@Override
public List<RatedResolveResult> resolveName(PyQualifiedExpression element, TypeEvalContext context) {
    if (!Blaze.isBlazeProject(element.getProject())) {
        return ImmutableList.of();
    }
    PyBuiltinCache cache = getBuiltInCache(element);
    if (cache == null) {
        return ImmutableList.of();
    }
    String referencedName = element.getReferencedName();
    if (referencedName == null) {
        return ImmutableList.of();
    }
    List<RatedResolveResult> result = Lists.newArrayList();
    PyFile bfile = cache.getBuiltinsFile();
    if (bfile != null && !PyUtil.isClassPrivateName(referencedName)) {
        PsiElement resultElement = bfile.getElementNamed(referencedName);
        if (resultElement == null && "__builtins__".equals(referencedName)) {
            // resolve __builtins__ reference
            resultElement = bfile;
        }
        if (resultElement != null) {
            result.add(new ImportedResolveResult(resultElement, PyReferenceImpl.getRate(resultElement, context), null));
        }
    }
    return result;
}
Also used : ImportedResolveResult(com.jetbrains.python.psi.resolve.ImportedResolveResult) PyFile(com.jetbrains.python.psi.PyFile) RatedResolveResult(com.jetbrains.python.psi.resolve.RatedResolveResult) PsiElement(com.intellij.psi.PsiElement) PyBuiltinCache(com.jetbrains.python.psi.impl.PyBuiltinCache)

Aggregations

PyBuiltinCache (com.jetbrains.python.psi.impl.PyBuiltinCache)10 PsiElement (com.intellij.psi.PsiElement)4 Nullable (org.jetbrains.annotations.Nullable)3 PyFile (com.jetbrains.python.psi.PyFile)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)1 PyUtil.guessLanguageLevel (com.jetbrains.python.psi.PyUtil.guessLanguageLevel)1 PyExpressionCodeFragmentImpl (com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl)1 ImportedResolveResult (com.jetbrains.python.psi.resolve.ImportedResolveResult)1 PyResolveContext (com.jetbrains.python.psi.resolve.PyResolveContext)1 RatedResolveResult (com.jetbrains.python.psi.resolve.RatedResolveResult)1 PyType (com.jetbrains.python.psi.types.PyType)1 ArrayList (java.util.ArrayList)1 NotNull (org.jetbrains.annotations.NotNull)1