Java 类com.intellij.psi.util.QualifiedName 实例源码

项目:educational-plugin    文件:PyStudyImportResolver.java   
@Nullable
public PsiElement resolveImportReference(QualifiedName name, PyQualifiedNameResolveContext context, boolean withRoots) {
  if (StudyTaskManager.getInstance(context.getProject()).getCourse() == null) {
    return null;
  }
  final String nameString = name.toString();
  PsiFile containingFile = context.getFootholdFile();
  if (containingFile == null) return null;

  final PsiDirectory directory = containingFile.getContainingDirectory();
  if (directory == null) return null;
  final PsiFile file = directory.findFile(nameString + ".py");
  if (file != null) {
    return file;
  }

  return null;
}
项目:intellij-ce-playground    文件:PyStudyImportResolver.java   
@Nullable
public PsiElement resolveImportReference(QualifiedName name, QualifiedNameResolveContext context, boolean withRoots) {
  if (StudyTaskManager.getInstance(context.getProject()).getCourse() == null) {
    return null;
  }
  final String nameString = name.toString();
  PsiFile containingFile = context.getFootholdFile();
  if (containingFile == null) return null;

  final PsiDirectory directory = containingFile.getContainingDirectory();
  if (directory == null) return null;
  final PsiFile file = directory.findFile(nameString + ".py");
  if (file != null) {
    return file;
  }

  return null;
}
项目:intellij-ce-playground    文件:PyJavaImportResolver.java   
@Nullable
public PsiElement resolveImportReference(QualifiedName name, QualifiedNameResolveContext context, boolean withRoots) {
  String fqn = name.toString();
  final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(context.getProject());
  final PsiPackage aPackage = psiFacade.findPackage(fqn);
  if (aPackage != null) {
    return aPackage;
  }

  Module module = context.getModule();
  if (module != null) {
    final PsiClass aClass = psiFacade.findClass(fqn, module.getModuleWithDependenciesAndLibrariesScope(false));
    if (aClass != null) return aClass;
  }
  return null;
}
项目:intellij-ce-playground    文件:PyQtTypeProvider.java   
@Nullable
@Override
public PyType getCallableType(@NotNull PyCallable callable, @NotNull TypeEvalContext context) {
  if (callable instanceof PyFunction) {
    final String qualifiedName = callable.getQualifiedName();
    if (qualifiedName != null && qualifiedName.startsWith("PyQt")){
      final QualifiedName name = QualifiedName.fromDottedString(qualifiedName);
      final String qtVersion = name.getComponents().get(0);
      final String docstring = ((PyFunction)callable).getDocStringValue();
      if (docstring != null && docstring.contains("[signal]")) {
        final PyClass aClass = PyClassNameIndex.findClass(qtVersion + "." + ourQtBoundSignal, callable.getProject());
        if (aClass != null)
          return new PyClassTypeImpl(aClass, false);
      }
    }
  }
  return null;
}
项目:intellij    文件:AbstractPyImportResolverStrategy.java   
@Override
public final void addImportCandidates(
    PsiReference reference, String name, AutoImportQuickFix quickFix) {
  Project project = reference.getElement().getProject();
  PySourcesIndex index = getSourcesIndex(project);
  if (index == null) {
    return;
  }
  PsiManager psiManager = PsiManager.getInstance(project);
  for (QualifiedName candidate : index.shortNames.get(name)) {
    PsiElementProvider resolver = index.sourceMap.get(candidate);
    if (resolver == null) {
      continue;
    }
    PsiElement psi = resolver.get(psiManager);
    if (psi == null) {
      continue;
    }
    PsiFile file = psi.getContainingFile();
    if (file != null) {
      quickFix.addImport(psi, file, candidate.removeLastComponent());
    }
  }
}
项目:intellij-ce-playground    文件:PyClassElementType.java   
public PyClassStub createStub(@NotNull final PyClass psi, final StubElement parentStub) {
  final PyExpression[] exprs = psi.getSuperClassExpressions();
  List<QualifiedName> superClasses = new ArrayList<QualifiedName>();
  for (PyExpression expression : exprs) {
    if (expression instanceof PyKeywordArgument) {
      continue;
    }
    expression = PyClassImpl.unfoldClass(expression);
    superClasses.add(PyPsiUtils.asQualifiedName(expression));
  }
  final PyStringLiteralExpression docStringExpression = psi.getDocStringExpression();
  return new PyClassStubImpl(psi.getName(), parentStub,
                             superClasses.toArray(new QualifiedName[superClasses.size()]),
                             PyPsiUtils.asQualifiedName(psi.getMetaClassExpression()),
                             psi.getOwnSlots(),
                             PyPsiUtils.strValue(docStringExpression),
                             getStubElementType());
}
项目:intellij-ce-playground    文件:ImportCandidateHolder.java   
/**
 * Helper method that builds an import path, handling all these "import foo", "import foo as bar", "from bar import foo", etc.
 * Either importPath or importSource must be not null.
 *
 * @param name       what is ultimately imported.
 * @param importPath known path to import the name.
 * @param source     known ImportElement to import the name; its 'as' clause is used if present.
 * @return a properly qualified name.
 */
