Search in sources :

Example 1 with ScopeOwner

use of com.jetbrains.python.codeInsight.controlflow.ScopeOwner in project intellij-community by JetBrains.

the class PyUserSkeletonsUtil method getUserSkeleton.

@Nullable
private static PsiElement getUserSkeleton(@NotNull PyElement element, @NotNull PyFile skeletonFile, @Nullable TypeEvalContext context) {
    if (element instanceof PyFile) {
        return skeletonFile;
    }
    final ScopeOwner owner = ScopeUtil.getScopeOwner(element);
    final String name = element.getName();
    if (owner != null && name != null) {
        assert owner != element;
        final PsiElement originalOwner = getUserSkeleton(owner, skeletonFile, context);
        if (originalOwner instanceof PyClass) {
            final PyClass classOwner = (PyClass) originalOwner;
            final PyType type = TypeEvalContext.codeInsightFallback(classOwner.getProject()).getType(classOwner);
            if (type instanceof PyClassLikeType) {
                final PyClassLikeType classType = (PyClassLikeType) type;
                final PyClassLikeType instanceType = classType.toInstance();
                PyResolveContext resolveContext = PyResolveContext.noImplicits();
                if (context != null) {
                    resolveContext = resolveContext.withTypeEvalContext(context);
                }
                final List<? extends RatedResolveResult> resolveResults = instanceType.resolveMember(name, null, AccessDirection.READ, resolveContext, false);
                if (resolveResults != null && !resolveResults.isEmpty()) {
                    return resolveResults.get(0).getElement();
                }
            }
        } else if (originalOwner instanceof PyFile) {
            return ((PyFile) originalOwner).getElementNamed(name);
        }
    }
    return null;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) PyType(com.jetbrains.python.psi.types.PyType) PyClassLikeType(com.jetbrains.python.psi.types.PyClassLikeType) PsiElement(com.intellij.psi.PsiElement) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with ScopeOwner

use of com.jetbrains.python.codeInsight.controlflow.ScopeOwner in project intellij-community by JetBrains.

the class PyCodeFragmentTest method check.

private void check(final PyFile myFile, final int beginMarker, final int endMarker, final String result) {
    final PsiElement startElement = myFile.findElementAt(beginMarker);
    final PsiElement endElement = myFile.findElementAt(endMarker - BEGIN_MARKER.length());
    PsiElement context = PsiTreeUtil.findCommonParent(startElement, endElement);
    if (!(context instanceof ScopeOwner)) {
        context = PsiTreeUtil.getParentOfType(context, ScopeOwner.class);
    }
    final StringBuffer buffer = new StringBuffer();
    try {
        final CodeFragment fragment = PyCodeFragmentUtil.createCodeFragment((ScopeOwner) context, startElement, endElement);
        if (fragment.isReturnInstructionInside()) {
            buffer.append("Return instruction inside found").append("\n");
        }
        buffer.append("In:\n");
        for (String inputVariable : new TreeSet<>(fragment.getInputVariables())) {
            buffer.append(inputVariable).append('\n');
        }
        buffer.append("Out:\n");
        for (String outputVariable : new TreeSet<>(fragment.getOutputVariables())) {
            buffer.append(outputVariable).append('\n');
        }
    } catch (CannotCreateCodeFragmentException e) {
        assertEquals(result.trim(), e.getMessage());
        return;
    }
    assertEquals(result.trim(), buffer.toString().trim());
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) CannotCreateCodeFragmentException(com.intellij.codeInsight.codeFragment.CannotCreateCodeFragmentException) TreeSet(java.util.TreeSet) CodeFragment(com.intellij.codeInsight.codeFragment.CodeFragment) PsiElement(com.intellij.psi.PsiElement)

Example 3 with ScopeOwner

use of com.jetbrains.python.codeInsight.controlflow.ScopeOwner in project intellij-community by JetBrains.

the class PythonImportUtils method proposeImportFix.

@Nullable
public static AutoImportQuickFix proposeImportFix(final PyElement node, PsiReference reference) {
    final String text = reference.getElement().getText();
    // text of the part we're working with
    final String refText = reference.getRangeInElement().substring(text);
    // don't propose meaningless auto imports if no interpreter is configured
    final Module module = ModuleUtilCore.findModuleForPsiElement(node);
    if (module != null && PythonSdkType.findPythonSdk(module) == null) {
        return null;
    }
    // don't show auto-import fix if we're trying to reference a variable which is defined below in the same scope
    ScopeOwner scopeOwner = PsiTreeUtil.getParentOfType(node, ScopeOwner.class);
    if (scopeOwner != null && ControlFlowCache.getScope(scopeOwner).containsDeclaration(refText)) {
        return null;
    }
    AutoImportQuickFix fix = addCandidates(node, reference, refText, null);
    if (fix != null)
        return fix;
    final String packageName = PyPackageAliasesProvider.commonImportAliases.get(refText);
    if (packageName != null) {
        fix = addCandidates(node, reference, packageName, refText);
        if (fix != null)
            return fix;
    }
    return null;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) Module(com.intellij.openapi.module.Module) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with ScopeOwner

