public HierarchyBrowserBaseEx(@NotNull Project project, @NotNull PsiElement element) {
    super(project);

    setHierarchyBase(element);

    myCardLayout = new CardLayout();
    myTreePanel = new JPanel(myCardLayout);

    createTrees(myType2TreeMap);

    final HierarchyBrowserManager.State state =
        HierarchyBrowserManager.getInstance(project).getState();
    for (String type : myType2TreeMap.keySet()) {
      myType2ScopeMap.put(type, state.SCOPE != null ? state.SCOPE : SCOPE_ALL);
    }

    final Enumeration<String> keys = myType2TreeMap.keys();
    while (keys.hasMoreElements()) {
      final String key = keys.nextElement();
      final JTree tree = myType2TreeMap.get(key);
      myOccurrenceNavigators.put(
          key,
          new OccurenceNavigatorSupport(tree) {
            @Override
            @Nullable
            protected Navigatable createDescriptorForNode(DefaultMutableTreeNode node) {
              final HierarchyNodeDescriptor descriptor = getDescriptor(node);
              if (descriptor == null) return null;
              PsiElement psiElement = getOpenFileElementFromDescriptor(descriptor);
              if (psiElement == null || !psiElement.isValid()) return null;
              final VirtualFile virtualFile = psiElement.getContainingFile().getVirtualFile();
              if (virtualFile == null) return null;
              return new OpenFileDescriptor(
                  psiElement.getProject(), virtualFile, psiElement.getTextOffset());
            }

            @Override
            public String getNextOccurenceActionName() {
              return getNextOccurenceActionNameImpl();
            }

            @Override
            public String getPreviousOccurenceActionName() {
              return getPrevOccurenceActionNameImpl();
            }
          });
      myTreePanel.add(ScrollPaneFactory.createScrollPane(tree), key);
    }

    final JPanel legendPanel = createLegendPanel();
    final JPanel contentPanel;
    if (legendPanel != null) {
      contentPanel = new JPanel(new BorderLayout());
      contentPanel.add(myTreePanel, BorderLayout.CENTER);
      contentPanel.add(legendPanel, BorderLayout.SOUTH);
    } else {
      contentPanel = myTreePanel;
    }
    buildUi(createToolbar(getActionPlace(), HELP_ID).getComponent(), contentPanel);
  }
 private static void putInMap(
     PsiClass aClass,
     Map<MethodSignature, HierarchicalMethodSignature> result,
     Map<MethodSignature, HierarchicalMethodSignatureImpl> map,
     HierarchicalMethodSignature hierarchicalMethodSignature,
     MethodSignature signature) {
   if (!PsiUtil.isAccessible(
       aClass.getProject(), hierarchicalMethodSignature.getMethod(), aClass, aClass)) return;
   HierarchicalMethodSignatureImpl existing = map.get(signature);
   if (existing == null) {
     HierarchicalMethodSignatureImpl copy = copy(hierarchicalMethodSignature);
     LOG.assertTrue(copy.getMethod().isValid());
     map.put(signature, copy);
   } else if (isReturnTypeIsMoreSpecificThan(hierarchicalMethodSignature, existing)
       && isSuperMethod(aClass, hierarchicalMethodSignature, existing)) {
     HierarchicalMethodSignatureImpl newSuper = copy(hierarchicalMethodSignature);
     mergeSupers(newSuper, existing);
     LOG.assertTrue(newSuper.getMethod().isValid());
     map.put(signature, newSuper);
   } else if (isSuperMethod(aClass, existing, hierarchicalMethodSignature)) {
     mergeSupers(existing, hierarchicalMethodSignature);
   }
   // just drop an invalid method declaration there - to highlight accordingly
   else if (!result.containsKey(signature)) {
     LOG.assertTrue(hierarchicalMethodSignature.getMethod().isValid());
     result.put(signature, hierarchicalMethodSignature);
   }
 }
  public static void replaceMovedMemberTypeParameters(
      final PsiElement member,
      final Iterable<PsiTypeParameter> parametersIterable,
      final PsiSubstitutor substitutor,
      final GroovyPsiElementFactory factory) {
    final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<PsiElement, PsiElement>();
    for (PsiTypeParameter parameter : parametersIterable) {
      PsiType substitutedType = substitutor.substitute(parameter);
      if (substitutedType == null) {
        substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
      }

      PsiElement scopeElement = member instanceof GrField ? member.getParent() : member;
      for (PsiReference reference :
          ReferencesSearch.search(parameter, new LocalSearchScope(scopeElement))) {
        final PsiElement element = reference.getElement();
        final PsiElement parent = element.getParent();
        if (parent instanceof PsiTypeElement) {
          replacement.put(parent, factory.createTypeElement(substitutedType));
        } else if (element instanceof GrCodeReferenceElement
            && substitutedType instanceof PsiClassType) {
          replacement.put(
              element, factory.createReferenceElementByType((PsiClassType) substitutedType));
        }
      }
    }

    for (PsiElement element : replacement.keySet()) {
      if (element.isValid()) {
        element.replace(replacement.get(element));
      }
    }
  }
  private static Map<String, PsiType> getCompatibleTypeNames(
      @NotNull PsiType type, @Nullable PsiType min, PsiManager manager, GlobalSearchScope scope) {
    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    // if initial type is not assignable to min type we don't take into consideration min type.
    if (min != null && !TypesUtil.isAssignable(min, type, manager, scope)) {
      min = null;
    }

    Map<String, PsiType> map = new LinkedHashMap<String, PsiType>();
    final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type);
    if (unboxed != null) type = unboxed;
    final Set<PsiType> set = new LinkedHashSet<PsiType>();
    set.add(type);
    while (!set.isEmpty()) {
      PsiType cur = set.iterator().next();
      set.remove(cur);
      if (!map.containsValue(cur)
          && (min == null || TypesUtil.isAssignable(min, cur, manager, scope))) {
        if (isPartiallySubstituted(cur)) {
          LOG.assertTrue(cur instanceof PsiClassType);
          PsiClassType rawType = ((PsiClassType) cur).rawType();
          map.put(rawType.getPresentableText(), rawType);
        } else {
          map.put(cur.getPresentableText(), cur);
        }
        for (PsiType superType : cur.getSuperTypes()) {
          if (!map.containsValue(superType)) {
            set.add(superType);
          }
        }
      }
    }
    return map;
  }
 private static void fillResultsMap(
     Map<PsiFile, PsiClass[]> result, PsiFile containingFile, PsiClass[] topLevelClasses) {
   PsiClass[] classes = result.get(containingFile);
   if (topLevelClasses != null) {
     if (classes != null) {
       topLevelClasses = ArrayUtil.mergeArrays(classes, topLevelClasses, PsiClass.ARRAY_FACTORY);
     }
     result.put(containingFile, topLevelClasses);
   } else {
     result.put(containingFile, classes);
   }
 }
  private void putAllInternal(@NotNull PsiClass parentClass, PsiType[] mappings) {
    final PsiTypeParameter[] params = parentClass.getTypeParameters();

    for (int i = 0; i < params.length; i++) {
      PsiTypeParameter param = params[i];
      assert param != null;
      if (mappings != null && mappings.length > i) {
        mySubstitutionMap.put(param, mappings[i]);
      } else {
        mySubstitutionMap.put(param, null);
      }
    }
  }
 public <Option> void addCustomization(
     CustomizableReferenceProvider.CustomizationKey<Option> key, Option value) {
   if (myOptions == null) {
     myOptions = new HashMap<CustomizableReferenceProvider.CustomizationKey, Object>(5);
   }
   myOptions.put(key, value);
 }
  @Nullable
  private <T extends RefElement> T getFromRefTableOrCache(
      final PsiElement element,
      @NotNull NullableFactory<T> factory,
      @Nullable Consumer<T> whenCached) {

    PsiAnchor psiAnchor = createAnchor(element);
    T result;
    synchronized (myRefTable) {
      //noinspection unchecked
      result = (T) myRefTable.get(psiAnchor);

      if (result != null) return result;

      if (!isValidPointForReference()) {
        // LOG.assertTrue(true, "References may become invalid after process is finished");
        return null;
      }

      result = factory.create();
      if (result == null) return null;

      myRefTable.put(psiAnchor, result);
      mySortedRefs = null;

      if (whenCached != null) {
        whenCached.consume(result);
      }
    }

    return result;
  }
  private ClassMapCachingNulls<MultiHostInjector> getInjectorMap() {
    ClassMapCachingNulls<MultiHostInjector> cached = cachedInjectors;
    if (cached != null) {
      return cached;
    }

    Map<Class, MultiHostInjector[]> injectors = ContainerUtil.newHashMap();

    List<MultiHostInjector> allInjectors = ContainerUtil.newArrayList();
    allInjectors.addAll(myManualInjectors);
    Collections.addAll(
        allInjectors, MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME.getExtensions(myProject));
    if (LanguageInjector.EXTENSION_POINT_NAME.getExtensions().length > 0) {
      allInjectors.add(PsiManagerRegisteredInjectorsAdapter.INSTANCE);
    }

    for (MultiHostInjector injector : allInjectors) {
      for (Class<? extends PsiElement> place : injector.elementsToInjectIn()) {
        LOG.assertTrue(place != null, injector);
        MultiHostInjector[] existing = injectors.get(place);
        injectors.put(
            place,
            existing == null
                ? new MultiHostInjector[] {injector}
                : ArrayUtil.append(existing, injector));
      }
    }

    ClassMapCachingNulls<MultiHostInjector> result =
        new ClassMapCachingNulls<>(injectors, new MultiHostInjector[0], allInjectors);
    cachedInjectors = result;
    return result;
  }
