下面列出了怎么用com.intellij.psi.PsiType的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean isPsiMethodCamelLanguage(PsiMethod method) {
PsiType type = method.getReturnType();
if (type != null && type instanceof PsiClassReferenceType) {
PsiClassReferenceType clazz = (PsiClassReferenceType) type;
PsiClass resolved = clazz.resolve();
if (resolved != null) {
boolean language = getCamelIdeaUtils().isCamelExpressionOrLanguage(resolved);
// try parent using some weird/nasty stub stuff which is how complex IDEA AST
// is when its parsing the Camel route builder
if (!language) {
PsiElement elem = resolved.getParent();
if (elem instanceof PsiTypeParameterList) {
elem = elem.getParent();
}
if (elem instanceof PsiClass) {
language = getCamelIdeaUtils().isCamelExpressionOrLanguage((PsiClass) elem);
}
}
return language;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LombokLightParameter that = (LombokLightParameter) o;
final PsiType thisType = getType();
final PsiType thatType = that.getType();
if (thisType.isValid() != thatType.isValid()) {
return false;
}
return thisType.getCanonicalText().equals(thatType.getCanonicalText());
}
@Override
public String renderBuildCode(@NotNull PsiVariable psiVariable, @NotNull String fieldName, @NotNull String builderVariable) {
final PsiManager psiManager = psiVariable.getManager();
final PsiType psiFieldType = psiVariable.getType();
final PsiType rowKeyType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 0);
final PsiType columnKeyType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 1);
final PsiType valueType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 2);
return MessageFormat.format(
"{4}<{1}, {2}, {3}> {0} = " +
"{5}.{0} == null ? " +
"{4}.<{1}, {2}, {3}>of() : " +
"{5}.{0}.build();\n",
fieldName, rowKeyType.getCanonicalText(false), columnKeyType.getCanonicalText(false),
valueType.getCanonicalText(false), collectionQualifiedName, builderVariable);
}
private void visitPsiFields(final PsiField psiField) {
if (!ClassUtils.isPrimitive(psiField.getType())) {
String type = removeSpecialSymbols(psiField.getType().getCanonicalText());
if (psiField.getInitializer() != null) {
PsiExpression psiExpression = psiField.getInitializer();
if (psiExpression != null) {
PsiType psiType = psiExpression.getType();
if (psiType != null && !ClassUtils.isPrimitive(psiType)) {
String psiFieldInitializer =
removeSpecialSymbols(psiType.getCanonicalText());
addInMap(psiFieldInitializer, emptySet);
}
}
}
addInMap(type, emptySet);
}
}
private boolean validateExistingMethods(@NotNull PsiField psiField, @NotNull ProblemBuilder builder) {
boolean result = true;
final PsiClass psiClass = psiField.getContainingClass();
if (null != psiClass) {
final boolean isBoolean = PsiType.BOOLEAN.equals(psiField.getType());
final AccessorsInfo accessorsInfo = AccessorsInfo.build(psiField);
final Collection<String> methodNames = LombokUtils.toAllGetterNames(accessorsInfo, psiField.getName(), isBoolean);
final Collection<PsiMethod> classMethods = PsiClassUtil.collectClassMethodsIntern(psiClass);
filterToleratedElements(classMethods);
for (String methodName : methodNames) {
if (PsiMethodUtil.hasSimilarMethod(classMethods, methodName, 0)) {
final String setterMethodName = LombokUtils.getGetterName(psiField);
builder.addWarning("Not generated '%s'(): A method with similar name '%s' already exists", setterMethodName, methodName);
result = false;
}
}
}
return result;
}
@Test
public void createOnEventMethodInSection() {
testHelper.getPsiClass(
psiClasses -> {
Assert.assertNotNull(psiClasses);
PsiClass hasSectionAnnotation = psiClasses.get(0);
PsiMethod onEventMethod =
OnEventGenerateUtils.createOnEventMethod(
hasSectionAnnotation, hasSectionAnnotation, Collections.emptyList());
Assert.assertEquals(1, onEventMethod.getParameters().length);
PsiType contextType = (PsiType) onEventMethod.getParameters()[0].getType();
Assert.assertEquals(
LithoClassNames.SECTION_CONTEXT_CLASS_NAME, contextType.getCanonicalText());
return true;
},
"OnEventSectionSpec.java");
}
@Nullable
public static PsiType safeGetValidType(@NotNull Module module, @NotNull String fqn) {
try {
// Intellij expects inner classes to be referred via `.` instead of `$`
PsiType type = JavaPsiFacade.getInstance(module.getProject()).getParserFacade()
.createTypeFromText(fqn.replaceAll("\\$", "."), null);
boolean typeValid = isValidType(type);
if (typeValid) {
if (type instanceof PsiClassType) {
return PsiClassType.class.cast(type);
} else if (type instanceof PsiArrayType) {
return PsiArrayType.class.cast(type);
}
}
return null;
} catch (IncorrectOperationException e) {
debug(() -> log.debug("Unable to find class fqn " + fqn));
return null;
}
}
public static boolean isValidType(@NotNull PsiType type) {
if (!type.isValid()) {
TimeoutUtil.sleep(
1); // to see if processing in another thread suddenly makes the type valid again (which is a bug)
if (!type.isValid()) {
return false;
}
}
if (type instanceof PsiArrayType) {
return isValidType(PsiArrayType.class.cast(type).getComponentType());
} else if (type instanceof PsiWildcardType) {
PsiType bound = ((PsiWildcardType) type).getBound();
return bound != null && isValidType(bound);
} else if (type instanceof PsiCapturedWildcardType) {
PsiType lowerBound = ((PsiCapturedWildcardType) type).getLowerBound();
type = (lowerBound != NULL ? lowerBound : ((PsiCapturedWildcardType) type).getUpperBound());
return type != NULL && isValidType(type);
} else if (type instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
return classResolveResult.isValidResult() && isValidElement(
requireNonNull(classResolveResult.getElement())) && !hasUnresolvedComponents(type);
}
return true;
}
@Nullable
@Override
protected String doGetDocumentationForValue(Module module, String nodeNavigationPathDotDelimited,
String originalValue) {
// Format for the documentation is as follows
/*
* <p><b>a.b.c</b> ({@link com.acme.Generic}<{@link com.acme.Class1}, {@link com.acme.Class2}>)</p>
* <p>Long description</p>
* or of this type
* <p><b>Type</b> {@link com.acme.Array}[]</p>
* <p><b>Declared at</b>{@link com.acme.GenericRemovedClass#method}></p> <-- only for groups with method info
*/
StringBuilder builder =
new StringBuilder().append("<b>").append(nodeNavigationPathDotDelimited).append("</b>");
String classFqn = PsiType.BOOLEAN.getBoxedTypeName();
StringBuilder linkBuilder = new StringBuilder();
createHyperlink(linkBuilder, classFqn, classFqn, false);
builder.append(" (").append(linkBuilder.toString()).append(")");
builder.append("<p>").append(originalValue).append("</p>");
return builder.toString();
}
private boolean validateExistingMethods(@NotNull PsiField psiField, @NotNull ProblemBuilder builder) {
boolean result = true;
final PsiClass psiClass = psiField.getContainingClass();
if (null != psiClass) {
final Collection<PsiMethod> classMethods = PsiClassUtil.collectClassMethodsIntern(psiClass);
filterToleratedElements(classMethods);
final boolean isBoolean = PsiType.BOOLEAN.equals(psiField.getType());
final Collection<String> methodNames = getAllSetterNames(psiField, isBoolean);
for (String methodName : methodNames) {
if (PsiMethodUtil.hasSimilarMethod(classMethods, methodName, 1)) {
final String setterMethodName = getSetterName(psiField, isBoolean);
builder.addWarning("Not generated '%s'(): A method with similar name '%s' already exists", setterMethodName, methodName);
result = false;
}
}
}
return result;
}
@NotNull
public static MetadataProxy newMetadataProxy(Module module, @NotNull PsiType type) {
if (type instanceof PsiArrayType) {
return new ArrayMetadataProxy(module, (PsiArrayType) type);
} else if (type instanceof PsiPrimitiveType) {
PsiPrimitiveType primitiveType = (PsiPrimitiveType) type;
type = getBoxedTypeFromPrimitiveType(module, primitiveType);
}
if (type instanceof PsiClassType) {
SuggestionNodeType suggestionNodeType = getSuggestionNodeType(type);
if (suggestionNodeType == SuggestionNodeType.MAP) {
return new MapClassMetadataProxy((PsiClassType) type);
} else {
return new ClassMetadataProxy((PsiClassType) type);
}
}
throw new IllegalAccessError(
"Supports only PsiArrayType, PsiPrimitiveType & PsiClassType types");
}
public void testValModifiersEditing() {
PsiFile file = myFixture.configureByText("a.java", "import lombok.val;\nclass Foo { {val o = <caret>;} }");
PsiLocalVariable var = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), PsiLocalVariable.class);
assertNotNull(var);
PsiType type1 = var.getType();
assertNotNull(type1);
assertEquals("lombok.val", type1.getCanonicalText(false));
myFixture.type('1');
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
assertTrue(var.isValid());
assertNotNull(var.getModifierList());
assertTrue("val should make variable final", var.getModifierList().hasModifierProperty(PsiModifier.FINAL));
}
@NotNull
@Override
public String getDocumentationForKey(Module module, String nodeNavigationPathDotDelimited) {
/*
* <p><b>a.b.c</b> ({@link com.acme.Generic}<{@link com.acme.Class1}, {@link com.acme.Class2}>)</p>
* <p>Long description</p>
*/
StringBuilder builder =
new StringBuilder().append("<b>").append(nodeNavigationPathDotDelimited).append("</b>");
PsiType psiType = getPsiType(module);
if (psiType != null) {
String classFqn = toClassFqn(psiType);
StringBuilder linkBuilder = new StringBuilder();
createHyperlink(linkBuilder, classFqn, classFqn, false);
builder.append(" (").append(linkBuilder.toString()).append(")");
}
return builder.toString();
}
@NotNull
public Suggestion buildSuggestionForValue(FileType fileType,
List<? extends SuggestionNode> matchesRootTillLeaf, @Nullable String defaultValue,
@Nullable PsiType valueType) {
Suggestion.SuggestionBuilder builder =
Suggestion.builder().suggestionToDisplay(toString()).description(description).forValue(true)
.matchesTopFirst(matchesRootTillLeaf).numOfAncestors(matchesRootTillLeaf.size());
if (valueType != null) {
builder.shortType(shortenedType(valueType.getCanonicalText()));
builder.icon(SuggestionNodeType.ENUM.getIcon());
}
builder.representingDefaultValue(toString().equals(defaultValue));
return builder.fileType(fileType).build();
}
private List<ReferenceableBeanId> findTargets(PsiElement element, String query) {
Module module = ModuleUtilCore.findModuleForPsiElement(element);
if (module == null) {
return Collections.emptyList();
}
PsiType expectedType = getExpectedType(element);
Predicate<String> beanIdPredicate = b -> b.startsWith(query);
if (expectedType != null) {
return BeanUtils.getService().findReferenceableBeanIdsByType(module, beanIdPredicate, expectedType);
} else {
return BeanUtils.getService().findReferenceableBeanIds(module, beanIdPredicate);
}
}
protected void addAllMethodParameter(@NotNull LombokLightMethodBuilder methodBuilder, @NotNull PsiType psiFieldType, @NotNull String singularName) {
final PsiManager psiManager = methodBuilder.getManager();
final PsiType elementType = PsiTypeUtil.extractAllElementType(psiFieldType, psiManager);
final PsiType collectionType = PsiTypeUtil.createCollectionType(psiManager, CommonClassNames.JAVA_LANG_ITERABLE, elementType);
methodBuilder.withParameter(singularName, collectionType);
}
@NotNull
private String createCodeBlockText(@NotNull PsiField psiField, @NotNull PsiClass psiClass, PsiType returnType, boolean isStatic, PsiParameter methodParameter) {
final String blockText;
final String thisOrClass = isStatic ? psiClass.getName() : "this";
blockText = String.format("%s.%s = %s; ", thisOrClass, psiField.getName(), methodParameter.getName());
String codeBlockText = blockText;
if (!isStatic && !PsiType.VOID.equals(returnType)) {
codeBlockText += "return this;";
}
return codeBlockText;
}
protected void addAllMethodParameter(@NotNull LombokLightMethodBuilder methodBuilder, @NotNull PsiType psiFieldType, @NotNull String singularName) {
final PsiManager psiManager = methodBuilder.getManager();
final PsiType rowKeyType = PsiTypeUtil.extractAllElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 0);
final PsiType columnKeyType = PsiTypeUtil.extractAllElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 1);
final PsiType valueType = PsiTypeUtil.extractAllElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 2);
final PsiType collectionType = PsiTypeUtil.createCollectionType(psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, rowKeyType, columnKeyType, valueType);
methodBuilder.withParameter(singularName, collectionType);
}
/**
* Resolves generics on the given type and returns them (if any) or null if there are none
*/
public static List<PsiType> getResolvedGenerics(PsiType type) {
List<PsiType> psiTypes = null;
if (type instanceof PsiClassType) {
PsiClassType pct = (PsiClassType) type;
psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());
}
return psiTypes;
}
private static PsiMethod findMethod(PsiClass configPropertiesType, String setterName, PsiType fieldType) {
PsiMethod[] methods = configPropertiesType.findMethodsByName(setterName, true);
for(PsiMethod method : methods) {
if (method.getParameterList().getParametersCount() == 1 && method.getParameterList().getParameters()[0].getType().equals(fieldType)) {
return method;
}
}
return null;
}
public static String getResolvedResultTypeName(PsiMethod method) {
//return method.getReturnType().getCanonicalText();
PsiType type = method.getReturnType();
while (type instanceof PsiArrayType) {
type = ((PsiArrayType)type).getComponentType();
}
return type.getCanonicalText();
}
/**
* Resolves generics on the given type and returns them (if any) or null if there are none
*
* @param type
* @return
*/
public static List<PsiType> getResolvedGenerics(PsiType type) {
List<PsiType> psiTypes = null;
if (type instanceof PsiClassType) {
PsiClassType pct = (PsiClassType) type;
psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());
}
return psiTypes;
}
private static TypeVariableName toTypeVariableName(PsiTypeParameter psiTypeParameter) {
String typeName = psiTypeParameter.getName();
TypeName[] typeBounds =
Arrays.stream(psiTypeParameter.getBounds())
.filter(PsiType.class::isInstance)
.map(bound -> PsiTypeUtils.getTypeName((PsiType) bound))
.toArray(TypeName[]::new);
return TypeVariableName.get(typeName, typeBounds);
}
static EventDeclarationModel getEventDeclarationModel(
PsiClassObjectAccessExpression psiExpression) {
PsiType valueType = psiExpression.getOperand().getType();
PsiClass valueClass = PsiTypesUtil.getPsiClass(valueType);
return new EventDeclarationModel(
PsiTypeUtils.guessClassName(valueType.getCanonicalText()),
getReturnType(valueClass),
getFields(valueClass),
psiExpression);
}
public static PsiClass checkForLazyOrProvider(PsiParameter psiParameter) {
PsiClass wrapperClass = PsiConsultantImpl.getClass(psiParameter);
PsiType psiParameterType = psiParameter.getType();
if (!(psiParameterType instanceof PsiClassType)) {
return wrapperClass;
}
return getPsiClass(wrapperClass, psiParameterType);
}
protected void addOneMethodParameter(@NotNull LombokLightMethodBuilder methodBuilder, @NotNull PsiType psiFieldType, @NotNull String singularName) {
final PsiManager psiManager = methodBuilder.getManager();
final PsiType keyType = getKeyType(psiManager, psiFieldType);
final PsiType valueType = getValueType(psiManager, psiFieldType);
methodBuilder.withParameter(singularName + KEY, keyType);
methodBuilder.withParameter(singularName + VALUE, valueType);
}
private void visitPsiReturnStatement(final PsiReturnStatement element) {
PsiExpression returnValue = element.getReturnValue();
if (returnValue != null) {
PsiType returnType = returnValue.getType();
if (returnType != null) {
String qualifiedName = removeSpecialSymbols(returnType.getCanonicalText());
addInMap(qualifiedName, emptySet);
}
}
}
public LombokLightFieldBuilder(@NotNull PsiManager manager, @NotNull String name, @NotNull PsiType type) {
super(manager, name, type);
myName = name;
myNameIdentifier = new LombokLightIdentifier(manager, name);
myModifierList = new LombokLightModifierList(manager, JavaLanguage.INSTANCE, Collections.emptyList());
setBaseIcon(LombokIcons.FIELD_ICON);
}
public SqliteMagicLightParameter(@NotNull String name, @NotNull PsiType type, PsiElement declarationScope, Language language) {
super(name, type, declarationScope, language);
myName = name;
PsiManager manager = declarationScope.getManager();
myNameIdentifier = new SqliteMagicLightIdentifier(manager, name);
ReflectionUtil.setFinalFieldPerReflection(LightVariableBuilder.class, this, LightModifierList.class,
new SqliteMagicLightModifierList(manager, language));
}
@Nullable
public static Map<PsiTypeParameter, PsiType> getTypeParameters(PsiType type) {
if (type instanceof PsiArrayType) {
return getTypeParameters(((PsiArrayType) type).getComponentType());
} else if (type instanceof PsiPrimitiveType) {
return null;
} else if (type instanceof PsiClassType) {
PsiClassType.ClassResolveResult resolveResult =
PsiClassType.class.cast(type).resolveGenerics();
if (resolveResult.isValidResult()) {
return resolveResult.getSubstitutor().getSubstitutionMap();
}
}
return null;
}