예제 #1
0
 @Override
 public DfaInstructionState[] visitPush(
     PushInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
   if (myContext == instruction.getPlace()) {
     final Map<DfaVariableValue, DfaVariableState> map =
         ((ValuableDataFlowRunner.MyDfaMemoryState) memState).getVariableStates();
     for (Map.Entry<DfaVariableValue, DfaVariableState> entry : map.entrySet()) {
       ValuableDataFlowRunner.ValuableDfaVariableState state =
           (ValuableDataFlowRunner.ValuableDfaVariableState) entry.getValue();
       DfaVariableValue variableValue = entry.getKey();
       final PsiExpression psiExpression = state.myExpression;
       if (psiExpression != null && variableValue.getQualifier() == null) {
         myValues.put(variableValue.getPsiVariable(), psiExpression);
       }
     }
     DfaValue value = instruction.getValue();
     if (value instanceof DfaVariableValue
         && ((DfaVariableValue) value).getQualifier() == null) {
       if (memState.isNotNull((DfaVariableValue) value)) {
         myNotNulls.add(((DfaVariableValue) value).getPsiVariable());
       }
       if (memState.isNull(value)) {
         myNulls.add(((DfaVariableValue) value).getPsiVariable());
       }
     }
   }
   return super.visitPush(instruction, runner, memState);
 }
예제 #2
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();
  }
  private void runAfterCommitActions(@NotNull Document document) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    List<Runnable> list;
    synchronized (ACTION_AFTER_COMMIT) {
      list = document.getUserData(ACTION_AFTER_COMMIT);
      if (list != null) {
        list = new ArrayList<Runnable>(list);
        document.putUserData(ACTION_AFTER_COMMIT, null);
      }
    }
    if (list != null) {
      for (final Runnable runnable : list) {
        runnable.run();
      }
    }

    if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) {
      List<Object> keys = new ArrayList<Object>(actionsWhenAllDocumentsAreCommitted.keySet());
      for (Object key : keys) {
        Runnable action = actionsWhenAllDocumentsAreCommitted.remove(key);
        myDocumentCommitProcessor.log("Running after commit runnable: ", null, false, key, action);
        action.run();
      }
    }
  }
  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);
  }
예제 #5
0
  protected void addLookupItem(
      Set<LookupElement> set,
      TailType tailType,
      @NotNull Object completion,
      final PsiFile file,
      final CompletionVariant variant) {
    LookupElement ret = objectToLookupItem(completion);
    if (ret == null) return;
    if (!(ret instanceof LookupItem)) {
      set.add(ret);
      return;
    }

    LookupItem item = (LookupItem) ret;

    final InsertHandler insertHandler = variant.getInsertHandler();
    if (insertHandler != null && item.getInsertHandler() == null) {
      item.setInsertHandler(insertHandler);
      item.setTailType(TailType.UNKNOWN);
    } else if (tailType != TailType.NONE) {
      item.setTailType(tailType);
    }
    final Map<Object, Object> itemProperties = variant.getItemProperties();
    for (final Object key : itemProperties.keySet()) {
      item.setAttribute(key, itemProperties.get(key));
    }

    set.add(ret);
  }
  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));
      }
    }
  }