Beispiel #10
0
  /**
   * @return true, if the element contains a reference to a different class than fullyQualifiedName
   *     but which has the same class name
   */
  public static boolean containsConflictingReference(PsiFile element, String fullyQualifiedName) {
    final Map<String, Boolean> cachedValue =
        CachedValuesManager.getManager(element.getProject())
            .getCachedValue(
                element,
                new CachedValueProvider<Map<String, Boolean>>() {
                  @Nullable
                  @Override
                  public Result<Map<String, Boolean>> compute() {
                    return new Result<Map<String, Boolean>>(
                        Collections.synchronizedMap(new HashMap<String, Boolean>()),
                        PsiModificationTracker.MODIFICATION_COUNT);
                  }
                });
    Boolean conflictingRef = cachedValue.get(fullyQualifiedName);
    if (conflictingRef != null) {
      return conflictingRef.booleanValue();
    }

    final ConflictingClassReferenceVisitor visitor =
        new ConflictingClassReferenceVisitor(fullyQualifiedName);
    element.accept(visitor);
    conflictingRef = visitor.isConflictingReferenceFound();
    cachedValue.put(fullyQualifiedName, conflictingRef);

    return conflictingRef.booleanValue();
  }
Beispiel #11
0
  public void collectCommonPluginRoots(
      Map<String, VirtualFile> result, @NotNull Module module, boolean refresh) {
    if (isCommonPluginsModule(module)) {
      for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) {
        String pluginName = getInstalledPluginNameByPath(module.getProject(), root);
        if (pluginName != null) {
          result.put(pluginName, root);
        }
      }
    } else {
      VirtualFile root = findAppRoot(module);
      if (root == null) return;

      extractPlugins(
          module.getProject(), root.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY), result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getCommonPluginsDir(module), refresh),
          result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getGlobalPluginsDir(module), refresh),
          result);
    }
  }
  @Override
  @SuppressWarnings({"HardCodedStringLiteral"})
  public void loadState(Element element) {
    Element entryPointsElement = element.getChild("entry_points");
    if (entryPointsElement != null) {
      final String version = entryPointsElement.getAttributeValue(VERSION_ATTR);
      if (!Comparing.strEqual(version, VERSION)) {
        convert(entryPointsElement, myPersistentEntryPoints);
      } else {
        List content = entryPointsElement.getChildren();
        for (final Object aContent : content) {
          Element entryElement = (Element) aContent;
          if (ENTRY_POINT_ATTR.equals(entryElement.getName())) {
            SmartRefElementPointerImpl entryPoint = new SmartRefElementPointerImpl(entryElement);
            myPersistentEntryPoints.put(entryPoint.getFQName(), entryPoint);
          }
        }
      }
    }
    try {
      ADDITIONAL_ANNOTATIONS.readExternal(element);
    } catch (Throwable ignored) {
    }

    getPatterns().clear();
    for (Element pattern : element.getChildren("pattern")) {
      final ClassPattern classPattern = new ClassPattern();
      XmlSerializer.deserializeInto(classPattern, pattern);
      getPatterns().add(classPattern);
    }
  }
