Search in sources :

Example 1 with PyClassType

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

the class PyDebugProcess method typeToPosition.

@Nullable
private static XSourcePosition typeToPosition(PyType pyType) {
    final PyClassType classType = PyUtil.as(pyType, PyClassType.class);
    if (classType != null) {
        return XDebuggerUtil.getInstance().createPositionByElement(classType.getPyClass());
    }
    final PyModuleType moduleType = PyUtil.as(pyType, PyModuleType.class);
    if (moduleType != null) {
        return XDebuggerUtil.getInstance().createPositionByElement(moduleType.getModule());
    }
    return null;
}
Also used : PyClassType(com.jetbrains.python.psi.types.PyClassType) PyModuleType(com.jetbrains.python.psi.types.PyModuleType) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with PyClassType

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

the class PyOperatorReference method resolveMember.

@NotNull
private List<RatedResolveResult> resolveMember(@Nullable PyExpression object, @Nullable String name) {
    final ArrayList<RatedResolveResult> results = new ArrayList<>();
    if (object != null && name != null) {
        final TypeEvalContext typeEvalContext = myContext.getTypeEvalContext();
        PyType type = typeEvalContext.getType(object);
        typeEvalContext.trace("Side text is %s, type is %s", object.getText(), type);
        if (type instanceof PyClassLikeType) {
            if (((PyClassLikeType) type).isDefinition()) {
                type = ((PyClassLikeType) type).getMetaClassType(typeEvalContext, true);
            }
        }
        if (type != null) {
            List<? extends RatedResolveResult> res = type.resolveMember(name, object, AccessDirection.of(myElement), myContext);
            if (res != null && res.size() > 0) {
                results.addAll(res);
            } else if (typeEvalContext.tracing()) {
                VirtualFile vFile = null;
                if (type instanceof PyClassType) {
                    final PyClass pyClass = ((PyClassType) type).getPyClass();
                    vFile = pyClass.getContainingFile().getVirtualFile();
                }
                type.resolveMember(name, object, AccessDirection.of(myElement), myContext);
                typeEvalContext.trace("Could not resolve member %s in type %s from file %s", name, type, vFile);
            }
        }
    }
    return results;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PyClassType(com.jetbrains.python.psi.types.PyClassType) PyType(com.jetbrains.python.psi.types.PyType) ArrayList(java.util.ArrayList) PyClassLikeType(com.jetbrains.python.psi.types.PyClassLikeType) RatedResolveResult(com.jetbrains.python.psi.resolve.RatedResolveResult) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with PyClassType

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

the class PyAddSpecifierToFormatQuickFix method applyFix.

public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    final PyBinaryExpression expression = PsiTreeUtil.getParentOfType(element, PyBinaryExpression.class);
    if (expression == null)
        return;
    PyExpression rightExpression = expression.getRightExpression();
    if (rightExpression instanceof PyParenthesizedExpression) {
        rightExpression = ((PyParenthesizedExpression) rightExpression).getContainedExpression();
    }
    if (rightExpression == null)
        return;
    final PsiFile file = element.getContainingFile();
    final Document document = FileDocumentManager.getInstance().getDocument(file.getVirtualFile());
    if (document == null)
        return;
    final int offset = element.getTextOffset();
    final TypeEvalContext context = TypeEvalContext.userInitiated(file.getProject(), file);
    final PyClassType strType = PyBuiltinCache.getInstance(element).getStrType();
    final PyClassType floatType = PyBuiltinCache.getInstance(element).getFloatType();
    final PyClassType intType = PyBuiltinCache.getInstance(element).getIntType();
    final PyExpression leftExpression = expression.getLeftExpression();
    if (leftExpression instanceof PyStringLiteralExpression) {
        final List<PyStringFormatParser.SubstitutionChunk> chunks = filterSubstitutions(parsePercentFormat(((PyStringLiteralExpression) leftExpression).getStringValue()));
        PyExpression[] elements;
        if (rightExpression instanceof PyTupleExpression) {
            elements = ((PyTupleExpression) rightExpression).getElements();
        } else {
            elements = new PyExpression[] { rightExpression };
        }
        int shift = 2;
        for (int i = 0; i < chunks.size(); i++) {
            final PyStringFormatParser.SubstitutionChunk chunk = chunks.get(i);
            if (elements.length <= i)
                return;
            final PyType type = context.getType(elements[i]);
            final char conversionType = chunk.getConversionType();
            if (conversionType == '') {
                final int insertOffset = offset + chunk.getStartIndex() + shift;
                if (insertOffset > leftExpression.getTextRange().getEndOffset())
                    return;
                if (PyTypeChecker.match(strType, type, context)) {
                    document.insertString(insertOffset, "s");
                    shift += 1;
                }
                if (PyTypeChecker.match(intType, type, context) || PyTypeChecker.match(floatType, type, context)) {
                    document.insertString(insertOffset, "d");
                    shift += 1;
                }
            }
        }
    }
}
Also used : PyClassType(com.jetbrains.python.psi.types.PyClassType) Document(com.intellij.openapi.editor.Document) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyStringFormatParser(com.jetbrains.python.inspections.PyStringFormatParser) PyType(com.jetbrains.python.psi.types.PyType) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement)

Example 4 with PyClassType

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

the class PyCreatePropertyQuickFix method applyFix.

