Search in sources :

Example 46 with ScopeOwner

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

the class PyReferenceImpl method getVariants.

@Override
@NotNull
public Object[] getVariants() {
    final List<LookupElement> ret = Lists.newArrayList();
    // Use real context here to enable correct completion and resolve in case of PyExpressionCodeFragment!!!
    final PyQualifiedExpression originalElement = CompletionUtil.getOriginalElement(myElement);
    final PyQualifiedExpression element = originalElement != null ? originalElement : myElement;
    final PsiElement realContext = PyPsiUtils.getRealContext(element);
    // include our own names
    final int underscores = PyUtil.getInitialUnderscores(element.getName());
    final CompletionVariantsProcessor processor = new CompletionVariantsProcessor(element);
    final ScopeOwner owner = realContext instanceof ScopeOwner ? (ScopeOwner) realContext : ScopeUtil.getScopeOwner(realContext);
    if (owner != null) {
        PyResolveUtil.scopeCrawlUp(processor, owner, null, null);
    }
    // This method is probably called for completion, so use appropriate context here
    // in a call, include function's arg names
    KeywordArgumentCompletionUtil.collectFunctionArgNames(element, ret, TypeEvalContext.codeCompletion(element.getProject(), element.getContainingFile()));
    // include builtin names
    final PyFile builtinsFile = PyBuiltinCache.getInstance(element).getBuiltinsFile();
    if (builtinsFile != null) {
        PyResolveUtil.scopeCrawlUp(processor, builtinsFile, null, null);
    }
    if (underscores >= 2) {
        // if we're a normal module, add module's attrs
        if (realContext.getContainingFile() instanceof PyFile) {
            for (String name : PyModuleType.getPossibleInstanceMembers()) {
                ret.add(LookupElementBuilder.create(name).withIcon(PlatformIcons.FIELD_ICON));
            }
        }
        // if we're inside method, add implicit __class__
        if (LanguageLevel.forElement(myElement).isAtLeast(LanguageLevel.PYTHON30)) {
            Optional.ofNullable(PsiTreeUtil.getParentOfType(myElement, PyFunction.class)).map(PyFunction::getContainingClass).ifPresent(pyClass -> ret.add(LookupElementBuilder.create(PyNames.__CLASS__)));
        }
    }
    ret.addAll(getOriginalElements(processor));
    return ret.toArray();
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) LookupElement(com.intellij.codeInsight.lookup.LookupElement) NotNull(org.jetbrains.annotations.NotNull)

Example 47 with ScopeOwner

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

the class CompletionVariantsProcessor method setupItem.

private LookupElementBuilder setupItem(LookupElementBuilder item) {
    final PsiElement element = item.getPsiElement();
    if (!myPlainNamesOnly) {
        if (!mySuppressParentheses && element instanceof PyFunction && ((PyFunction) element).getProperty() == null && !PyUtil.hasCustomDecorators((PyFunction) element) && !isSingleArgDecoratorCall(myContext, (PyFunction) element)) {
            final Project project = element.getProject();
            item = item.withInsertHandler(PyFunctionInsertHandler.INSTANCE);
            final TypeEvalContext context = TypeEvalContext.codeCompletion(project, myContext != null ? myContext.getContainingFile() : null);
            final List<PyParameter> parameters = PyUtil.getParameters((PyFunction) element, context);
            final String params = StringUtil.join(parameters, pyParameter -> pyParameter.getName(), ", ");
            item = item.withTailText("(" + params + ")");
        } else if (element instanceof PyClass) {
            item = item.withInsertHandler(PyClassInsertHandler.INSTANCE);
        }
    }
    String source = null;
    if (element != null) {
        PyClass cls = null;
        if (element instanceof PyFunction) {
            cls = ((PyFunction) element).getContainingClass();
        } else if (element instanceof PyTargetExpression) {
            final PyTargetExpression expr = (PyTargetExpression) element;
            if (expr.isQualified() || ScopeUtil.getScopeOwner(expr) instanceof PyClass) {
                cls = expr.getContainingClass();
            }
        } else if (element instanceof PyClass) {
            final ScopeOwner owner = ScopeUtil.getScopeOwner(element);
            if (owner instanceof PyClass) {
                cls = (PyClass) owner;
            }
        }
        if (cls != null) {
            source = cls.getName();
        } else if (myContext == null || !PyUtil.inSameFile(myContext, element)) {
            QualifiedName path = QualifiedNameFinder.findCanonicalImportPath(element, null);
            if (path != null) {
                if (element instanceof PyFile) {
                    path = path.removeLastComponent();
                }
                source = path.toString();
            }
        }
    }
    if (source != null) {
        item = item.withTypeText(source);
    }
    return item;
}
Also used : Project(com.intellij.openapi.project.Project) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) QualifiedName(com.intellij.psi.util.QualifiedName) PsiElement(com.intellij.psi.PsiElement) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext)

