private void addToResult(Map<PsiExpression, PsiType> map) { if (myResult == null) { myResult = new THashMap<>(map, ExpressionTypeMemoryState.EXPRESSION_HASHING_STRATEGY); } else { final Iterator<PsiExpression> iterator = myResult.keySet().iterator(); while (iterator.hasNext()) { PsiExpression psiExpression = iterator.next(); if (!myResult.get(psiExpression).equals(map.get(psiExpression))) { iterator.remove(); } } } }
private OccurenceNavigator getOccurrenceNavigator() { if (myCurrentViewType == null) { return EMPTY_NAVIGATOR; } final OccurenceNavigator navigator = myOccurrenceNavigators.get(myCurrentViewType); return navigator != null ? navigator : EMPTY_NAVIGATOR; }
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); }
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); } }
/** * @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); } }
@Contract("_, !null -> !null") public PsiSubstitutor findNestedSubstitutor( PsiElement arg, @Nullable PsiSubstitutor defaultSession) { InferenceSession session = myNestedSessions.get(PsiTreeUtil.getParentOfType(arg, PsiCall.class)); return session == null ? defaultSession : session.getInferenceSubstitution(); }
@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; }
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 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; }
/** * @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(); }
@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 PsiClass[] getCachedClassInDumbMode(String name) { Map<String, PsiClass[]> map = SoftReference.dereference(myClassCache); if (map == null) { map = new HashMap<String, PsiClass[]>(); for (PsiClass psiClass : getClasses(new EverythingGlobalScope(getProject()))) { String psiClassName = psiClass.getName(); if (psiClassName != null) { PsiClass[] existing = map.get(psiClassName); map.put( psiClassName, existing == null ? new PsiClass[] {psiClass} : ArrayUtil.append(existing, psiClass)); } } myClassCache = new SoftReference<Map<String, PsiClass[]>>(map); } PsiClass[] classes = map.get(name); return classes == null ? PsiClass.EMPTY_ARRAY : classes; }
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); } }
@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; }
@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 boolean isReferenced(@NotNull PsiNamedElement element) { List<PsiReference> array; synchronized (myLocalRefsMap) { array = myLocalRefsMap.getKeysByValue(element); } if (array != null && !array.isEmpty() && !isParameterUsedRecursively(element, array)) return true; Boolean usedStatus = myDclsUsedMap.get(PsiAnchor.create(element)); return usedStatus == Boolean.TRUE; }
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); }
@NotNull private static String createPrimaryConstructorInvocation( @NotNull String s, @NotNull List<? extends Field> fields, @NotNull Map<String, String> initializers) { List<String> result = new LinkedList<String>(); for (Field f : fields) { String id = f.getIdentifier().toKotlin(); result.add(initializers.get(id)); } return s + "(" + AstUtil.join(result, ", ") + ")"; }
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))); } } }
private static void rebindExternalReferences( PsiElement element, Map<PsiClass, PsiElement> oldToNewMap, Set<PsiElement> rebindExpressions) { final LocalSearchScope searchScope = new LocalSearchScope(element); for (PsiClass aClass : oldToNewMap.keySet()) { final PsiElement newClass = oldToNewMap.get(aClass); for (PsiReference reference : ReferencesSearch.search(aClass, searchScope)) { rebindExpressions.add(reference.bindToElement(newClass)); } } }
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 updateEditorsFromProperties() { String propertyName = getSelectedPropertyName(); ((CardLayout) myValuesPanel.getLayout()) .show(myValuesPanel, propertyName == null ? NO_PROPERTY_SELECTED : VALUES); if (propertyName == null) return; for (final PropertiesFile propertiesFile : myResourceBundle.getPropertiesFiles(myProject)) { final EditorEx editor = (EditorEx) myEditors.get(propertiesFile); if (editor == null) continue; final IProperty property = propertiesFile.findPropertyByKey(propertyName); final Document document = editor.getDocument(); CommandProcessor.getInstance() .executeCommand( null, new Runnable() { @Override public void run() { ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { updateDocumentFromPropertyValue( getPropertyEditorValue(property), document, propertiesFile); } }); } }, "", this); JPanel titledPanel = myTitledPanels.get(propertiesFile); ((TitledBorder) titledPanel.getBorder()) .setTitleColor(property == null ? JBColor.RED : UIUtil.getLabelTextForeground()); titledPanel.repaint(); } }
@NotNull private static FunctionDescriptor substituteSuperFunction( @NotNull Map<ClassDescriptor, JetType> superclassToSupertype, @NotNull FunctionDescriptor superFun) { DeclarationDescriptor superFunContainer = superFun.getContainingDeclaration(); assert superFunContainer instanceof ClassDescriptor : superFunContainer; JetType supertype = superclassToSupertype.get(superFunContainer); assert supertype != null : "Couldn't find super type for super function: " + superFun; TypeSubstitutor supertypeSubstitutor = TypeSubstitutor.create(supertype); FunctionDescriptor substitutedSuperFun = superFun.substitute(supertypeSubstitutor); assert substitutedSuperFun != null; return substitutedSuperFun; }
@Override @Nullable public PsiType getControlFlowExpressionType(@NotNull PsiExpression expr) { final Map<PsiExpression, PsiType> allCasts = getAllTypeCasts(expr); if (!allCasts.containsKey(expr)) { return null; // optimization } final Map<PsiExpression, PsiType> fromDfa = buildDataflowTypeMap(expr); if (fromDfa != null) { return fromDfa.get(expr); } return null; }
@Nullable public static PsiClass findInnerClassByName( GrTypeDefinition grType, String name, boolean checkBases) { if (!checkBases) { for (PsiClass inner : grType.getInnerClasses()) { if (name.equals(inner.getName())) return inner; } return null; } else { Map<String, CandidateInfo> innerClasses = CollectClassMembersUtil.getAllInnerClasses(grType, true); final CandidateInfo info = innerClasses.get(name); return info == null ? null : (PsiClass) info.getElement(); } }
// uses hierarchy signature tree if available, traverses class structure by itself otherwise public static boolean processDirectSuperMethodsSmart( @NotNull PsiMethod method, @NotNull Processor<PsiMethod> superMethodProcessor) { // boolean old = PsiSuperMethodUtil.isSuperMethod(method, superMethod); PsiClass aClass = method.getContainingClass(); if (aClass == null) return false; if (!canHaveSuperMethod(method, true, false)) return false; Map<MethodSignature, HierarchicalMethodSignature> cachedMap = SIGNATURES_KEY.getCachedValueOrNull(aClass); if (cachedMap != null) { HierarchicalMethodSignature signature = cachedMap.get(method.getSignature(PsiSubstitutor.EMPTY)); if (signature != null) { List<HierarchicalMethodSignature> superSignatures = signature.getSuperSignatures(); for (HierarchicalMethodSignature superSignature : superSignatures) { if (!superMethodProcessor.process(superSignature.getMethod())) return false; } return true; } } PsiClassType[] directSupers = aClass.getSuperTypes(); for (PsiClassType directSuper : directSupers) { PsiClassType.ClassResolveResult resolveResult = directSuper.resolveGenerics(); if (resolveResult.getSubstitutor() != PsiSubstitutor.EMPTY) { // generics break; } PsiClass directSuperClass = resolveResult.getElement(); if (directSuperClass == null) continue; PsiMethod[] candidates = directSuperClass.findMethodsBySignature(method, false); for (PsiMethod candidate : candidates) { if (PsiUtil.canBeOverriden(candidate)) { if (!superMethodProcessor.process(candidate)) return false; } } return true; } List<HierarchicalMethodSignature> superSignatures = method.getHierarchicalMethodSignature().getSuperSignatures(); for (HierarchicalMethodSignature superSignature : superSignatures) { if (!superMethodProcessor.process(superSignature.getMethod())) return false; } return true; }
@Nullable public static PsiField findFieldByName( GrTypeDefinition grType, String name, boolean checkBases, boolean includeSynthetic) { if (!checkBases) { for (PsiField field : CollectClassMembersUtil.getFields(grType, includeSynthetic)) { if (name.equals(field.getName())) return field; } return null; } Map<String, CandidateInfo> fieldsMap = CollectClassMembersUtil.getAllFields(grType, includeSynthetic); final CandidateInfo info = fieldsMap.get(name); return info == null ? null : (PsiField) info.getElement(); }
private static PsiExpression getLiteralExpression( PsiExpression context, PsiManager manager, @NotNull String text) { Map<String, PsiExpression> cache = LITERAL_EXPRESSION_CACHE.get(manager); if (cache == null) { cache = new ConcurrentSoftValueHashMap<String, PsiExpression>(); cache = manager.putUserDataIfAbsent(LITERAL_EXPRESSION_CACHE, cache); } PsiExpression expression = cache.get(text); if (expression == null) { expression = JavaPsiFacade.getElementFactory(manager.getProject()) .createExpressionFromText(text, context); cache.put(text, expression); } return expression; }
/** * Schedules action to be executed when all documents are committed. * * @return true if action has been run immediately, or false if action was scheduled for execution * later. */ @Override public boolean performWhenAllCommitted(@NotNull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); assert !myProject.isDisposed() : "Already disposed: " + myProject; if (myUncommittedDocuments.isEmpty()) { action.run(); return true; } CompositeRunnable actions = (CompositeRunnable) actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY); if (actions == null) { actions = new CompositeRunnable(); actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, actions); } actions.add(action); myDocumentCommitProcessor.log( "PDI: added performWhenAllCommitted", null, false, action, myUncommittedDocuments); return false; }