public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (element instanceof PyQualifiedExpression) {
        final PyExpression qualifier = ((PyQualifiedExpression) element).getQualifier();
        if (qualifier != null) {
            final PyType type = TypeEvalContext.codeAnalysis(element.getProject(), element.getContainingFile()).getType(qualifier);
            if (type instanceof PyClassType) {
                final PyClass cls = ((PyClassType) type).getPyClass();
                final String propertyName = ((PyQualifiedExpression) element).getName();
                if (propertyName == null)
                    return;
                final String fieldName = "_" + propertyName;
                final PyElementGenerator generator = PyElementGenerator.getInstance(project);
                final PyFunction property = generator.createProperty(LanguageLevel.forElement(cls), propertyName, fieldName, myAccessDirection);
                PyUtil.addElementToStatementList(property, cls.getStatementList(), myAccessDirection == AccessDirection.READ);
            }
        }
    }
}
Also used : PyClassType(com.jetbrains.python.psi.types.PyClassType) PyType(com.jetbrains.python.psi.types.PyType) PsiElement(com.intellij.psi.PsiElement)

Example 5 with PyClassType

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

the class AddMethodQuickFix method applyFix.

public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        // there can be no name clash, else the name would have resolved, and it hasn't.
        final PsiElement problemElement = descriptor.getPsiElement();
        final PyClassType type = getClassType(problemElement);
        if (type == null)
            return;
        final PyClass cls = type.getPyClass();
        boolean callByClass = type.isDefinition();
        PyStatementList clsStmtList = cls.getStatementList();
        sure(FileModificationService.getInstance().preparePsiElementForWrite(clsStmtList));
        // try to at least match parameter count
        // TODO: get parameter style from code style
        PyFunctionBuilder builder = new PyFunctionBuilder(myIdentifier, cls);
        PsiElement pe = problemElement.getParent();
        // set to non-null to add a decorator
        String decoratorName = null;
        PyExpression[] args = PyExpression.EMPTY_ARRAY;
        if (pe instanceof PyCallExpression) {
            PyArgumentList arglist = ((PyCallExpression) pe).getArgumentList();
            if (arglist == null)
                return;
            args = arglist.getArguments();
        }
        boolean madeInstance = false;
        if (callByClass) {
            if (args.length > 0) {
                final TypeEvalContext context = TypeEvalContext.userInitiated(cls.getProject(), cls.getContainingFile());
                final PyType firstArgType = context.getType(args[0]);
                if (firstArgType instanceof PyClassType && ((PyClassType) firstArgType).getPyClass().isSubclass(cls, context)) {
                    // class, first arg ok: instance method
                    // NOTE: might use a name other than 'self', according to code style.
                    builder.parameter("self");
                    madeInstance = true;
                }
            }
            if (!madeInstance) {
                // class, first arg absent or of different type: classmethod
                // NOTE: might use a name other than 'cls', according to code style.
                builder.parameter("cls");
                decoratorName = PyNames.CLASSMETHOD;
            }
        } else {
            // instance method
            // NOTE: might use a name other than 'self', according to code style.
            builder.parameter("self");
        }
        // ClassFoo.meth(foo_instance)
        boolean skipFirst = callByClass && madeInstance;
        for (PyExpression arg : args) {
            if (skipFirst) {
                skipFirst = false;
                continue;
            }
            if (arg instanceof PyKeywordArgument) {
                // foo(bar) -> def foo(self, bar_1)
                builder.parameter(((PyKeywordArgument) arg).getKeyword());
            } else if (arg instanceof PyReferenceExpression) {
                PyReferenceExpression refex = (PyReferenceExpression) arg;
                builder.parameter(refex.getReferencedName());
            } else {
                // use a boring name
                builder.parameter("param");
            }
        }
        PyFunction method = builder.buildFunction(project, LanguageLevel.getDefault());
        if (decoratorName != null) {
            PyElementGenerator generator = PyElementGenerator.getInstance(project);
            PyDecoratorList decoratorList = generator.createFromText(LanguageLevel.getDefault(), PyDecoratorList.class, "@" + decoratorName + "\ndef foo(): pass", new int[] { 0, 0 });
            // in the very beginning
            method.addBefore(decoratorList, method.getFirstChild());
        }
        method = (PyFunction) PyUtil.addElementToStatementList(method, clsStmtList, PyNames.INIT.equals(method.getName()));
        if (myReplaceUsage) {
            showTemplateBuilder(method);
        }
    } catch (IncorrectOperationException ignored) {
        // we failed. tell about this
        PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.method"), MessageType.ERROR);
    }
}
Also used : PyClassType(com.jetbrains.python.psi.types.PyClassType) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyFunctionBuilder(com.jetbrains.python.psi.impl.PyFunctionBuilder) PyType(com.jetbrains.python.psi.types.PyType) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement)

Aggregations

PyClassType (com.jetbrains.python.psi.types.PyClassType)8 PyType (com.jetbrains.python.psi.types.PyType)6 PsiElement (com.intellij.psi.PsiElement)4 TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)3 PyClassTypeImpl (com.jetbrains.python.psi.types.PyClassTypeImpl)2 Document (com.intellij.openapi.editor.Document)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 PsiFile (com.intellij.psi.PsiFile)1 IncorrectOperationException (com.intellij.util.IncorrectOperationException)1 PyStringFormatParser (com.jetbrains.python.inspections.PyStringFormatParser)1 PyFunctionBuilder (com.jetbrains.python.psi.impl.PyFunctionBuilder)1 RatedResolveResult (com.jetbrains.python.psi.resolve.RatedResolveResult)1 PyClassLikeType (com.jetbrains.python.psi.types.PyClassLikeType)1 PyModuleType (com.jetbrains.python.psi.types.PyModuleType)1 ArrayList (java.util.ArrayList)1 NotNull (org.jetbrains.annotations.NotNull)1 Nullable (org.jetbrains.annotations.Nullable)1