Search in sources :

Example 11 with QualifiedName

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

the class PyMoveSymbolProcessor method insertQualifiedImportAndReplaceReference.

/**
   * <pre>{@code
   *   print(foo.bar)
   * }</pre>
   * is transformed to
   * <pre>{@code
   *   import new
   *   print(new.bar)
   * }</pre>
   */
private static void insertQualifiedImportAndReplaceReference(@NotNull PsiNamedElement targetElement, @NotNull PyQualifiedExpression expression) {
    final PyElementGenerator generator = PyElementGenerator.getInstance(expression.getProject());
    final PsiFile srcFile = targetElement.getContainingFile();
    final LanguageLevel languageLevel = LanguageLevel.forElement(expression);
    if (srcFile != expression.getContainingFile()) {
        final QualifiedName qualifier = QualifiedNameFinder.findCanonicalImportPath(srcFile, expression);
        PyClassRefactoringUtil.insertImport(expression, srcFile, null, false);
        final String newQualifiedReference = qualifier + "." + expression.getReferencedName();
        expression.replace(generator.createExpressionFromText(languageLevel, newQualifiedReference));
    } else {
        expression.replace(generator.createExpressionFromText(languageLevel, expression.getReferencedName()));
    }
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

Example 12 with QualifiedName

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

the class PyMoveFileHandler method resolveRelativeImportFromModuleLocation.

/**
   * @param referenceExpr is null if we resolve import of type "from .. import bar", and "foo" for import of type "from foo import bar"
   */
@Nullable
private static PsiFileSystemItem resolveRelativeImportFromModuleLocation(@NotNull PsiManager manager, @NotNull String moduleLocation, @Nullable PyReferenceExpression referenceExpr, int relativeLevel) {
    String relativeImportBasePath = VirtualFileManager.extractPath(moduleLocation);
    for (int level = 0; level < relativeLevel; level++) {
        relativeImportBasePath = PathUtil.getParentPath(relativeImportBasePath);
    }
    if (!relativeImportBasePath.isEmpty()) {
        final String protocol = VirtualFileManager.extractProtocol(moduleLocation);
        assert protocol != null : "Original location: " + moduleLocation;
        final String relativeImportBaseUrl = VirtualFileManager.constructUrl(protocol, relativeImportBasePath);
        final VirtualFile relativeImportBaseDir = VirtualFileManager.getInstance().findFileByUrl(relativeImportBaseUrl);
        VirtualFile sourceFile = relativeImportBaseDir;
        if (relativeImportBaseDir != null && relativeImportBaseDir.isDirectory() && referenceExpr != null) {
            final QualifiedName qualifiedName = referenceExpr.asQualifiedName();
            if (qualifiedName == null) {
                return null;
            }
            final String relativePath = qualifiedName.join("/");
            sourceFile = relativeImportBaseDir.findFileByRelativePath(relativePath);
            if (sourceFile == null) {
                sourceFile = relativeImportBaseDir.findFileByRelativePath(relativePath + PyNames.DOT_PY);
            }
        }
        if (sourceFile != null) {
            final PsiFileSystemItem sourceElement;
            if (sourceFile.isDirectory()) {
                sourceElement = manager.findDirectory(sourceFile);
            } else {
                sourceElement = manager.findFile(sourceFile);
            }
            return sourceElement;
        }
    }
    return null;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) QualifiedName(com.intellij.psi.util.QualifiedName) Nullable(org.jetbrains.annotations.Nullable)

Example 13 with QualifiedName

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

the class PyMoveFileHandler method retargetUsages.

@Override
public void retargetUsages(List<UsageInfo> usages, Map<PsiElement, PsiElement> oldToNewMap) {
    final Set<PsiFile> updatedFiles = new HashSet<>();
    for (UsageInfo usage : usages) {
        final PsiElement usageElement = usage.getElement();
        if (usageElement != null) {
            final PsiNamedElement movedElement = usageElement.getCopyableUserData(REFERENCED_ELEMENT);
            usageElement.putCopyableUserData(REFERENCED_ELEMENT, null);
            if (movedElement != null) {
                final PsiFile usageFile = usageElement.getContainingFile();
                final PyImportStatementBase importStmt = PsiTreeUtil.getParentOfType(usageElement, PyImportStatementBase.class);
                // TODO: Retarget qualified expressions in docstrings
                if (importStmt != null) {
                    if (usageFile.getUserData(ORIGINAL_FILE_LOCATION) != null) {
                        // Leave relative imports as they are after #updateRelativeImportsInModule
                        final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(usageFile.getProject(), usageFile);
                        final PyResolveContext resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(typeEvalContext);
                        if (ContainerUtil.getFirstItem(PyUtil.multiResolveTopPriority(usageElement, resolveContext)) == movedElement) {
                            continue;
                        }
                    }
                    updatedFiles.add(usageFile);
                    final boolean usageInsideImportElement = PsiTreeUtil.getParentOfType(usageElement, PyImportElement.class) != null;
                    if (usageInsideImportElement) {
                        // or simple unqualified import of the module (import module).
                        if (PyClassRefactoringUtil.updateUnqualifiedImportOfElement(importStmt, movedElement)) {
                            continue;
                        }
                    }
                    final QualifiedName newElementName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
                    if (importStmt instanceof PyFromImportStatement) {
                        if (!usageInsideImportElement) {
                            replaceRelativeImportSourceWithQualifiedExpression((PyFromImportStatement) importStmt, newElementName);
                        }
                    } else {
                        replaceWithQualifiedExpression(usageElement, newElementName);
                    }
                } else if (usageElement instanceof PyReferenceExpression) {
                    updatedFiles.add(usageFile);
                    if (((PyReferenceExpression) usageElement).isQualified()) {
                        final QualifiedName newQualifiedName = QualifiedNameFinder.findCanonicalImportPath(movedElement, usageElement);
                        replaceWithQualifiedExpression(usageElement, newQualifiedName);
                    } else {
                        final QualifiedName newName = QualifiedName.fromComponents(PyClassRefactoringUtil.getOriginalName(movedElement));
                        replaceWithQualifiedExpression(usageElement, newName);
                    }
                }
            }
        }
    }
    if (!updatedFiles.isEmpty()) {
        final PyImportOptimizer optimizer = new PyImportOptimizer();
        for (PsiFile file : updatedFiles) {
            final boolean injectedFragment = InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file);
            if (!injectedFragment) {
                optimizer.processFile(file).run();
            }
        }
    }
}
Also used : PyResolveContext(com.jetbrains.python.psi.resolve.PyResolveContext) QualifiedName(com.intellij.psi.util.QualifiedName) TypeEvalContext(com.jetbrains.python.psi.types.TypeEvalContext) PyImportOptimizer(com.jetbrains.python.codeInsight.imports.PyImportOptimizer) UsageInfo(com.intellij.usageView.UsageInfo)