Beispiel #13
0
 private void acquire(@NotNull ProgressIndicator indicator) {
   RefCountHolder holder = get();
   assert holder != null : "no way";
   map.put(indicator, holder);
   holder = get();
   assert holder != null : "can't be!";
 }
  /**
   * Get array string values mapped with their PsiElements
   *
   * <p>["value", "value2"]
   */
  @NotNull
  public static Map<String, PsiElement> getArrayValuesAsMap(
      @NotNull ArrayCreationExpression arrayCreationExpression) {

    List<PsiElement> arrayValues =
        PhpPsiUtil.getChildren(
            arrayCreationExpression,
            new Condition<PsiElement>() {
              @Override
              public boolean value(PsiElement psiElement) {
                return psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE;
              }
            });

    if (arrayValues == null) {
      return Collections.emptyMap();
    }

    Map<String, PsiElement> keys = new HashMap<String, PsiElement>();
    for (PsiElement child : arrayValues) {
      String stringValue = PhpElementsUtil.getStringValue(child.getFirstChild());
      if (stringValue != null && StringUtils.isNotBlank(stringValue)) {
        keys.put(stringValue, child);
      }
    }

    return keys;
  }
  private static PsiSubstitutor obtainFinalSubstitutor(
      PsiClass superClass,
      PsiSubstitutor superSubstitutor,
      PsiSubstitutor derivedSubstitutor,
      boolean inRawContext) {
    if (inRawContext) {
      Set<PsiTypeParameter> typeParams = superSubstitutor.getSubstitutionMap().keySet();
      PsiElementFactory factory = JavaPsiFacade.getElementFactory(superClass.getProject());
      superSubstitutor =
          factory.createRawSubstitutor(
              derivedSubstitutor, typeParams.toArray(new PsiTypeParameter[typeParams.size()]));
    }
    Map<PsiTypeParameter, PsiType> map = null;
    for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(superClass)) {
      PsiType type = superSubstitutor.substitute(typeParameter);
      final PsiType t = derivedSubstitutor.substitute(type);
      if (map == null) {
        map = new THashMap<PsiTypeParameter, PsiType>();
      }
      map.put(typeParameter, t);
    }

    return map == null
        ? PsiSubstitutor.EMPTY
        : JavaPsiFacade.getInstance(superClass.getProject())
            .getElementFactory()
            .createSubstitutor(map);
  }
  @Override
  public void addEntryPoint(@NotNull RefElement newEntryPoint, boolean isPersistent) {
    if (!newEntryPoint.isValid()) return;
    if (isPersistent) {
      if (newEntryPoint instanceof RefMethod && ((RefMethod) newEntryPoint).isConstructor()
          || newEntryPoint instanceof RefClass) {
        final ClassPattern classPattern = new ClassPattern();
        classPattern.pattern = new SmartRefElementPointerImpl(newEntryPoint, true).getFQName();
        getPatterns().add(classPattern);

        final EntryPointsManager entryPointsManager =
            getInstance(newEntryPoint.getElement().getProject());
        if (this != entryPointsManager) {
          entryPointsManager.addEntryPoint(newEntryPoint, true);
        }

        return;
      }
    }

    if (newEntryPoint instanceof RefClass) {
      RefClass refClass = (RefClass) newEntryPoint;

      if (refClass.isAnonymous()) {
        // Anonymous class cannot be an entry point.
        return;
      }

      List<RefMethod> refConstructors = refClass.getConstructors();
      if (refConstructors.size() == 1) {
        addEntryPoint(refConstructors.get(0), isPersistent);
      } else if (refConstructors.size() > 1) {
        // Many constructors here. Need to ask user which ones are used
        for (RefMethod refConstructor : refConstructors) {
          addEntryPoint(refConstructor, isPersistent);
        }
      }
    }

    if (!isPersistent) {
      myTemporaryEntryPoints.add(newEntryPoint);
      ((RefElementImpl) newEntryPoint).setEntry(true);
    } else {
      if (myPersistentEntryPoints.get(newEntryPoint.getExternalName()) == null) {
        final SmartRefElementPointerImpl entry =
            new SmartRefElementPointerImpl(newEntryPoint, true);
        myPersistentEntryPoints.put(entry.getFQName(), entry);
        ((RefElementImpl) newEntryPoint).setEntry(true);
        ((RefElementImpl) newEntryPoint).setPermanentEntry(true);
        if (entry.isPersistent()) { // do save entry points
          final EntryPointsManager entryPointsManager =
              getInstance(newEntryPoint.getElement().getProject());
          if (this != entryPointsManager) {
            entryPointsManager.addEntryPoint(newEntryPoint, true);
          }
        }
      }
    }
  }
 private static Map<String, LocalVariableProxyImpl> getVisibleVariables(
     final StackFrameProxyImpl frame) throws EvaluateException {
   final Map<String, LocalVariableProxyImpl> vars = new HashMap<String, LocalVariableProxyImpl>();
   for (LocalVariableProxyImpl localVariableProxy : frame.visibleVariables()) {
     vars.put(localVariableProxy.name(), localVariableProxy);
   }
   return vars;
 }
  private static CompoundInitialState createState(InferenceSession topLevelSession) {
    final PsiSubstitutor topInferenceSubstitutor =
        replaceVariables(topLevelSession.getInferenceVariables());
    final Map<PsiElement, InitialInferenceState> nestedStates =
        new LinkedHashMap<PsiElement, InitialInferenceState>();

    final InferenceSessionContainer copy =
        new InferenceSessionContainer() {
          @Override
          public PsiSubstitutor findNestedSubstitutor(
              PsiElement arg, @Nullable PsiSubstitutor defaultSession) {
            // for the case foo(bar(a -> m())): top level inference won't touch lambda "a -> m()"
            // for the case foo(a -> bar(b -> m())): top level inference would go till nested lambda
            // "b -> m()" and the state from top level could be found here by "bar(b -> m())"
            // but proceeding with additional constraints from saved point would produce new
            // expression constraints with different inference variables (could be found in
            // myNestedSessions)
            // which won't be found in the system if we won't reject stored sessions in such cases
            final PsiSubstitutor substitutor = super.findNestedSubstitutor(arg, null);
            if (substitutor != null) {
              return substitutor;
            }

            final InitialInferenceState state =
                nestedStates.get(PsiTreeUtil.getParentOfType(arg, PsiCall.class));
            if (state != null) {
              return state.getInferenceSubstitutor();
            }
            return super.findNestedSubstitutor(arg, defaultSession);
          }
        };
    final Map<PsiElement, InferenceSession> nestedSessions =
        topLevelSession.getInferenceSessionContainer().myNestedSessions;
    for (Map.Entry<PsiElement, InferenceSession> entry : nestedSessions.entrySet()) {
      nestedStates.put(
          entry.getKey(),
          entry
              .getValue()
              .createInitialState(
                  copy, topLevelSession.getInferenceVariables(), topInferenceSubstitutor));
    }

    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    for (InferenceVariable variable : topLevelSession.getInferenceVariables()) {
      final PsiType instantiation = variable.getInstantiation();
      if (instantiation != PsiType.NULL) {
        final PsiClass psiClass =
            PsiUtil.resolveClassInClassTypeOnly(topInferenceSubstitutor.substitute(variable));
        if (psiClass instanceof InferenceVariable) {
          substitutor = substitutor.put((PsiTypeParameter) psiClass, instantiation);
        }
      }
    }

    return new CompoundInitialState(substitutor, nestedStates);
  }
 private static Map<ClassDescriptor, JetType> getSuperclassToSupertypeMap(
     ClassDescriptor containingClass) {
   Map<ClassDescriptor, JetType> superclassToSupertype = Maps.newHashMap();
   for (JetType supertype : TypeUtils.getAllSupertypes(containingClass.getDefaultType())) {
     ClassifierDescriptor superclass = supertype.getConstructor().getDeclarationDescriptor();
     assert superclass instanceof ClassDescriptor;
     superclassToSupertype.put((ClassDescriptor) superclass, supertype);
   }
   return superclassToSupertype;
 }