use of com.jetbrains.python.codeInsight.controlflow.ScopeOwner in project intellij-community by JetBrains.

the class DeclarationConflictChecker method findDefinitions.

/**
   * For each reference in the collection, finds a definition of name visible from the point of the reference. Returns a list of
   * such definitions.
   * @param name what to look for.
   * @param references references to check.
   * @param ignored if an element defining the name is also listed here, ignore it.
   * @return a list of pairs (referring element, element that defines name).
   */
@NotNull
public static List<Pair<PsiElement, PsiElement>> findDefinitions(@NotNull String name, @NotNull Collection<PsiReference> references, @NotNull Set<PsiElement> ignored) {
    final List<Pair<PsiElement, PsiElement>> conflicts = new ArrayList<>();
    for (PsiReference ref : references) {
        final PsiElement refElement = ref.getElement();
        final ScopeOwner owner = ScopeUtil.getScopeOwner(refElement);
        if (owner != null) {
            for (PsiElement element : PyResolveUtil.resolveLocally(owner, name)) {
                if (!ignored.contains(element)) {
                    conflicts.add(Pair.create(refElement, element));
                }
            }
        }
    }
    return conflicts;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) ArrayList(java.util.ArrayList) PsiReference(com.intellij.psi.PsiReference) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with ScopeOwner

use of com.jetbrains.python.codeInsight.controlflow.ScopeOwner in project intellij-community by JetBrains.

the class PyStdlibTypeProvider method getEnumType.

@Nullable
private static PyType getEnumType(@NotNull PsiElement referenceTarget, @NotNull TypeEvalContext context, @Nullable PsiElement anchor) {
    if (referenceTarget instanceof PyTargetExpression) {
        final PyTargetExpression target = (PyTargetExpression) referenceTarget;
        final ScopeOwner owner = ScopeUtil.getScopeOwner(target);
        if (owner instanceof PyClass) {
            final PyClass cls = (PyClass) owner;
            final List<PyClassLikeType> types = cls.getAncestorTypes(context);
            for (PyClassLikeType type : types) {
                if (type != null && "enum.Enum".equals(type.getClassQName())) {
                    final PyType classType = context.getType(cls);
                    if (classType instanceof PyClassType) {
                        return ((PyClassType) classType).toInstance();
                    }
                }
            }
        }
    }
    if (referenceTarget instanceof PyQualifiedNameOwner) {
        final PyQualifiedNameOwner qualifiedNameOwner = (PyQualifiedNameOwner) referenceTarget;
        final String name = qualifiedNameOwner.getQualifiedName();
        if ("enum.Enum.name".equals(name)) {
            return PyBuiltinCache.getInstance(referenceTarget).getStrType();
        } else if ("enum.Enum.value".equals(name) && anchor instanceof PyReferenceExpression && context.maySwitchToAST(anchor)) {
            final PyReferenceExpression anchorExpr = (PyReferenceExpression) anchor;
            final PyExpression qualifier = anchorExpr.getQualifier();
            if (qualifier instanceof PyReferenceExpression) {
                final PyReferenceExpression qualifierExpr = (PyReferenceExpression) qualifier;
                final PsiElement resolvedQualifier = qualifierExpr.getReference().resolve();
                if (resolvedQualifier instanceof PyTargetExpression) {
                    final PyTargetExpression qualifierTarget = (PyTargetExpression) resolvedQualifier;
                    // Requires switching to AST, we cannot use getType(qualifierTarget) here, because its type is overridden by this type provider
                    if (context.maySwitchToAST(qualifierTarget)) {
                        final PyExpression value = qualifierTarget.findAssignedValue();
                        if (value != null) {
                            return context.getType(value);
                        }
                    }
                }
            }
        } else if ("enum.EnumMeta.__members__".equals(name)) {
            return PyTypeParser.getTypeByName(referenceTarget, "dict[str, unknown]");
        }
    }
    return null;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) PsiElement(com.intellij.psi.PsiElement) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)51 PsiElement (com.intellij.psi.PsiElement)25 Nullable (org.jetbrains.annotations.Nullable)18 NotNull (org.jetbrains.annotations.NotNull)14 Pair (com.intellij.openapi.util.Pair)6 QualifiedName (com.intellij.psi.util.QualifiedName)6 ArrayList (java.util.ArrayList)6 Instruction (com.intellij.codeInsight.controlflow.Instruction)4 TextRange (com.intellij.openapi.util.TextRange)4 PsiFile (com.intellij.psi.PsiFile)4 Scope (com.jetbrains.python.codeInsight.dataflow.scope.Scope)4 List (java.util.List)4 LookupElement (com.intellij.codeInsight.lookup.LookupElement)3 Project (com.intellij.openapi.project.Project)3 Ref (com.intellij.openapi.util.Ref)3 PsiLanguageInjectionHost (com.intellij.psi.PsiLanguageInjectionHost)3 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)3 TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)3 CannotCreateCodeFragmentException (com.intellij.codeInsight.codeFragment.CannotCreateCodeFragmentException)2 ASTNode (com.intellij.lang.ASTNode)2