Example 14 with QualifiedName

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

the class PyKnownDecoratorUtil method asKnownDecorator.

@Nullable
public static KnownDecorator asKnownDecorator(@NotNull PyDecorator decorator, @NotNull TypeEvalContext context) {
    final QualifiedName qualifiedName = decorator.getQualifiedName();
    if (qualifiedName == null) {
        return null;
    }
    if (context.maySwitchToAST(decorator)) {
        PyQualifiedNameOwner resolved = as(resolveDecorator(decorator), PyQualifiedNameOwner.class);
        if (resolved instanceof PyFunction && PyNames.INIT.equals(resolved.getName())) {
            resolved = ((PyFunction) resolved).getContainingClass();
        }
        if (resolved != null && resolved.getQualifiedName() != null) {
            final QualifiedName resolvedName = QualifiedName.fromDottedString(resolved.getQualifiedName());
            final KnownDecorator knownDecorator = ourByShortName.get(resolvedName.getLastComponent());
            if (knownDecorator != null && resolvedName.equals(knownDecorator.getQualifiedName())) {
                return knownDecorator;
            }
        }
    } else {
        return ourByShortName.get(qualifiedName.getLastComponent());
    }
    return null;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName) KnownDecorator(com.jetbrains.python.psi.PyKnownDecoratorUtil.KnownDecorator) Nullable(org.jetbrains.annotations.Nullable)

Example 15 with QualifiedName

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

the class SetupTaskIntrospector method usesSetuptools.

public static boolean usesSetuptools(@NotNull PyFile file) {
    final List<PyFromImportStatement> imports = file.getFromImports();
    for (PyFromImportStatement anImport : imports) {
        final QualifiedName qName = anImport.getImportSourceQName();
        if (qName != null && qName.matches("setuptools")) {
            return true;
        }
    }
    final List<PyImportElement> importElements = file.getImportTargets();
    for (PyImportElement element : importElements) {
        final QualifiedName qName = element.getImportedQName();
        if (qName != null && qName.matches("setuptools")) {
            return true;
        }
    }
    return false;
}
Also used : QualifiedName(com.intellij.psi.util.QualifiedName)

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