Beispiel #20
0
 private void processInterface(PsiClass inheritor, PsiClass anInterface) {
   for (Iterator<PsiMethod> methodIterator = myRemainingMethods.iterator();
       methodIterator.hasNext(); ) {
     PsiMethod method = methodIterator.next();
     SiblingInfo info = findSibling(inheritor, anInterface, method);
     if (info != null) {
       myResult.put(method, info);
       methodIterator.remove();
     }
   }
 }
 @NotNull
 public Map<String, String> getLocalNamespaceDeclarations() {
   Map<String, String> namespaces = new THashMap<String, String>();
   for (final XmlAttribute attribute : getAttributes()) {
     if (!attribute.isNamespaceDeclaration() || attribute.getValue() == null) continue;
     // xmlns -> "", xmlns:a -> a
     final String localName = attribute.getLocalName();
     namespaces.put(localName.equals(attribute.getName()) ? "" : localName, attribute.getValue());
   }
   return namespaces;
 }
 @NotNull
 private AnnotationData internAnnotationData(@NotNull AnnotationData data) {
   synchronized (annotationDataCache) {
     AnnotationData interned = annotationDataCache.get(data);
     if (interned == null) {
       annotationDataCache.put(data, data);
       interned = data;
     }
     return interned;
   }
 }