@NotNull
public static String getQualifiedName(@NotNull String name, @Nullable QualifiedName importPath, @Nullable PyImportElement source) {
  final StringBuilder sb = new StringBuilder();
  if (source != null) {
    final PsiElement parent = source.getParent();
    if (parent instanceof PyFromImportStatement) {
      sb.append(name);
    }
    else {
      sb.append(source.getVisibleName()).append(".").append(name);
    }
  }
  else {
    if (importPath != null && importPath.getComponentCount() > 0) {
      sb.append(importPath).append(".");
    }
    sb.append(name);
  }
  return sb.toString();
}
项目:intellij-ce-playground    文件:PyiUtil.java   
@Nullable
private static QualifiedName findImportableName(@NotNull PyFile file) {
  final VirtualFile moduleVirtualFile = file.getVirtualFile();
  if (moduleVirtualFile != null) {
    String moduleName = QualifiedNameFinder.findShortestImportableName(file, moduleVirtualFile);
    if (moduleName != null) {
      final QualifiedName qName = QualifiedName.fromDottedString(moduleName);
      for (PyCanonicalPathProvider provider : Extensions.getExtensions(PyCanonicalPathProvider.EP_NAME)) {
        final QualifiedName restored = provider.getCanonicalPath(qName, null);
        if (restored != null) {
          return restored;
        }
      }
      return qName;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:DocStringTypeReference.java   
@Nullable
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
  if (element.equals(resolve())) {
    return element;
  }
  if (myElement instanceof PyStringLiteralExpression && element instanceof PyClass) {
    final PyStringLiteralExpression e = (PyStringLiteralExpression)myElement;
    final PyClass cls = (PyClass)element;
    QualifiedName qname = QualifiedNameFinder.findCanonicalImportPath(cls, element);
    if (qname != null) {
      qname = qname.append(cls.getName());
      ElementManipulator<PyStringLiteralExpression> manipulator = ElementManipulators.getManipulator(e);
      myType = new PyClassTypeImpl(cls, false);
      return manipulator.handleContentChange(e, myFullRange, qname.toString());
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:PythonDocumentationProvider.java   
@Override
public void promptToConfigureDocumentation(@NotNull PsiElement element) {
  final Project project = element.getProject();
  final QualifiedName qName = QualifiedNameFinder.findCanonicalImportPath(element, element);
  if (qName != null && qName.getComponentCount() > 0) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        final int rc = Messages.showOkCancelDialog(project,
                                                   "No external documentation URL configured for module " + qName.getComponents().get(0) +
                                                   ".\nWould you like to configure it now?",
                                                   "Python External Documentation",
                                                   Messages.getQuestionIcon());
        if (rc == Messages.OK) {
          ShowSettingsUtilImpl.showSettingsDialog(project, PythonDocumentationConfigurable.ID, "");
        }
      }
    }, ModalityState.NON_MODAL);
  }
}
项目:intellij-ce-playground    文件:PyQualifiedReference.java   
private static Collection<PyExpression> collectAssignedAttributes(PyQualifiedExpression qualifier) {
  final Set<String> names = new HashSet<String>();
  final QualifiedName qualifierQName = qualifier.asQualifiedName();
  if (qualifierQName != null) {
    final List<PyExpression> results = new ArrayList<PyExpression>();
    for (ScopeOwner owner = ScopeUtil.getScopeOwner(qualifier); owner != null; owner = ScopeUtil.getScopeOwner(owner)) {
      final Scope scope = ControlFlowCache.getScope(owner);
      for (PyTargetExpression target : scope.getTargetExpressions()) {
        final QualifiedName targetQName = target.asQualifiedName();
        if (targetQName != null) {
          if (targetQName.getComponentCount() == qualifierQName.getComponentCount() + 1 && targetQName.matchesPrefix(qualifierQName)) {
            final String name = target.getName();
            if (!names.contains(name)) {
              names.add(name);
              results.add(target);
            }
          }
        }
      }
    }
    return results;
  }
  return Collections.emptyList();
}
项目:intellij-ce-playground    文件:PyPep8NamingInspection.java   
@Override
public void visitPyImportElement(PyImportElement node) {
  final String asName = node.getAsName();
  final QualifiedName importedQName = node.getImportedQName();
  if (importedQName == null) return;
  final String name = importedQName.getLastComponent();

  if (asName == null || name == null) return;
  if (UPPERCASE_REGEX.matcher(name).matches()) {
    if (!UPPERCASE_REGEX.matcher(asName).matches()) {
      registerAndAddRenameQuickFix(node.getAsNameElement(), "Constant variable imported as non constant");
    }
  }
  else if (LOWERCASE_REGEX.matcher(name).matches()) {
    if (!LOWERCASE_REGEX.matcher(asName).matches()) {
      registerAndAddRenameQuickFix(node.getAsNameElement(), "Lowercase variable imported as non lowercase");
    }
  }
  else if (LOWERCASE_REGEX.matcher(asName).matches()) {
    registerAndAddRenameQuickFix(node.getAsNameElement(), "CamelCase variable imported as lowercase");
  }
  else if (UPPERCASE_REGEX.matcher(asName).matches()) {
    registerAndAddRenameQuickFix(node.getAsNameElement(), "CamelCase variable imported as constant");
  }
}
项目:intellij    文件:BlazePyOutsideModuleImportResolver.java   
@Nullable
private static PsiElement resolveModuleAt(
    @Nullable PsiDirectory directory,
    QualifiedName qualifiedName,
    PyQualifiedNameResolveContext context) {
  if (directory == null || !directory.isValid()) {
    return null;
  }
  PsiElement seeker = directory;
  for (String name : qualifiedName.getComponents()) {
    if (name == null) {
      return null;
    }
    seeker =
        ResolveImportUtil.resolveChild(
            seeker, name, context.getFootholdFile(), false, true, false);
  }
  return seeker;
}
项目:intellij-ce-playground    文件:QualifiedNameResolverImpl.java   
public boolean visitRoot(final VirtualFile root, @Nullable Module module, @Nullable Sdk sdk, boolean isModuleSource) {
  if (!root.isValid()) {
    return true;
  }
  if (root.equals(PyUserSkeletonsUtil.getUserSkeletonsDirectory())) {
    return true;
  }
  PsiElement resolveResult = resolveInRoot(root);
  if (resolveResult != null) {
    addRoot(resolveResult, isModuleSource);
  }

  if (isAcceptRootAsTopLevelPackage() && myQualifiedName.matchesPrefix(QualifiedName.fromDottedString(root.getName()))) {
    resolveResult = resolveInRoot(root.getParent());
    if (resolveResult != null) {
      addRoot(resolveResult, isModuleSource);
    }
  }

  return true;
}
项目:intellij-ce-playground    文件:QualifiedNameResolverImpl.java   
/**
 * Resolve relative imports from sdk root to the skeleton dir
 */
private void addRelativeImportResultsFromSkeletons(@NotNull final PsiFile foothold) {
  final boolean inSource = FileIndexFacade.getInstance(foothold.getProject()).isInContent(foothold.getVirtualFile());
  if (inSource) return;
  PsiDirectory containingDirectory = foothold.getContainingDirectory();
  if (myRelativeLevel > 0) {
    containingDirectory = ResolveImportUtil.stepBackFrom(foothold, myRelativeLevel);
  }
  if (containingDirectory != null) {
    final QualifiedName containingQName = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null);
    if (containingQName != null && containingQName.getComponentCount() > 0) {
      final QualifiedName absoluteQName = containingQName.append(myQualifiedName.toString());
      final QualifiedNameResolverImpl absoluteVisitor =
        (QualifiedNameResolverImpl)new QualifiedNameResolverImpl(absoluteQName).fromElement(foothold);

      final Sdk sdk = PythonSdkType.getSdk(foothold);
      if (sdk == null) return;
      final VirtualFile skeletonsDir = PySdkUtil.findSkeletonsDir(sdk);
      if (skeletonsDir == null) return;
      final PsiDirectory directory = myContext.getPsiManager().findDirectory(skeletonsDir);
      final PsiElement psiElement = absoluteVisitor.resolveModuleAt(directory);
      if (psiElement != null)
        myLibResults.add(psiElement);
    }
  }
}
项目:intellij-ce-playground    文件:ResolveImportUtil.java   
public static List<RatedResolveResult> resolveNameInFromImport(PyFromImportStatement importStatement, @NotNull QualifiedName qName) {
  PsiFile file = importStatement.getContainingFile().getOriginalFile();
  String name = qName.getComponents().get(0);

  final List<PsiElement> candidates = importStatement.resolveImportSourceCandidates();
  List<PsiElement> resultList = new ArrayList<PsiElement>();
  for (PsiElement candidate : candidates) {
    if (!candidate.isValid()) {
      throw new PsiInvalidElementAccessException(candidate, "Got an invalid candidate from resolveImportSourceCandidates(): " + candidate.getClass());
    }
    if (candidate instanceof PsiDirectory) {
      candidate = PyUtil.getPackageElement((PsiDirectory)candidate, importStatement);
    }
    PsiElement result = resolveChild(candidate, name, file, false, true);
    if (result != null) {
      if (!result.isValid()) {
        throw new PsiInvalidElementAccessException(result, "Got an invalid candidate from resolveChild(): " + result.getClass());
      }
      resultList.add(result);
    }
  }
  if (!resultList.isEmpty()) {
    return rateResults(resultList);
  }
  return Collections.emptyList();
}
项目:intellij-ce-playground    文件:PyQualifiedReference.java   
private int getImplicitResultRate(PyElement target, List<QualifiedName> imports) {
  int rate = RatedResolveResult.RATE_LOW;
  if (target.getContainingFile() == myElement.getContainingFile()) {
    rate += 200;
  }
  else {
    final VirtualFile vFile = target.getContainingFile().getVirtualFile();
    if (vFile != null) {
      if (ProjectScope.getProjectScope(myElement.getProject()).contains(vFile)) {
        rate += 80;
      }
      final QualifiedName qName = QualifiedNameFinder.findShortestImportableQName(myElement, vFile);
      if (qName != null && imports.contains(qName)) {
        rate += 70;
      }
    }
  }
  if (myElement.getParent() instanceof PyCallExpression) {
    if (target instanceof PyFunction) rate += 50;
  }
  else {
    if (!(target instanceof PyFunction)) rate += 50;
  }
  return rate;
}
项目:intellij-ce-playground    文件:PyStubsTest.java   
public void testImportStatement() {
  final PyFileImpl file = (PyFileImpl) getTestFile();

  final List<PyFromImportStatement> fromImports = file.getFromImports();
  assertEquals(1, fromImports.size());
  final PyFromImportStatement fromImport = fromImports.get(0);
  final PyImportElement[] importElements = fromImport.getImportElements();
  assertEquals(1, importElements.length);
  assertEquals("argv", importElements [0].getVisibleName());
  assertFalse(fromImport.isStarImport());
  assertEquals(0, fromImport.getRelativeLevel());
  final QualifiedName qName = fromImport.getImportSourceQName();
  assertSameElements(qName.getComponents(), "sys");

  final List<PyImportElement> importTargets = file.getImportTargets();
  assertEquals(1, importTargets.size());
  final PyImportElement importElement = importTargets.get(0);
  final QualifiedName importQName = importElement.getImportedQName();
  assertSameElements(importQName.getComponents(), "os", "path");

  assertNotParsed(file);
}
项目:intellij-ce-playground    文件:QualifiedNameFinder.java   
public boolean visitRoot(VirtualFile root, Module module, Sdk sdk, boolean isModuleSource) {
  if (myVFile != null) {
    final String relativePath = VfsUtilCore.getRelativePath(myVFile, root, '/');
    if (relativePath != null && !relativePath.isEmpty()) {
      List<String> result = StringUtil.split(relativePath, "/");
      if (result.size() > 0) {
        result.set(result.size() - 1, FileUtil.getNameWithoutExtension(result.get(result.size() - 1)));
      }
      for (String component : result) {
        if (!PyNames.isIdentifier(component)) {
          return true;
        }
      }
      myResults.add(QualifiedName.fromComponents(result));
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:PyFromImportStatementImpl.java   
public QualifiedName getImportSourceQName() {
  final PyFromImportStatementStub stub = getStub();
  if (stub != null) {
    final QualifiedName qName = stub.getImportSourceQName();
    if (qName != null && qName.getComponentCount() == 0) {  // relative import only: from .. import the_name
      return null;
    }
    return qName;
  }

  final PyReferenceExpression importSource = getImportSource();
  if (importSource == null) {
    return null;
  }
  return importSource.asQualifiedName();
}
项目:intellij-ce-playground    文件:PyTargetExpressionElementType.java   
public void serialize(@NotNull final PyTargetExpressionStub stub, @NotNull final StubOutputStream stream)
    throws IOException {
  stream.writeName(stub.getName());
  final String docString = stub.getDocString();
  stream.writeUTFFast(docString != null ? docString : "");
  stream.writeVarInt(stub.getInitializerType().getIndex());
  final CustomTargetExpressionStub customStub = stub.getCustomStub(CustomTargetExpressionStub.class);
  if (customStub != null) {
    stream.writeName(customStub.getTypeClass().getCanonicalName());
    customStub.serialize(stream);
  }
  else {
    QualifiedName.serialize(stub.getInitializer(), stream);
    stream.writeBoolean(stub.isQualified());
  }
}
项目:intellij-ce-playground    文件:PyTargetExpressionElementType.java   
@NotNull
public PyTargetExpressionStub deserialize(@NotNull final StubInputStream stream, final StubElement parentStub)
    throws IOException {
  String name = StringRef.toString(stream.readName());
  String docString = stream.readUTFFast();
  if (docString.isEmpty()) {
    docString = null;
  }
  PyTargetExpressionStub.InitializerType initializerType = PyTargetExpressionStub.InitializerType.fromIndex(stream.readVarInt());
  if (initializerType == PyTargetExpressionStub.InitializerType.Custom) {
    final String typeName = stream.readName().getString();
    for(CustomTargetExpressionStubType type: getCustomStubTypes()) {
      if (type.getClass().getCanonicalName().equals(typeName)) {
        CustomTargetExpressionStub stub = type.deserializeStub(stream);
        return new PyTargetExpressionStubImpl(name, docString, stub, parentStub);
      }
    }
    throw new IOException("Unknown custom stub type " + typeName);
  }
  QualifiedName initializer = QualifiedName.deserialize(stream);
  boolean isQualified = stream.readBoolean();
  return new PyTargetExpressionStubImpl(name, docString, initializerType, initializer, isQualified, parentStub);
}
项目:intellij-ce-playground    文件:PyImportedModule.java   
public PsiElement getElementNamed(String the_name) {
  QualifiedName prefix = myImportedPrefix.append(the_name);
  if (myImportElement != null) {
    final QualifiedName qName = myImportElement.getImportedQName();
    if (qName != null && qName.getComponentCount() == prefix.getComponentCount()) {
      return resolve(myImportElement, prefix);
    }
    return new PyImportedModule(myImportElement, myContainingFile, prefix);
  }
  final PyImportElement fromImportElement = findMatchingFromImport(myImportedPrefix, the_name);
  if (fromImportElement != null) {
    return fromImportElement.resolve();
  }

  return null;
}
项目:intellij-ce-playground    文件:PyFileImpl.java   
public boolean calculateImportFromFuture(FutureFeature feature) {
  if (getText().contains(feature.toString())) {
    final List<PyFromImportStatement> fromImports = getFromImports();
    for (PyFromImportStatement fromImport : fromImports) {
      if (fromImport.isFromFuture()) {
        final PyImportElement[] pyImportElements = fromImport.getImportElements();
        for (PyImportElement element : pyImportElements) {
          final QualifiedName qName = element.getImportedQName();
          if (qName != null && qName.matches(feature.toString())) {
            return true;
          }
        }
      }
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:PyTargetExpressionElementType.java   
public PyTargetExpressionStub createStub(@NotNull final PyTargetExpression psi, final StubElement parentStub) {
  final String name = psi.getName();
  final PyExpression assignedValue = psi.findAssignedValue();
  final String docString = DocStringUtil.getDocStringValue(psi);
  for (CustomTargetExpressionStubType customStubType : getCustomStubTypes()) {
    CustomTargetExpressionStub customStub = customStubType.createStub(psi);
    if (customStub != null) {
      return new PyTargetExpressionStubImpl(name, docString, customStub, parentStub);
    }
  }
  PyTargetExpressionStub.InitializerType initializerType = PyTargetExpressionStub.InitializerType.Other;
  QualifiedName initializer = null;
  if (assignedValue instanceof PyReferenceExpression) {
    initializerType = PyTargetExpressionStub.InitializerType.ReferenceExpression;
    initializer = ((PyReferenceExpression) assignedValue).asQualifiedName();
  }
  else if (assignedValue instanceof PyCallExpression) {
    initializerType = PyTargetExpressionStub.InitializerType.CallExpression;
    final PyExpression callee = ((PyCallExpression)assignedValue).getCallee();
    if (callee instanceof PyReferenceExpression) {
      initializer = ((PyReferenceExpression) callee).asQualifiedName();
    }
  }
  return new PyTargetExpressionStubImpl(name, docString, initializerType, initializer, psi.isQualified(), parentStub);
}
项目:intellij-ce-playground    文件:PyTargetExpressionImpl.java   
@Override
public QualifiedName getCalleeName() {
  final PyTargetExpressionStub stub = getStub();
  if (stub != null) {
    final PyTargetExpressionStub.InitializerType initializerType = stub.getInitializerType();
    if (initializerType == PyTargetExpressionStub.InitializerType.CallExpression) {
      return stub.getInitializer();
    }
    else if (initializerType == PyTargetExpressionStub.InitializerType.Custom) {
      final CustomTargetExpressionStub customStub = stub.getCustomStub(CustomTargetExpressionStub.class);
      if (customStub != null) {
        return customStub.getCalleeName();
      }
    }
    return null;
  }
  final PyExpression value = findAssignedValue();
  if (value instanceof PyCallExpression) {
    final PyExpression callee = ((PyCallExpression)value).getCallee();
    return PyPsiUtils.asQualifiedName(callee);
  }
  return null;
}
项目:idea-php-dotenv-plugin    文件:PythonPsiHelper.java   
/**
 * Checks os.environ[""] call
 * @param subscription checking element
 * @return true if
 */
static boolean checkIndexCall(PySubscriptionExpression subscription) {
    QualifiedName qualifiedName = subscription.asQualifiedName();

    if(qualifiedName == null) {
        return false;
    }

    String name = qualifiedName.toString();

    return name != null && name.equals("os.environ.__getitem__");
}
项目:intellij-ce-playground    文件:PyJavaImportCandidateProvider.java   
@Override
public void addImportCandidates(PsiReference reference, String name, AutoImportQuickFix quickFix) {
  final PsiElement element = reference.getElement();
  final Project project = element.getProject();
  Module module = ModuleUtil.findModuleForPsiElement(element);
  GlobalSearchScope scope = module == null ? ProjectScope.getAllScope(project) : module.getModuleWithDependenciesAndLibrariesScope(false);
  PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
  final PsiClass[] classesByName = cache.getClassesByName(name, scope);
  for (PsiClass psiClass : classesByName) {
    final QualifiedName packageQName = QualifiedName.fromDottedString(psiClass.getQualifiedName()).removeLastComponent();
    quickFix.addImport(psiClass, psiClass.getContainingFile(), packageQName);
  }
}
项目:intellij-ce-playground    文件:NumpyModuleMembersProvider.java   
private static void addTestingModule(PyFile module, List<PyCustomMember> members) {
  PyPsiFacade psiFacade = PyPsiFacade.getInstance(module.getProject());
  final QualifiedNameResolver resolver =
    psiFacade.qualifiedNameResolver(QualifiedName.fromDottedString("numpy.testing")).withPlainDirectories().fromElement(module);
  PsiElement testingModule = PyUtil.turnDirIntoInit(resolver.firstResult());
  members.add(new PyCustomMember("testing", testingModule));
}
项目:intellij-ce-playground    文件:PyUserSkeletonsUtil.java   
@Nullable
public static PyFile getUserSkeletonForModuleQName(@NotNull String qName, @NotNull PsiElement foothold) {
  final Sdk sdk = PythonSdkType.getSdk(foothold);
  if (sdk != null) {
    final Project project = foothold.getProject();
    final PythonSdkPathCache cache = PythonSdkPathCache.getInstance(project, sdk);
    final QualifiedName cacheQName = QualifiedName.fromDottedString(USER_SKELETONS_DIR + "." + qName);
    final List<PsiElement> results = cache.get(cacheQName);
    if (results != null) {
      final PsiElement element = results.isEmpty() ? null : results.get(0);
      if (element instanceof PyFile) {
        return (PyFile)element;
      }
    }
    final VirtualFile directory = getUserSkeletonsDirectory();
    if (directory != null) {
      final PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(directory);
      PsiElement fileSkeleton = new QualifiedNameResolverImpl(qName).resolveModuleAt(psiDirectory);
      if (fileSkeleton instanceof PsiDirectory) {
        fileSkeleton = PyUtil.getPackageElement((PsiDirectory)fileSkeleton, foothold);
      }
      if (fileSkeleton instanceof PyFile) {
        cache.put(cacheQName, Collections.singletonList(fileSkeleton));
        return (PyFile)fileSkeleton;
      }
    }
    cache.put(cacheQName, Collections.<PsiElement>emptyList());
  }
  return null;
}
项目:intellij-ce-playground    文件:PyReferenceExpressionImpl.java   
@Nullable
public QualifiedName asQualifiedName() {
  if (myQualifiedName == null) {
    myQualifiedName = PyPsiUtils.asQualifiedName(this);
  }
  return myQualifiedName;
}
项目:intellij-ce-playground    文件:PyImportReference.java   
@NotNull
@Override
protected List<RatedResolveResult> resolveInner() {
  final PyImportElement parent = PsiTreeUtil.getParentOfType(myElement, PyImportElement.class); //importRef.getParent();
  final QualifiedName qname = myElement.asQualifiedName();
  return qname == null ? Collections.<RatedResolveResult>emptyList() : ResolveImportUtil.resolveNameInImportStatement(parent, qname);
}
项目:intellij-ce-playground    文件:PyPsiUtils.java   
@NotNull
public static String toPath(@Nullable PyQualifiedExpression expr) {
  if (expr != null) {
    final QualifiedName qName = expr.asQualifiedName();
    if (qName != null) {
      return qName.toString();
    }
    final String name = expr.getName();
    if (name != null) {
      return name;
    }
  }
  return "";
}
项目:intellij-ce-playground    文件:PyStdlibModuleMembersProvider.java   
@Override
protected Collection<PyCustomMember> getMembersByQName(PyFile module, String qName) {
  if (qName.equals("os")) {
    final List<PyCustomMember> results = new ArrayList<PyCustomMember>();
    PsiElement path = null;
    if (module != null) {
      final String pathModuleName = SystemInfo.isWindows ? "ntpath" : "posixpath";
      path = ResolveImportUtil.resolveModuleInRoots(QualifiedName.fromDottedString(pathModuleName), module);
    }
    results.add(new PyCustomMember("path", path));
    return results;
  }
  return Collections.emptyList();
}
项目:intellij-ce-playground    文件:AddImportHelper.java   
/**
 * Adds an import statement, if it doesn't exist yet, presumably below all other initial imports in the file.
 *
 * @param file   where to operate
 * @param name   which to import (qualified is OK)
 * @param asName optional name for 'as' clause
 * @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 statement was actually added
 */
public static boolean addImportStatement(@NotNull PsiFile file,
                                         @NotNull String name,
                                         @Nullable String asName,
                                         @Nullable ImportPriority priority,
                                         @Nullable PsiElement anchor) {
  if (!(file instanceof PyFile)) {
    return false;
  }
  final List<PyImportElement> existingImports = ((PyFile)file).getImportTargets();
  for (PyImportElement element : existingImports) {
    final QualifiedName qName = element.getImportedQName();
    if (qName != null && name.equals(qName.toString())) {
      if ((asName != null && asName.equals(element.getAsName())) || asName == null) {
        return false;
      }
    }
  }

  final PyElementGenerator generator = PyElementGenerator.getInstance(file.getProject());
  final LanguageLevel languageLevel = LanguageLevel.forElement(file);
  final PyImportStatement importNodeToInsert = generator.createImportStatement(languageLevel, name, asName);
  final PyImportStatementBase importStatement = PsiTreeUtil.getParentOfType(anchor, PyImportStatementBase.class, false);
  final PsiElement insertParent = importStatement != null && importStatement.getContainingFile() == file ?
                                  importStatement.getParent() : file;
  try {
    if (anchor instanceof PyImportStatementBase) {
      insertParent.addAfter(importNodeToInsert, anchor);
    }
    else {
      insertParent.addBefore(importNodeToInsert, getInsertPosition(insertParent, importNodeToInsert, priority));
    }
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
  return true;
}
项目:intellij-ce-playground    文件:PyClassStubImpl.java   
public PyClassStubImpl(final String name, StubElement parentStub, final QualifiedName[] superClasses, @Nullable QualifiedName metaClass,
                       final List<String> slots, String docString, IStubElementType stubElementType) {
  super(parentStub, stubElementType);
  myName = name;
  mySuperClasses = superClasses;
  myMetaClass = metaClass;
  mySlots = slots;
  myDocString = docString;
}
项目:intellij-ce-playground    文件:AddImportHelper.java   
/**
 * 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);
    }
  }
}
项目:intellij-ce-playground    文件:PyQualifiedReference.java   
private void addImplicitResolveResults(String referencedName, ResolveResultList ret) {
  final Project project = myElement.getProject();
  final GlobalSearchScope scope = PyProjectScopeBuilder.excludeSdkTestsScope(project);
  final Collection functions = PyFunctionNameIndex.find(referencedName, project, scope);
  final PsiFile containingFile = myElement.getContainingFile();
  final List<QualifiedName> imports;
  if (containingFile instanceof PyFile) {
    imports = collectImports((PyFile)containingFile);
  }
  else {
    imports = Collections.emptyList();
  }
  for (Object function : functions) {
    if (!(function instanceof PyFunction)) {
      FileBasedIndex.getInstance().scheduleRebuild(StubUpdatingIndex.INDEX_ID,
                                                   new Throwable("found non-function object " + function + " in function list"));
      break;
    }
    PyFunction pyFunction = (PyFunction)function;
    if (pyFunction.getContainingClass() != null) {
      ret.add(new ImplicitResolveResult(pyFunction, getImplicitResultRate(pyFunction, imports)));
    }
  }

  final Collection attributes = PyInstanceAttributeIndex.find(referencedName, project, scope);
  for (Object attribute : attributes) {
    if (!(attribute instanceof PyTargetExpression)) {
      FileBasedIndex.getInstance().scheduleRebuild(StubUpdatingIndex.INDEX_ID,
                                                   new Throwable(
                                                     "found non-target expression object " + attribute + " in target expression list"));
      break;
    }
    ret.add(new ImplicitResolveResult((PyTargetExpression)attribute, getImplicitResultRate((PyTargetExpression)attribute, imports)));
  }
}
项目:intellij-ce-playground    文件:CompatibilityVisitor.java   
@Override
public void visitPyImportStatement(PyImportStatement node) {
  super.visitPyImportStatement(node);
  PyIfStatement ifParent = PsiTreeUtil.getParentOfType(node, PyIfStatement.class);
  if (ifParent != null)
    return;
  PyImportElement[] importElements = node.getImportElements();
  int len = 0;
  String moduleName = "";
  StringBuilder message = new StringBuilder(myCommonMessage);
  for (int i = 0; i != myVersionsToProcess.size(); ++i) {
    LanguageLevel languageLevel = myVersionsToProcess.get(i);
    for (PyImportElement importElement : importElements) {
      final QualifiedName qName = importElement.getImportedQName();
      if (qName != null) {
        if (!languageLevel.isPy3K()) {
          if (qName.matches("builtins")) {
            len = appendLanguageLevel(message, len, languageLevel);
            moduleName = "builtins";
          }
        }
        else {
          if (qName.matches("__builtin__")) {
            len = appendLanguageLevel(message, len, languageLevel);
            moduleName = "__builtin__";
          }
        }
      }
    }
  }
  commonRegisterProblem(message, " not have module " + moduleName, len, node, new ReplaceBuiltinsQuickFix());
}
项目:intellij-ce-playground    文件:PythonDocumentationMap.java   
@Nullable
public String urlFor(QualifiedName moduleQName, @Nullable PsiNamedElement element, String pyVersion) {
  for (Entry entry : myState.myEntries) {
    if (moduleQName.matchesPrefix(QualifiedName.fromDottedString(entry.myPrefix))) {
      return transformPattern(entry.myUrlPattern, moduleQName, element, pyVersion);
    }
  }
  return null;
}