public static void addCompletions( @NotNull final JavaSmartCompletionParameters parameters, @NotNull Consumer<LookupElement> result, final PrefixMatcher matcher) { final Condition<String> shortNameCondition = new Condition<String>() { public boolean value(String s) { return matcher.prefixMatches(s); } }; PsiType classParameter = PsiUtil.substituteTypeParameter( parameters.getExpectedType(), CommonClassNames.JAVA_LANG_CLASS, 0, false); boolean addInheritors = false; PsiElement position = parameters.getPosition(); if (classParameter instanceof PsiWildcardType) { final PsiWildcardType wildcardType = (PsiWildcardType) classParameter; classParameter = wildcardType.getBound(); addInheritors = wildcardType.isExtends() && classParameter instanceof PsiClassType; } else if (!matcher.getPrefix().isEmpty()) { addInheritors = true; classParameter = PsiType.getJavaLangObject(position.getManager(), position.getResolveScope()); } if (classParameter != null) { PsiFile file = position.getContainingFile(); addClassLiteralLookupElement(classParameter, result, file); if (addInheritors) { addInheritorClassLiterals(file, shortNameCondition, classParameter, result, matcher); } } }
@Nullable public static CreateClassOrPackageFix createFix( @NotNull final String qualifiedName, @NotNull final PsiElement context, @Nullable ClassKind kind, String superClass) { return createFix( qualifiedName, context.getResolveScope(), context, null, kind, superClass, null); }
@Nullable @Override protected List<ClosureParameterInfo> getParameterInfos( InsertionContext context, PsiMethod method, PsiSubstitutor substitutor, Document document, int offset, PsiElement parent) { final String name = method.getName(); if (!"eachWithIndex".equals(name)) return null; if (method instanceof GrGdkMethod) method = ((GrGdkMethod) method).getStaticMethod(); final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) return null; final String qname = containingClass.getQualifiedName(); if (!GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(qname)) return null; final PsiParameter[] parameters = method.getParameterList().getParameters(); if (parameters.length != 2) return null; final PsiType type = parameters[0].getType(); final PsiType collection = substitutor.substitute(type); final PsiType iterable = getIteratedType(parent, collection); if (iterable != null) { return Arrays.asList( new ClosureParameterInfo(iterable.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } if (InheritanceUtil.isInheritor(collection, CommonClassNames.JAVA_UTIL_MAP)) { final PsiType[] typeParams = ((PsiClassType) collection).getParameters(); final Project project = context.getProject(); final PsiClass entry = JavaPsiFacade.getInstance(project) .findClass("java.util.Map.Entry", parent.getResolveScope()); if (entry == null) return null; final PsiClassType entryType = JavaPsiFacade.getElementFactory(project).createType(entry, typeParams); return Arrays.asList( new ClosureParameterInfo(entryType.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } return Arrays.asList( new ClosureParameterInfo(collection.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); }
public static boolean addStaticImport( @NotNull String qualifierClass, @NonNls @NotNull String memberName, @NotNull PsiElement context) { if (!nameCanBeStaticallyImported(qualifierClass, memberName, context)) { return false; } final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); if (InheritanceUtil.isInheritor(containingClass, qualifierClass)) { return true; } final PsiFile psiFile = context.getContainingFile(); if (!(psiFile instanceof PsiJavaFile)) { return false; } final PsiJavaFile javaFile = (PsiJavaFile) psiFile; final PsiImportList importList = javaFile.getImportList(); if (importList == null) { return false; } final PsiImportStatementBase existingImportStatement = importList.findSingleImportStatement(memberName); if (existingImportStatement != null) { return false; } final PsiImportStaticStatement onDemandImportStatement = findOnDemandImportStaticStatement(importList, qualifierClass); if (onDemandImportStatement != null && !hasOnDemandImportStaticConflict(qualifierClass, memberName, context)) { return true; } final Project project = context.getProject(); final GlobalSearchScope scope = context.getResolveScope(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass aClass = psiFacade.findClass(qualifierClass, scope); if (aClass == null) { return false; } final String qualifiedName = aClass.getQualifiedName(); if (qualifiedName == null) { return false; } final List<PsiImportStaticStatement> imports = getMatchingImports(importList, qualifiedName); final CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project); final PsiElementFactory elementFactory = psiFacade.getElementFactory(); if (imports.size() < codeStyleSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND) { importList.add(elementFactory.createImportStaticStatement(aClass, memberName)); } else { for (PsiImportStaticStatement importStatement : imports) { importStatement.delete(); } importList.add(elementFactory.createImportStaticStatement(aClass, "*")); } return true; }
@Override public boolean processDeclarations( @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { GlobalSearchScope scope = place.getResolveScope(); processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this); ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); final JavaPsiFacade facade = getFacade(); final Condition<String> prefixMatcher = processor.getHint(JavaCompletionHints.NAME_FILTER); if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) { NameHint nameHint = processor.getHint(NameHint.KEY); if (nameHint != null) { final String shortName = nameHint.getName(state); if (containsClassNamed(shortName) && processClassesByName(processor, state, scope, shortName)) return false; } else if (prefixMatcher != null) { for (String className : getClassNamesCache()) { if (prefixMatcher.value(className)) { if (processClassesByName(processor, state, scope, className)) return false; } } } else { PsiClass[] classes = getClasses(scope); if (!processClasses(processor, state, classes)) return false; } } if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.PACKAGE)) { NameHint nameHint = processor.getHint(NameHint.KEY); if (nameHint != null) { PsiPackage aPackage = findSubPackageByName(nameHint.getName(state)); if (aPackage != null) { if (!processor.execute(aPackage, state)) return false; } } else { PsiPackage[] packs = getSubPackages(scope); for (PsiPackage pack : packs) { final String packageName = pack.getName(); if (packageName == null) continue; if (!facade.getNameHelper().isIdentifier(packageName, PsiUtil.getLanguageLevel(this))) { continue; } if (!processor.execute(pack, state)) { return false; } } } } return true; }
public PsiVariable getVariable() { if (myVariable == null) { final PsiManager manager = myNavigationElement.getManager(); PsiType type = RecursionManager.doPreventingRecursion( this, true, new Computable<PsiType>() { @Override public PsiType compute() { PsiType res = null; for (GrExpression expression : myExpressions) { if (expression == null) continue; res = TypesUtil.getLeastUpperBoundNullable(res, expression.getType(), manager); } if (myExpressionsOfCollection != null) { for (GrExpression expression : myExpressionsOfCollection) { if (expression == null) continue; PsiType listType = expression.getType(); PsiType type = PsiUtil.extractIterableTypeParameter(listType, true); if (type == null) { if (listType == null) continue; if (listType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { type = PsiType.getJavaLangString( expression.getManager(), expression.getResolveScope()); } } res = TypesUtil.getLeastUpperBoundNullable(res, type, manager); } } return res; } }); if (type == null) { type = PsiType.getJavaLangObject(manager, myNavigationElement.getResolveScope()); } myVariable = new SpockVariable(manager, myName, type, myNavigationElement); } return myVariable; }
@NotNull public static PsiType createSetType(@NotNull PsiElement context, @NotNull PsiType type) { JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getProject()); GlobalSearchScope resolveScope = context.getResolveScope(); PsiClass setClass = facade.findClass(JAVA_UTIL_SET, resolveScope); if (setClass != null && setClass.getTypeParameters().length == 1) { return facade.getElementFactory().createType(setClass, type); } return facade.getElementFactory().createTypeByFQClassName(JAVA_UTIL_SET, resolveScope); }
@Override public boolean processDeclarations( @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { GlobalSearchScope scope = place.getResolveScope(); processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this); ElementClassHint classHint = processor.getHint(ElementClassHint.KEY); final Condition<String> nameCondition = processor.getHint(JavaCompletionHints.NAME_FILTER); if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) { NameHint nameHint = processor.getHint(NameHint.KEY); if (nameHint != null) { final String shortName = nameHint.getName(state); final PsiClass[] classes = findClassByShortName(shortName, scope); if (!processClasses(processor, state, classes, Conditions.<String>alwaysTrue())) return false; } else { PsiClass[] classes = getClasses(scope); if (!processClasses( processor, state, classes, nameCondition != null ? nameCondition : Conditions.<String>alwaysTrue())) return false; } } if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.PACKAGE)) { NameHint nameHint = processor.getHint(NameHint.KEY); if (nameHint != null) { PsiPackage aPackage = findSubPackageByName(nameHint.getName(state)); if (aPackage != null) { if (!processor.execute(aPackage, state)) return false; } } else { PsiPackage[] packs = getSubPackages(scope); for (PsiPackage pack : packs) { final String packageName = pack.getName(); if (packageName == null) continue; if (!PsiNameHelper.getInstance(myManager.getProject()) .isIdentifier(packageName, PsiUtil.getLanguageLevel(this))) { continue; } if (!processor.execute(pack, state)) { return false; } } } } return true; }
public CompletionResolveScopeProcessor( @NotNull CSharpResolveOptions options, @NotNull ExecuteTarget[] targets) { myPlace = options.getElement(); Collections.addAll(myElements, options.getAdditionalElements()); myScope = myPlace.getResolveScope(); CSharpContextUtil.ContextType completionContextType = options.getCompletionContextType(); if (completionContextType != null) { myContextType = completionContextType; } else { myContextType = myPlace instanceof CSharpReferenceExpression ? CSharpContextUtil.getParentContextTypeForReference( (CSharpReferenceExpression) myPlace) : CSharpContextUtil.ContextType.ANY; } putUserData(ExecuteTargetUtil.EXECUTE_TARGETS, ExecuteTargetUtil.of(targets)); }
public static boolean isAssignableWithoutConversions( @Nullable PsiType lType, @Nullable PsiType rType, @NotNull PsiElement context) { if (lType == null || rType == null) return false; if (rType == PsiType.NULL) { return !(lType instanceof PsiPrimitiveType); } PsiManager manager = context.getManager(); GlobalSearchScope scope = context.getResolveScope(); if (rType instanceof GrTupleType && ((GrTupleType) rType).getComponentTypes().length == 0) { if (lType instanceof PsiArrayType || InheritanceUtil.isInheritor(lType, JAVA_UTIL_LIST) || InheritanceUtil.isInheritor(lType, JAVA_UTIL_SET)) { return true; } } if (isClassType(rType, GROOVY_LANG_GSTRING) && lType.equalsToText(JAVA_LANG_STRING)) { return true; } if (isNumericType(lType) && isNumericType(rType)) { lType = unboxPrimitiveTypeWrapper(lType); if (isClassType(lType, JAVA_MATH_BIG_DECIMAL)) lType = PsiType.DOUBLE; rType = unboxPrimitiveTypeWrapper(rType); if (isClassType(rType, JAVA_MATH_BIG_DECIMAL)) rType = PsiType.DOUBLE; } else { rType = boxPrimitiveType(rType, manager, scope); lType = boxPrimitiveType(lType, manager, scope); } if (rType instanceof GrMapType || rType instanceof GrTupleType) { Boolean result = isAssignableForNativeTypes(lType, (PsiClassType) rType, context); if (result != null && result.booleanValue()) return true; } if (TypeConversionUtil.isAssignable(lType, rType)) { return true; } return false; }
@Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) return; final XmlAttribute attr = (XmlAttribute) element.getParent(); final String name = attr.getName(); final XmlAttributeDescriptor descriptor = attr.getDescriptor(); LOG.assertTrue(descriptor != null); String value = attr.getValue(); final PsiElement declaration = descriptor.getDeclaration(); if (declaration instanceof PsiField) { final PsiType fieldType = ((PsiField) declaration).getType(); final PsiType itemType = JavaGenericsUtil.getCollectionItemType(fieldType, declaration.getResolveScope()); if (itemType != null) { final String typeNode = itemType.getPresentableText(); JavaFxPsiUtil.insertImportWhenNeeded( (XmlFile) attr.getContainingFile(), typeNode, itemType.getCanonicalText()); final String[] vals = value.split(","); value = StringUtil.join( vals, new Function<String, String>() { @Override public String fun(String s) { return "<" + typeNode + " " + FxmlConstants.FX_VALUE + "=\"" + s.trim() + "\"/>"; } }, "\n"); } } final XmlTag childTag = XmlElementFactory.getInstance(project) .createTagFromText("<" + name + ">" + value + "</" + name + ">"); attr.getParent().add(childTag); attr.delete(); }
public static PsiType buildTypeFromTypeString( @NotNull final String typeName, @NotNull final PsiElement context, @NotNull final PsiFile psiFile) { PsiType resultType; final PsiManager psiManager = psiFile.getManager(); if (typeName.indexOf('<') != -1 || typeName.indexOf('[') != -1 || typeName.indexOf('.') == -1) { try { return JavaPsiFacade.getInstance(psiManager.getProject()) .getElementFactory() .createTypeFromText(typeName, context); } catch (Exception ignored) { } // invalid syntax will produce unresolved class type } PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()) .findClass(typeName, context.getResolveScope()); if (aClass == null) { final LightClassReference ref = new LightClassReference( psiManager, PsiNameHelper.getShortClassName(typeName), typeName, PsiSubstitutor.EMPTY, psiFile); resultType = new PsiClassReferenceType(ref, null); } else { PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); PsiSubstitutor substitutor = factory.createRawSubstitutor(aClass); resultType = factory.createType(aClass, substitutor); } return resultType; }
public static boolean isInside(PsiElement place, PsiElement ancestor) { if (ancestor instanceof PsiDirectoryContainer) { final PsiDirectory[] directories = ((PsiDirectoryContainer) ancestor).getDirectories(place.getResolveScope()); for (PsiDirectory directory : directories) { if (isInside(place, directory)) return true; } } if (ancestor instanceof PsiFile) { for (PsiFile file : ((PsiFile) ancestor).getViewProvider().getAllFiles()) { if (PsiTreeUtil.isAncestor(file, place, false)) return true; } } boolean isAncestor = PsiTreeUtil.isAncestor(ancestor, place, false); if (!isAncestor && ancestor instanceof PsiNameIdentifierOwner) { final PsiElement nameIdentifier = ((PsiNameIdentifierOwner) ancestor).getNameIdentifier(); if (nameIdentifier != null && !PsiTreeUtil.isAncestor(ancestor, nameIdentifier, true)) { isAncestor = PsiTreeUtil.isAncestor(nameIdentifier.getParent(), place, false); } } if (!isAncestor) { final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(place.getProject()); PsiLanguageInjectionHost host = injectedLanguageManager.getInjectionHost(place); while (host != null) { if (PsiTreeUtil.isAncestor(ancestor, host, false)) { isAncestor = true; break; } host = injectedLanguageManager.getInjectionHost(host); } } return isAncestor; }
public static boolean checkTestNGInClasspath(PsiElement psiElement) { final Project project = psiElement.getProject(); final PsiManager manager = PsiManager.getInstance(project); if (JavaPsiFacade.getInstance(manager.getProject()) .findClass(TestNG.class.getName(), psiElement.getResolveScope()) == null) { if (!ApplicationManager.getApplication().isUnitTestMode()) { if (Messages.showOkCancelDialog( psiElement.getProject(), "TestNG will be added to module classpath", "Unable to convert.", Messages.getWarningIcon()) != Messages.OK) { return false; } } final Module module = ModuleUtilCore.findModuleForPsiElement(psiElement); if (module == null) return false; String url = VfsUtil.getUrlForLibraryRoot(new File(PathUtil.getJarPathForClass(Assert.class))); ModuleRootModificationUtil.addModuleLibrary(module, url); } return true; }
@NotNull public static PsiClassType createTypeByFQClassName( @NotNull String fqName, @NotNull PsiElement context) { return GroovyPsiManager.getInstance(context.getProject()) .createTypeByFQClassName(fqName, context.getResolveScope()); }
@NotNull public static PsiClassType getJavaLangObject(@NotNull PsiElement context) { return PsiType.getJavaLangObject(context.getManager(), context.getResolveScope()); }
@Override public void invoke( @NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { final PsiModifierList myModifierList = (PsiModifierList) startElement; final PsiVariable variable = myVariable == null ? null : myVariable.getElement(); if (!CodeInsightUtilBase.preparePsiElementForWrite(myModifierList)) return; final List<PsiModifierList> modifierLists = new ArrayList<PsiModifierList>(); final PsiFile containingFile = myModifierList.getContainingFile(); final PsiModifierList modifierList; if (variable != null && variable.isValid()) { ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { try { variable.normalizeDeclaration(); } catch (IncorrectOperationException e) { LOG.error(e); } } }); modifierList = variable.getModifierList(); assert modifierList != null; } else { modifierList = myModifierList; } PsiElement owner = modifierList.getParent(); if (owner instanceof PsiMethod) { PsiModifierList copy = (PsiModifierList) myModifierList.copy(); changeModifierList(copy); final int accessLevel = PsiUtil.getAccessLevel(copy); OverridingMethodsSearch.search((PsiMethod) owner, owner.getResolveScope(), true) .forEach( new PsiElementProcessorAdapter<PsiMethod>( new PsiElementProcessor<PsiMethod>() { public boolean execute(@NotNull PsiMethod inheritor) { PsiModifierList list = inheritor.getModifierList(); if (inheritor.getManager().isInProject(inheritor) && PsiUtil.getAccessLevel(list) < accessLevel) { modifierLists.add(list); } return true; } })); } if (!CodeInsightUtilBase.prepareFileForWrite(containingFile)) return; if (!modifierLists.isEmpty()) { if (Messages.showYesNoDialog( project, QuickFixBundle.message("change.inheritors.visibility.warning.text"), QuickFixBundle.message("change.inheritors.visibility.warning.title"), Messages.getQuestionIcon()) == DialogWrapper.OK_EXIT_CODE) { ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { if (!CodeInsightUtilBase.preparePsiElementsForWrite(modifierLists)) { return; } for (final PsiModifierList modifierList : modifierLists) { changeModifierList(modifierList); } } }); } } ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { changeModifierList(modifierList); UndoUtil.markPsiFileForUndo(containingFile); } }); }
public static boolean isAssignable( @Nullable PsiType lType, @Nullable PsiType rType, @NotNull PsiElement context) { if (lType == null || rType == null) { return false; } if (rType instanceof PsiIntersectionType) { for (PsiType child : ((PsiIntersectionType) rType).getConjuncts()) { if (isAssignable(lType, child, context)) { return true; } } return false; } if (lType instanceof PsiIntersectionType) { for (PsiType child : ((PsiIntersectionType) lType).getConjuncts()) { if (!isAssignable(child, rType, context)) { return false; } } return true; } if (rType == PsiType.NULL) { return !(lType instanceof PsiPrimitiveType); } if (isNumericType(lType) && isNumericType(rType)) { return true; } if (isClassType(lType, JAVA_LANG_STRING)) { return true; } final PsiManager manager = context.getManager(); final GlobalSearchScope scope = context.getResolveScope(); if (lType instanceof PsiArrayType) { PsiType lComponentType = ((PsiArrayType) lType).getComponentType(); PsiType rComponentType = ClosureParameterEnhancer.findTypeForIteration(rType, context); if (rComponentType != null && isAssignable(lComponentType, rComponentType, context)) { return true; } } if (unboxPrimitiveTypeWrapper(lType) == PsiType.CHAR && (isClassType(rType, JAVA_LANG_STRING) || isClassType(rType, GROOVY_LANG_GSTRING))) { return true; } if (isAssignableByMethodCallConversion(lType, rType, context)) return true; lType = boxPrimitiveType(lType, manager, scope); rType = boxPrimitiveType(rType, manager, scope); if (lType.isAssignableFrom(rType)) { return true; } if (context instanceof GroovyPsiElement) { for (GrTypeConverter converter : GrTypeConverter.EP_NAME.getExtensions()) { if (!converter.isAllowedInMethodCall()) { Boolean result = converter.isConvertible(lType, rType, (GroovyPsiElement) context); if (result != null) { return result; } } } } return false; }