Example 48 with ScopeOwner

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

the class PyResolveProcessor method tryAddResult.

private boolean tryAddResult(@Nullable PsiElement element, @Nullable PyImportedNameDefiner definer) {
    final ScopeOwner owner = ScopeUtil.getScopeOwner(definer != null ? definer : element);
    if (myOwner == null) {
        myOwner = owner;
    }
    final boolean sameScope = owner == myOwner;
    if (sameScope) {
        // XXX: In 'from foo import foo' inside __init__.py the preferred result is explicitly imported 'foo'
        if (definer instanceof PyFromImportStatement) {
            myImplicitlyImportedResults.put(element, definer);
        } else {
            myResults.put(element, definer);
        }
    }
    return sameScope;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) PyFromImportStatement(com.jetbrains.python.psi.PyFromImportStatement)

Example 49 with ScopeOwner

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

the class PyiUtil method findSimilarElement.

@Nullable
private static PsiElement findSimilarElement(@NotNull PyElement element, @NotNull PyFile file) {
    if (element instanceof PyFile) {
        return file;
    }
    final ScopeOwner owner = ScopeUtil.getScopeOwner(element);
    final String name = element.getName();
    if (owner != null && name != null) {
        assert owner != element;
        final PsiElement originalOwner = findSimilarElement(owner, file);
        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();
                final List<? extends RatedResolveResult> resolveResults = instanceType.resolveMember(name, null, AccessDirection.READ, PyResolveContext.noImplicits(), 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 50 with ScopeOwner

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

the class PyIterableVariableMacro method getVisibleNamedElements.

@NotNull
private static List<PsiNamedElement> getVisibleNamedElements(@NotNull PsiElement anchor) {
    final List<PsiNamedElement> results = new ArrayList<>();
    for (ScopeOwner owner = ScopeUtil.getScopeOwner(anchor); owner != null; owner = ScopeUtil.getScopeOwner(owner)) {
        final Scope scope = ControlFlowCache.getScope(owner);
        results.addAll(scope.getNamedElements());
        StreamEx.of(scope.getImportedNameDefiners()).filter(definer -> !PyImplicitImportNameDefiner.class.isInstance(definer)).flatMap(definer -> StreamSupport.stream(definer.iterateNames().spliterator(), false)).select(PsiNamedElement.class).forEach(results::add);
    }
    return results;
}
Also used : TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyNames(com.jetbrains.python.PyNames) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) PyType(com.jetbrains.python.psi.types.PyType) com.intellij.codeInsight.template(com.intellij.codeInsight.template) ScopeUtil(com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil) PyImplicitImportNameDefiner(com.jetbrains.python.psi.PyImplicitImportNameDefiner) ArrayList(java.util.ArrayList) Nullable(org.jetbrains.annotations.Nullable) PyTypedElement(com.jetbrains.python.psi.PyTypedElement) List(java.util.List) Scope(com.jetbrains.python.codeInsight.dataflow.scope.Scope) PyABCUtil(com.jetbrains.python.psi.types.PyABCUtil) StreamEx(one.util.streamex.StreamEx) PsiElement(com.intellij.psi.PsiElement) ControlFlowCache(com.jetbrains.python.codeInsight.controlflow.ControlFlowCache) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) PsiNamedElement(com.intellij.psi.PsiNamedElement) StreamSupport(java.util.stream.StreamSupport) NotNull(org.jetbrains.annotations.NotNull) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) Scope(com.jetbrains.python.codeInsight.dataflow.scope.Scope) PsiNamedElement(com.intellij.psi.PsiNamedElement) ArrayList(java.util.ArrayList) PyImplicitImportNameDefiner(com.jetbrains.python.psi.PyImplicitImportNameDefiner) NotNull(org.jetbrains.annotations.NotNull)

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