예제 #7
0
 private void clear() {
   synchronized (myLocalRefsMap) {
     myLocalRefsMap.clear();
   }
   myImportStatements.clear();
   myDclsUsedMap.clear();
 }
 private static boolean copyOneClass(Map<PsiFile, PsiClass[]> classes) {
   if (classes.size() == 1) {
     final PsiClass[] psiClasses = classes.values().iterator().next();
     return psiClasses != null && psiClasses.length == 1;
   }
   return false;
 }
  @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;
  }
  /**
   * @param type
   * @param min
   * @param createDef
   * @param manager - must not be null if min is not null
   * @param scope - must not be null if min is not null
   */
  private GrTypeComboBox(
      @Nullable PsiType type,
      @Nullable PsiType min,
      boolean createDef,
      @Nullable PsiManager manager,
      @Nullable GlobalSearchScope scope) {
    LOG.assertTrue(min == null || manager != null);
    LOG.assertTrue(min == null || scope != null);

    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    Map<String, PsiType> types = Collections.emptyMap();
    if (type != null) {
      types = getCompatibleTypeNames(type, min, manager, scope);
    }

    if (createDef || types.isEmpty()) {
      addItem(new PsiTypeItem(null));
    }

    for (String typeName : types.keySet()) {
      addItem(new PsiTypeItem(types.get(typeName)));
    }

    if (createDef && getItemCount() > 1) {
      setSelectedIndex(1);
    }
  }
  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;
  }
  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;
  }
  /**
   * 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 JavaCompletionData getCompletionData(LanguageLevel level) {
   final Set<Map.Entry<LanguageLevel, JavaCompletionData>> entries = ourCompletionData.entrySet();
   for (Map.Entry<LanguageLevel, JavaCompletionData> entry : entries) {
     if (entry.getKey().isAtLeast(level)) return entry.getValue();
   }
   return ourCompletionData.get(LanguageLevel.JDK_1_3);
 }
 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 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);
  }
  @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 void releaseAllEditors() {
   for (final Editor editor : myEditors.values()) {
     if (!editor.isDisposed()) {
       EditorFactory.getInstance().releaseEditor(editor);
     }
   }
   myEditors.clear();
 }
  private static void fillFromSchema(PsiFile file, ElementNames names) {
    if (!(file instanceof XmlFile)) return;
    final XmlFile f = (XmlFile) file;
    final XmlDocument d = f.getDocument();
    if (d == null) return;
    final XmlTag rootTag = d.getRootTag();
    if (rootTag == null) return;

    //noinspection unchecked
    names.dependencies.add(new NSDeclTracker(rootTag));

    try {
      final Map<String, String> namespaceDeclarations = rootTag.getLocalNamespaceDeclarations();
      final Collection<String> prefixes = namespaceDeclarations.keySet();

      //noinspection unchecked
      final Set<XmlElementDescriptor> history = new THashSet<XmlElementDescriptor>();

      final XmlElementFactory ef = XmlElementFactory.getInstance(file.getProject());
      int noSchemaNamespaces = 0;
      for (String prefix : prefixes) {
        final String namespace = namespaceDeclarations.get(prefix);
        if (isIgnoredNamespace(prefix, namespace)) continue;

        final XmlTag tag =
            ef.createTagFromText("<dummy-tag xmlns='" + namespace + "' />", XMLLanguage.INSTANCE);
        final XmlDocument document = PsiTreeUtil.getParentOfType(tag, XmlDocument.class);
        final XmlNSDescriptor rootDescriptor = tag.getNSDescriptor(tag.getNamespace(), true);
        if (rootDescriptor == null
            || (rootDescriptor instanceof XmlNSDescriptorImpl
                && ((XmlNSDescriptorImpl) rootDescriptor).getTag() == null)
            || !rootDescriptor.getDeclaration().isPhysical()) {
          final QName any = QNameUtil.createAnyLocalName(namespace);
          names.elementNames.add(any);
          names.attributeNames.add(any);
          noSchemaNamespaces++;
          continue;
        }

        //noinspection unchecked
        names.dependencies.add(rootDescriptor.getDescriptorFile());

        final XmlElementDescriptor[] e = rootDescriptor.getRootElementsDescriptors(document);
        for (XmlElementDescriptor descriptor : e) {
          processElementDescriptors(descriptor, tag, names, history);
        }
      }

      names.validateNames = names.elementNames.size() > noSchemaNamespaces;

      //            final QName any = QNameUtil.createAnyLocalName("");
      //            names.elementNames.add(any);
      //            names.attributeNames.add(any);
    } catch (IncorrectOperationException e) {
      Logger.getInstance(XsltContextProvider.class.getName()).error(e);
    }
  }
  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);
  }
 @Override
 public boolean forbidToClone(PsiElement[] elements, boolean fromUpdate) {
   final Map<PsiFile, PsiClass[]> fileMap =
       convertToTopLevelClasses(elements, fromUpdate, null, null);
   if (fileMap != null && fileMap.size() == 1) {
     final PsiClass[] psiClasses = fileMap.values().iterator().next();
     return psiClasses != null && psiClasses.length > 1;
   }
   return true;
 }
예제 #23
0
 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;
 }
예제 #24
0
  @NotNull
  private ClassifierDescriptor modifyTypeClassifier(
      @NotNull JetType autoType, @NotNull List<TypeAndVariance> typesFromSuper) {
    ClassifierDescriptor classifier = autoType.getConstructor().getDeclarationDescriptor();
    if (!(classifier instanceof ClassDescriptor)) {
      assert classifier != null : "no declaration descriptor for type " + autoType;

      if (classifier instanceof TypeParameterDescriptor
          && autoTypeParameterToModified.containsKey(classifier)) {
        return autoTypeParameterToModified.get(classifier);
      }
      return classifier;
    }
    ClassDescriptor klass = (ClassDescriptor) classifier;

    CollectionClassMapping collectionMapping = CollectionClassMapping.getInstance();

    boolean someSupersMutable = false;
    boolean someSupersCovariantReadOnly = false;
    boolean someSupersNotCovariantReadOnly = false;
    for (TypeAndVariance typeFromSuper : typesFromSuper) {
      ClassifierDescriptor classifierFromSuper =
          typeFromSuper.type.getConstructor().getDeclarationDescriptor();
      if (classifierFromSuper instanceof ClassDescriptor) {
        ClassDescriptor classFromSuper = (ClassDescriptor) classifierFromSuper;

        if (collectionMapping.isMutableCollection(classFromSuper)) {
          someSupersMutable = true;
        } else if (collectionMapping.isReadOnlyCollection(classFromSuper)) {
          if (typeFromSuper.varianceOfPosition == Variance.OUT_VARIANCE) {
            someSupersCovariantReadOnly = true;
          } else {
            someSupersNotCovariantReadOnly = true;
          }
        }
      }
    }

    if (someSupersMutable && someSupersNotCovariantReadOnly) {
      reportError("Incompatible types in superclasses: " + typesFromSuper);
      return classifier;
    } else if (someSupersMutable) {
      if (collectionMapping.isReadOnlyCollection(klass)) {
        return collectionMapping.convertReadOnlyToMutable(klass);
      }
    } else if (someSupersNotCovariantReadOnly || someSupersCovariantReadOnly) {
      if (collectionMapping.isMutableCollection(klass)) {
        return collectionMapping.convertMutableToReadOnly(klass);
      }
    }

    ClassifierDescriptor fixed =
        PropagationHeuristics.tryToFixOverridingTWithRawType(this, typesFromSuper);
    return fixed != null ? fixed : classifier;
  }
 public static PsiField[] getAllFields(GrTypeDefinition grType) {
   Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType);
   return ContainerUtil.map2Array(
       fieldsMap.values(),
       PsiField.class,
       new Function<CandidateInfo, PsiField>() {
         public PsiField fun(CandidateInfo entry) {
           return (PsiField) entry.getElement();
         }
       });
 }
예제 #26
0
 @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;
   }
 }
 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;
 }
 private static void decodeRef(
     final PsiJavaCodeReferenceElement expression,
     final Map<PsiClass, PsiElement> oldToNewMap,
     Set<PsiElement> rebindExpressions) {
   final PsiElement resolved = expression.resolve();
   if (resolved instanceof PsiClass) {
     final PsiClass psiClass = (PsiClass) resolved;
     if (oldToNewMap.containsKey(psiClass)) {
       rebindExpressions.add(expression.bindToElement(oldToNewMap.get(psiClass)));
     }
   }
 }
예제 #30
0
  public String getAttributeValue(String qname) { // todo ?
    Map<String, String> map = myAttributeValueMap;
    while (map == null) {
      getAttributes();
      map = myAttributeValueMap;

      if (map == null) {
        myAttributes = null;
      }
    }
    return map.get(qname);
  }