Search in sources :

Example 51 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class AddImportHelper method addOrUpdateFromImportStatement.

/**
   * Adds new {@link PyFromImportStatement} in file or append {@link PyImportElement} to
   * existing from import statement.
   *
   * @param file     module where import will be added
   * @param from     import source (reference after {@code from} keyword)
   * @param name     imported name (identifier after {@code import} keyword)
   * @param asName   optional alias (identifier after {@code as} keyword)
   * @param priority optional import priority used to sort imports
   * @param anchor   place where the imported name was used. It will be used to determine proper block where new import should be inserted,
   *                 e.g. inside conditional block or try/except statement. Also if anchor is another import statement, new import statement
   *                 will be inserted right after it.
   * @return whether import was actually added
   * @see #addFromImportStatement
   */
public static boolean addOrUpdateFromImportStatement(@NotNull PsiFile file, @NotNull String from, @NotNull String name, @Nullable String asName, @Nullable ImportPriority priority, @Nullable PsiElement anchor) {
    final List<PyFromImportStatement> existingImports = ((PyFile) file).getFromImports();
    for (PyFromImportStatement existingImport : existingImports) {
        if (existingImport.isStarImport()) {
            continue;
        }
        final QualifiedName qName = existingImport.getImportSourceQName();
        if (qName != null && qName.toString().equals(from) && existingImport.getRelativeLevel() == 0) {
            for (PyImportElement el : existingImport.getImportElements()) {
                final QualifiedName importedQName = el.getImportedQName();
                if (importedQName != null && StringUtil.equals(name, importedQName.toString()) && StringUtil.equals(asName, el.getAsName())) {
                    return false;
                }
            }
            final PyElementGenerator generator = PyElementGenerator.getInstance(file.getProject());
            final PyImportElement importElement = generator.createImportElement(LanguageLevel.forElement(file), name, asName);
            existingImport.add(importElement);
            // May need to add parentheses, trailing comma, etc.
            CodeStyleManager.getInstance(file.getProject()).reformat(existingImport);
            return true;
        }
    }
    addFromImportStatement(file, from, name, asName, priority, anchor);
    return true;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

Example 52 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class AddImportHelper method addImport.

/**
   * Adds either {@link PyFromImportStatement} or {@link PyImportStatement}
   * to specified target depending on user preferences and whether it's possible to import element via "from" form of import
   * (e.g. consider top level module).
   *
   * @param target  element import is pointing to
   * @param file    file where import will be inserted
   * @param element used to determine where to insert import
   * @see PyCodeInsightSettings#PREFER_FROM_IMPORT
   * @see #addImportStatement
   * @see #addOrUpdateFromImportStatement
   */
public static void addImport(final PsiNamedElement target, final PsiFile file, final PyElement element) {
    final boolean useQualified = !PyCodeInsightSettings.getInstance().PREFER_FROM_IMPORT;
    final PsiFileSystemItem toImport = target instanceof PsiFileSystemItem ? ((PsiFileSystemItem) target).getParent() : target.getContainingFile();
    if (toImport == null)
        return;
    final ImportPriority priority = getImportPriority(file, toImport);
    final QualifiedName qName = QualifiedNameFinder.findCanonicalImportPath(target, element);
    if (qName == null)
        return;
    String path = qName.toString();
    if (target instanceof PsiFileSystemItem && qName.getComponentCount() == 1) {
        addImportStatement(file, path, null, priority, element);
    } else {
        final QualifiedName toImportQName = QualifiedNameFinder.findCanonicalImportPath(toImport, element);
        if (toImportQName == null)
            return;
        if (useQualified) {
            addImportStatement(file, path, null, priority, element);
            final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(file.getProject());
            final String targetName = PyUtil.getElementNameWithoutExtension(target);
            element.replace(elementGenerator.createExpressionFromText(LanguageLevel.forElement(target), toImportQName + "." + targetName));
        } else {
            final String name = target.getName();
            if (name != null)
                addOrUpdateFromImportStatement(file, toImportQName.toString(), name, null, priority, element);
        }
    }
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

Example 53 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyFromImportStatementImpl method getFullyQualifiedObjectNames.

@NotNull
@Override
public List<String> getFullyQualifiedObjectNames() {
    final QualifiedName source = getImportSourceQName();
    final String prefix = (source != null) ? (source.join(".") + '.') : "";
    final List<String> unqualifiedNames = PyImportStatementImpl.getImportElementNames(getImportElements());
    final List<String> result = new ArrayList<>(unqualifiedNames.size());
    for (final String unqualifiedName : unqualifiedNames) {
        result.add(prefix + unqualifiedName);
    }
    return result;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName) ArrayList(java.util.ArrayList) NotNull(org.jetbrains.annotations.NotNull)

Example 54 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyReferenceExpressionImpl method getGenericTypeFromTarget.

@Nullable
private static PyType getGenericTypeFromTarget(@NotNull PsiElement target, @NotNull TypeEvalContext context, @NotNull PyReferenceExpression anchor) {
    if (!(target instanceof PyTargetExpression)) {
        // PyTargetExpression will ask about its type itself
        final PyType pyType = getReferenceTypeFromProviders(target, context, anchor);
        if (pyType != null) {
            return pyType;
        }
    }
    if (target instanceof PyTargetExpression) {
        final String name = ((PyTargetExpression) target).getName();
        if (PyNames.NONE.equals(name)) {
            return PyNoneType.INSTANCE;
        }
        if (PyNames.TRUE.equals(name) || PyNames.FALSE.equals(name)) {
            return PyBuiltinCache.getInstance(target).getBoolType();
        }
    }
    if (target instanceof PyFile) {
        return new PyModuleType((PyFile) target);
    }
    if ((target instanceof PyTargetExpression || target instanceof PyNamedParameter) && context.allowDataFlow(anchor)) {
        final ScopeOwner scopeOwner = ScopeUtil.getScopeOwner(anchor);
        if (scopeOwner != null && scopeOwner == ScopeUtil.getScopeOwner(target)) {
            final String name = ((PyElement) target).getName();
            if (name != null) {
                final PyType type = getTypeByControlFlow(name, context, anchor, scopeOwner);
                if (type != null) {
                    return type;
                }
            }
        }
    }
    if (target instanceof PyFunction) {
        final PyDecoratorList decoratorList = ((PyFunction) target).getDecoratorList();
        if (decoratorList != null) {
            final PyDecorator propertyDecorator = decoratorList.findDecorator(PyNames.PROPERTY);
            if (propertyDecorator != null) {
                return PyBuiltinCache.getInstance(target).getObjectType(PyNames.PROPERTY);
            }
            for (PyDecorator decorator : decoratorList.getDecorators()) {
                final QualifiedName qName = decorator.getQualifiedName();
                if (qName != null && (qName.endsWith(PyNames.SETTER) || qName.endsWith(PyNames.DELETER) || qName.endsWith(PyNames.GETTER))) {
                    return PyBuiltinCache.getInstance(target).getObjectType(PyNames.PROPERTY);
                }
            }
        }
    }
    if (target instanceof PyTypedElement) {
        return context.getType((PyTypedElement) target);
    }
    if (target instanceof PsiDirectory) {
        final PsiDirectory dir = (PsiDirectory) target;
        final PsiFile file = dir.findFile(PyNames.INIT_DOT_PY);
        if (file != null) {
            return getTypeFromTarget(file, context, anchor);
        }
        if (PyUtil.isPackage(dir, anchor)) {
            final PsiFile containingFile = anchor.getContainingFile();
            if (containingFile instanceof PyFile) {
                final QualifiedName qualifiedName = QualifiedNameFinder.findShortestImportableQName(dir);
                if (qualifiedName != null) {
                    final PyImportedModule module = new PyImportedModule(null, (PyFile) containingFile, qualifiedName);
                    return new PyImportedModuleType(module);
                }
            }
        }
    }
    return null;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName) ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) Nullable(org.jetbrains.annotations.Nullable)

Example 55 with QualifiedName

use of com.intellij.psi.util.QualifiedName in project intellij-community by JetBrains.

the class PyReferenceExpressionImpl method getQualifiedReferenceTypeByControlFlow.

@Nullable
private PyType getQualifiedReferenceTypeByControlFlow(@NotNull TypeEvalContext context) {
    PyExpression qualifier = getQualifier();
    if (context.allowDataFlow(this) && qualifier != null) {
        PyExpression next = qualifier;
        while (next != null) {
            qualifier = next;
            next = qualifier instanceof PyQualifiedExpression ? ((PyQualifiedExpression) qualifier).getQualifier() : null;
        }
        final ScopeOwner scopeOwner = ScopeUtil.getScopeOwner(this);
        final QualifiedName qname = asQualifiedName();
        if (qname != null && scopeOwner != null) {
            return getTypeByControlFlow(qname.toString(), context, qualifier, scopeOwner);
        }
    }
    return null;
}
Also used : ScopeOwner(com.jetbrains.python.codeInsight.controlflow.ScopeOwner) QualifiedName(com.intellij.psi.util.QualifiedName) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

QualifiedName (com.intellij.psi.util.QualifiedName)63 Nullable (org.jetbrains.annotations.Nullable)22 NotNull (org.jetbrains.annotations.NotNull)17 VirtualFile (com.intellij.openapi.vfs.VirtualFile)9 Project (com.intellij.openapi.project.Project)8 ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)7 PsiElement (com.intellij.psi.PsiElement)6 ArrayList (java.util.ArrayList)5 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)4 Sdk (com.intellij.openapi.projectRoots.Sdk)3 PsiFile (com.intellij.psi.PsiFile)3 PsiDirectory (com.intellij.psi.PsiDirectory)2 PsiFileSystemItem (com.intellij.psi.PsiFileSystemItem)2 StringRef (com.intellij.util.io.StringRef)2 PyClass (com.jetbrains.python.psi.PyClass)2 PyFunction (com.jetbrains.python.psi.PyFunction)2 PyClassTypeImpl (com.jetbrains.python.psi.types.PyClassTypeImpl)2 TypeEvalContext (com.jetbrains.python.psi.types.TypeEvalContext)2 Instruction (com.intellij.codeInsight.controlflow.Instruction)1 InjectedLanguageManager (com.intellij.lang.injection.InjectedLanguageManager)1