Beispiel #23
0
 private static void decodeRef(
     final PsiJavaCodeReferenceElement expression,
     final Map<PsiClass, PsiElement> oldToNewMap,
     Map<PsiJavaCodeReferenceElement, PsiElement> rebindExpressions) {
   final PsiElement resolved = expression.resolve();
   if (resolved instanceof PsiClass) {
     final PsiClass psiClass = (PsiClass) resolved;
     if (oldToNewMap.containsKey(psiClass)) {
       rebindExpressions.put(expression, oldToNewMap.get(psiClass));
     }
   }
 }
    private boolean processClass(
        PsiClass resolve,
        PsiSubstitutor originalSubstitutor,
        final Map<PsiTypeParameter, PsiType> substMap) {
      final PsiTypeParameter[] params = resolve.getTypeParameters();
      for (final PsiTypeParameter param : params) {
        final PsiType original = originalSubstitutor.substitute(param);
        if (original == null) {
          substMap.put(param, null);
        } else {
          final PsiType substituted = substituteInternal(original);
          if (substituted == null) return false;
          substMap.put(param, substituted);
        }
      }
      if (resolve.hasModifierProperty(PsiModifier.STATIC)) return true;

      final PsiClass containingClass = resolve.getContainingClass();
      return containingClass == null
          || processClass(containingClass, originalSubstitutor, substMap);
    }
 public MethodParameterInjection copyFrom(@NotNull BaseInjection o) {
   super.copyFrom(o);
   if (o instanceof MethodParameterInjection) {
     final MethodParameterInjection other = (MethodParameterInjection) o;
     myClassName = other.getClassName();
     myParameterMap.clear();
     for (MethodInfo info : other.myParameterMap.values()) {
       myParameterMap.put(info.methodSignature, info.copy());
     }
   }
   return this;
 }
 @Nullable
 private static Map<PsiFile, PsiClass[]> convertToTopLevelClasses(
     final PsiElement[] elements,
     final boolean fromUpdate,
     String relativePath,
     Map<PsiFile, String> relativeMap) {
   final Map<PsiFile, PsiClass[]> result = new HashMap<PsiFile, PsiClass[]>();
   for (PsiElement element : elements) {
     final PsiElement navigationElement = element.getNavigationElement();
     LOG.assertTrue(navigationElement != null, element);
     final PsiFile containingFile = navigationElement.getContainingFile();
     if (!(containingFile instanceof PsiClassOwner
         && ProjectRootsUtil.isOutsideSourceRoot(containingFile))) {
       PsiClass[] topLevelClasses = getTopLevelClasses(element);
       if (topLevelClasses == null) {
         if (element instanceof PsiDirectory) {
           if (!fromUpdate) {
             final String name = ((PsiDirectory) element).getName();
             final String path =
                 relativePath != null
                     ? (relativePath.length() > 0 ? (relativePath + "/") : "") + name
                     : null;
             final Map<PsiFile, PsiClass[]> map =
                 convertToTopLevelClasses(element.getChildren(), fromUpdate, path, relativeMap);
             if (map == null) return null;
             for (Map.Entry<PsiFile, PsiClass[]> entry : map.entrySet()) {
               fillResultsMap(result, entry.getKey(), entry.getValue());
             }
           }
           continue;
         }
         if (!(element instanceof PsiFileSystemItem)) return null;
       }
       fillResultsMap(result, containingFile, topLevelClasses);
       if (relativeMap != null) {
         relativeMap.put(containingFile, relativePath);
       }
     }
   }
   if (result.isEmpty()) {
     return null;
   } else {
     boolean hasClasses = false;
     for (PsiClass[] classes : result.values()) {
       if (classes != null) {
         hasClasses = true;
         break;
       }
     }
     return hasClasses ? result : null;
   }
 }
 protected void readExternalImpl(Element e) {
   if (e.getAttribute("injector-id") == null) {
     setClassName(JDOMExternalizer.readString(e, "CLASS"));
     // setApplyInHierarchy(JDOMExternalizer.readBoolean(e, "APPLY_IN_HIERARCHY"));
     readOldFormat(e);
     final THashMap<String, String> map = new THashMap<>();
     JDOMExternalizer.readMap(e, map, null, "SIGNATURES");
     for (String s : map.keySet()) {
       final String fixedSignature = fixSignature(s, false);
       myParameterMap.put(fixedSignature, new MethodInfo(fixedSignature, map.get(s)));
     }
   }
 }
  private JetDecompiledData build() {
    myBuilder.append(PsiBundle.message("psi.decompiled.text.header"));
    myBuilder.append("\n\n");

    String packageName = myClsFile.getPackageName();
    if (packageName.length() > 0) {
      myBuilder.append("package ").append(packageName).append("\n\n");
    }

    PsiClass psiClass = myClsFile.getClasses()[0];

    if (isKotlinNamespaceClass(psiClass)) {
      NamespaceDescriptor nd =
          myJavaDescriptorResolver.resolveNamespace(
              new FqName(packageName), DescriptorSearchRule.INCLUDE_KOTLIN);

      if (nd != null) {
        for (DeclarationDescriptor member :
            sortDeclarations(nd.getMemberScope().getAllDescriptors())) {
          if (member instanceof ClassDescriptor || member instanceof NamespaceDescriptor) {
            continue;
          }
          appendDescriptor(member, "");
          myBuilder.append("\n");
        }
      }
    } else {
      ClassDescriptor cd =
          myJavaDescriptorResolver.resolveClass(psiClass, DescriptorSearchRule.INCLUDE_KOTLIN);
      if (cd != null) {
        appendDescriptor(cd, "");
      }
    }

    JetFile jetFile =
        JetDummyClassFileViewProvider.createJetFile(
            myClsFile.getManager(), myClsFile.getVirtualFile(), myBuilder.toString());
    for (Map.Entry<PsiElement, TextRange> clsMemberToRange : myClsMembersToRanges.entrySet()) {
      PsiElement clsMember = clsMemberToRange.getKey();
      assert clsMember instanceof ClsElementImpl;

      TextRange range = clsMemberToRange.getValue();
      JetDeclaration jetDeclaration =
          PsiTreeUtil.findElementOfClassAtRange(
              jetFile, range.getStartOffset(), range.getEndOffset(), JetDeclaration.class);
      assert jetDeclaration != null;
      myClsElementsToJetElements.put((ClsElementImpl) clsMember, jetDeclaration);
    }

    return new JetDecompiledData(jetFile, myClsElementsToJetElements);
  }
 @Override
 public void prepareRenaming(
     final PsiElement element, final String newName, final Map<PsiElement, String> allRenames) {
   GrField field = (GrField) element;
   final PsiMethod getter = GroovyPropertyUtils.findGetterForField(field);
   final PsiMethod setter = GroovyPropertyUtils.findSetterForField(field);
   if (getter != null && !(getter instanceof GrAccessorMethod)
       || setter != null && !(setter instanceof GrAccessorMethod)) {
     if (askToRenameAccesors(getter, setter, newName, element.getProject())) {
       if (getter != null && !(getter instanceof GrAccessorMethod)) {
         String name = getter.getName();
         allRenames.put(
             getter,
             name.startsWith("is")
                 ? "is" + StringUtil.capitalize(newName)
                 : "get" + StringUtil.capitalize(newName));
       }
       if (setter != null && !(setter instanceof GrAccessorMethod)) {
         allRenames.put(setter, "set" + StringUtil.capitalize(newName));
       }
     }
   }
 }
Beispiel #30
0
 private void extractPlugins(
     Project project, @Nullable VirtualFile pluginRoot, Map<String, VirtualFile> res) {
   if (pluginRoot != null) {
     VirtualFile[] children = pluginRoot.getChildren();
     if (children != null) {
       for (VirtualFile child : children) {
         String pluginName = getInstalledPluginNameByPath(project, child);
         if (pluginName != null) {
           res.put(pluginName, child);
         }
       }
     }
   }
 }