IDEA-66564 (parse indeterminate FP literals in compiled annotations); cleanup

This commit is contained in:
Roman Shevchenko
2011-03-18 20:03:23 +01:00
parent e58a11a3b9
commit e475bc1b20
13 changed files with 308 additions and 440 deletions
@@ -1,111 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.compiled;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.java.parser.DeclarationParser;
import com.intellij.lang.java.parser.JavaParserUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiElementFactoryImpl;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.DummyHolderFactory;
import com.intellij.psi.impl.source.JavaDummyElement;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import org.jetbrains.annotations.NotNull;
/**
* @author ven
*/
public class ClsAnnotationsUtil {
private static final Logger LOG = Logger.getInstance("com.intellij.psi.impl.compiled.ClsAnnotationsUtil");
private static final JavaParserUtil.ParserWrapper ANNOTATION_VALUE = new JavaParserUtil.ParserWrapper() {
@Override
public void parse(final PsiBuilder builder) {
DeclarationParser.parseAnnotationValue(builder);
}
};
private ClsAnnotationsUtil() { }
@NotNull
public static PsiAnnotationMemberValue getMemberValue(PsiElement element, ClsElementImpl parent) {
if (element instanceof PsiLiteralExpression) {
PsiLiteralExpression expr = (PsiLiteralExpression)element;
return new ClsLiteralExpressionImpl(parent, element.getText(), expr.getType(), expr.getValue());
}
else if (element instanceof PsiPrefixExpression) {
PsiExpression operand = ((PsiPrefixExpression) element).getOperand();
ClsLiteralExpressionImpl literal = (ClsLiteralExpressionImpl) getMemberValue(operand, null);
ClsPrefixExpressionImpl prefixExpression = new ClsPrefixExpressionImpl(parent, literal);
literal.setParent(prefixExpression);
return prefixExpression;
}
else if (element instanceof PsiClassObjectAccessExpression) {
PsiClassObjectAccessExpression expr = (PsiClassObjectAccessExpression)element;
return new ClsClassObjectAccessExpressionImpl(expr.getOperand().getType().getCanonicalText(), parent);
}
else if (element instanceof PsiArrayInitializerMemberValue) {
PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue)element).getInitializers();
PsiAnnotationMemberValue[] clsInitializers = new PsiAnnotationMemberValue[initializers.length];
ClsArrayInitializerMemberValueImpl arrayValue = new ClsArrayInitializerMemberValueImpl(parent, clsInitializers);
for (int i = 0; i < initializers.length; i++) {
clsInitializers[i] = getMemberValue(initializers[i], arrayValue);
}
return arrayValue;
}
else if (element instanceof PsiAnnotation) {
final PsiAnnotation psiAnnotation = (PsiAnnotation)element;
final PsiJavaCodeReferenceElement referenceElement = psiAnnotation.getNameReferenceElement();
assert referenceElement != null : psiAnnotation;
final String canonicalText = referenceElement.getCanonicalText();
return new ClsAnnotationValueImpl(parent) {
protected ClsJavaCodeReferenceElementImpl createReference() {
return new ClsJavaCodeReferenceElementImpl(this, canonicalText);
}
protected ClsAnnotationParameterListImpl createParameterList() {
PsiNameValuePair[] psiAttributes = psiAnnotation.getParameterList().getAttributes();
return new ClsAnnotationParameterListImpl(this, psiAttributes);
}
public PsiAnnotationOwner getOwner() {
return (PsiAnnotationOwner)getParent();
}
};
}
else if (element instanceof PsiReferenceExpression) {
return new ClsReferenceExpressionImpl(parent, (PsiReferenceExpression)element);
}
else {
LOG.error("Unexpected source element for annotation member value: " + element);
return null;
}
}
@NotNull
public static PsiAnnotationMemberValue createMemberValueFromText(final String text, final PsiManager manager, final ClsElementImpl parent) {
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiJavaFile context = ((PsiElementFactoryImpl)factory).getDummyJavaFile(); // kind of hack - we need to resolve classes from java.lang
final DummyHolder holder = DummyHolderFactory.createHolder(manager, new JavaDummyElement(text, ANNOTATION_VALUE, false), context);
final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode());
if (!(element instanceof PsiAnnotationMemberValue)) {
LOG.error("Could not parse initializer:'" + text + "'");
return null;
}
return getMemberValue(element, parent);
}
}
@@ -239,7 +239,7 @@ public abstract class ClsElementImpl extends PsiElementBase implements PsiCompil
}
if (type != null) {
LOG.assertTrue(element.getElementType() == type);
LOG.assertTrue(element.getElementType() == type, element.getElementType() + " != " + type);
}
element.putUserData(COMPILED_ELEMENT, this);
@@ -15,15 +15,12 @@
*/
package com.intellij.psi.impl.compiled;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.ElementType;
import com.intellij.psi.impl.source.tree.TreeElement;
import org.jetbrains.annotations.NotNull;
public class ClsLiteralExpressionImpl extends ClsElementImpl implements PsiLiteralExpression {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsLiteralExpressionImpl");
private ClsElementImpl myParent;
private final String myText;
private final PsiType myType;
@@ -211,7 +211,7 @@ public class ClsMethodImpl extends ClsRepositoryPsiElement<PsiMethodStub> implem
final String text = getStub().getDefaultValueText();
if (StringUtil.isEmpty(text)) return null;
myDefaultValue = ClsAnnotationsUtil.createMemberValueFromText(text, getManager(), this);
myDefaultValue = ClsParsingUtil.createMemberValueFromText(text, getManager(), this);
}
return myDefaultValue;
}
@@ -34,7 +34,7 @@ public class ClsNameValuePairImpl extends ClsElementImpl implements PsiNameValue
public ClsNameValuePairImpl(ClsElementImpl parent, String name, PsiAnnotationMemberValue value) {
myParent = parent;
myNameIdentifier = new ClsIdentifierImpl(this, name);
myMemberValue = ClsAnnotationsUtil.getMemberValue(value, this);
myMemberValue = ClsParsingUtil.getMemberValue(value, this);
}
public void appendMirrorText(final int indentLevel, final StringBuffer buffer) {
@@ -15,10 +15,23 @@
*/
package com.intellij.psi.impl.compiled;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.java.parser.DeclarationParser;
import com.intellij.lang.java.parser.JavaParserUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.CharFilter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiElementFactoryImpl;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.DummyHolderFactory;
import com.intellij.psi.impl.source.JavaDummyElement;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author ven
@@ -26,11 +39,35 @@ import com.intellij.util.IncorrectOperationException;
public class ClsParsingUtil {
private static final Logger LOG = Logger.getInstance("com.intellij.psi.impl.compiled.ClsParsingUtil");
private static final JavaParserUtil.ParserWrapper ANNOTATION_VALUE = new JavaParserUtil.ParserWrapper() {
@Override
public void parse(final PsiBuilder builder) {
DeclarationParser.parseAnnotationValue(builder);
}
};
private static final Map<String, String> INDETERMINATE_MAP;
static {
INDETERMINATE_MAP = new HashMap<String, String>();
INDETERMINATE_MAP.put("-1.0/0.0", "NEGATIVE_INFINITY");
INDETERMINATE_MAP.put("0.0/0.0", "NaN");
INDETERMINATE_MAP.put("1.0/0.0", "POSITIVE_INFINITY");
}
private static final CharFilter INDETERMINATE_FILTER = new CharFilter() {
private static final String UNWANTED = " fFdD";
@Override
public boolean accept(final char ch) {
return UNWANTED.indexOf(ch) == -1;
}
};
private ClsParsingUtil() { }
public static PsiExpression createExpressionFromText(final String exprText, final PsiManager manager, final ClsElementImpl parent) {
final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(manager.getProject()).getParserFacade();
final PsiJavaFile dummyJavaFile = ((PsiElementFactoryImpl)parserFacade).getDummyJavaFile(); // kind of hack - we need to resolve classes from java.lang
final PsiJavaFile dummyJavaFile = ((PsiElementFactoryImpl)parserFacade).getDummyJavaFile(); // to resolve classes from java.lang
final PsiExpression expr;
try {
expr = parserFacade.createExpressionFromText(exprText, dummyJavaFile);
@@ -40,34 +77,104 @@ public class ClsParsingUtil {
return null;
}
if (expr instanceof PsiLiteralExpression) {
PsiLiteralExpression literal = (PsiLiteralExpression)expr;
return new ClsLiteralExpressionImpl(parent, exprText, literal.getType(), literal.getValue());
}
else if (expr instanceof PsiPrefixExpression) {
PsiLiteralExpression operand = (PsiLiteralExpression)((PsiPrefixExpression)expr).getOperand();
if (operand != null) {
ClsLiteralExpressionImpl literalExpression =
new ClsLiteralExpressionImpl(null, operand.getText(), operand.getType(), operand.getValue());
ClsPrefixExpressionImpl prefixExpression = new ClsPrefixExpressionImpl(parent, literalExpression);
literalExpression.setParent(prefixExpression);
return prefixExpression;
}
}
else if (expr instanceof PsiReferenceExpression) {
PsiReferenceExpression patternExpr = (PsiReferenceExpression)expr;
return new ClsReferenceExpressionImpl(parent, patternExpr);
}
else {
final PsiConstantEvaluationHelper constantEvaluationHelper =
JavaPsiFacade.getInstance(manager.getProject()).getConstantEvaluationHelper();
Object value = constantEvaluationHelper.computeConstantExpression(expr);
if (value != null) {
return new ClsLiteralExpressionImpl(parent, exprText, expr.getType(), value); //it seems ok to make literal expression with non-literal text
}
return psiToClsExpression(expr, parent);
}
@NotNull
public static PsiAnnotationMemberValue createMemberValueFromText(final String text, final PsiManager manager, final ClsElementImpl parent) {
final String exprText = mapIndeterminate(text);
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiJavaFile context = ((PsiElementFactoryImpl)factory).getDummyJavaFile(); // to resolve classes from java.lang
final DummyHolder holder = DummyHolderFactory.createHolder(manager, new JavaDummyElement(exprText, ANNOTATION_VALUE, false), context);
final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode());
if (!(element instanceof PsiAnnotationMemberValue)) {
LOG.error("Could not parse initializer:'" + exprText + "'");
return null;
}
LOG.error(expr);
return null;
return getMemberValue(element, parent);
}
private static String mapIndeterminate(final String original) {
final int divPos = original.indexOf('/');
if (divPos > 0) {
final String symbol = INDETERMINATE_MAP.get(StringUtil.strip(original, INDETERMINATE_FILTER));
if (symbol != null) {
final int fPos = original.toLowerCase().indexOf('f');
final String type = (0 < fPos && fPos < divPos) ? CommonClassNames.JAVA_LANG_FLOAT : CommonClassNames.JAVA_LANG_DOUBLE;
return type + "." + symbol;
}
}
return original;
}
@NotNull
public static PsiAnnotationMemberValue getMemberValue(final PsiElement element, final ClsElementImpl parent) {
if (element instanceof PsiExpression) {
return psiToClsExpression((PsiExpression)element, parent);
}
else if (element instanceof PsiArrayInitializerMemberValue) {
PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue)element).getInitializers();
PsiAnnotationMemberValue[] clsInitializers = new PsiAnnotationMemberValue[initializers.length];
ClsArrayInitializerMemberValueImpl arrayValue = new ClsArrayInitializerMemberValueImpl(parent, clsInitializers);
for (int i = 0; i < initializers.length; i++) {
clsInitializers[i] = getMemberValue(initializers[i], arrayValue);
}
return arrayValue;
}
else if (element instanceof PsiAnnotation) {
final PsiAnnotation psiAnnotation = (PsiAnnotation)element;
final PsiJavaCodeReferenceElement referenceElement = psiAnnotation.getNameReferenceElement();
assert referenceElement != null : psiAnnotation;
final String canonicalText = referenceElement.getCanonicalText();
return new ClsAnnotationValueImpl(parent) {
protected ClsJavaCodeReferenceElementImpl createReference() {
return new ClsJavaCodeReferenceElementImpl(this, canonicalText);
}
protected ClsAnnotationParameterListImpl createParameterList() {
PsiNameValuePair[] psiAttributes = psiAnnotation.getParameterList().getAttributes();
return new ClsAnnotationParameterListImpl(this, psiAttributes);
}
public PsiAnnotationOwner getOwner() {
return (PsiAnnotationOwner)getParent();
}
};
}
else {
LOG.error("Unexpected source element for annotation member value: " + element);
return null;
}
}
@NotNull
private static PsiExpression psiToClsExpression(final PsiExpression expr, final ClsElementImpl parent) {
if (expr instanceof PsiLiteralExpression) {
return new ClsLiteralExpressionImpl(parent, expr.getText(), expr.getType(), ((PsiLiteralExpression)expr).getValue());
}
else if (expr instanceof PsiPrefixExpression) {
final PsiExpression operand = ((PsiPrefixExpression) expr).getOperand();
final ClsLiteralExpressionImpl literal = (ClsLiteralExpressionImpl) psiToClsExpression(operand, null);
final ClsPrefixExpressionImpl prefixExpression = new ClsPrefixExpressionImpl(parent, literal);
literal.setParent(prefixExpression);
return prefixExpression;
}
else if (expr instanceof PsiClassObjectAccessExpression) {
final String canonicalClassText = ((PsiClassObjectAccessExpression)expr).getOperand().getType().getCanonicalText();
return new ClsClassObjectAccessExpressionImpl(canonicalClassText, parent);
}
else if (expr instanceof PsiReferenceExpression) {
return new ClsReferenceExpressionImpl(parent, (PsiReferenceExpression)expr);
}
else {
final PsiConstantEvaluationHelper evaluator = JavaPsiFacade.getInstance(expr.getProject()).getConstantEvaluationHelper();
final Object value = evaluator.computeConstantExpression(expr);
if (value != null) {
return new ClsLiteralExpressionImpl(parent, expr.getText(), expr.getType(), value);
}
LOG.error("Unable to compute expression value: " + expr);
return null;
}
}
}
@@ -15,7 +15,6 @@
*/
package com.intellij.psi.impl.compiled;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.TreeElement;
@@ -23,8 +22,6 @@ import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public class ClsPrefixExpressionImpl extends ClsElementImpl implements PsiPrefixExpression {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsPrefixExpressionImpl");
private final ClsElementImpl myParent;
private final PsiExpression myOperand;
@@ -1,113 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4" relativePaths="false">
<component name="AntConfiguration">
<defaultAnt bundledAnt="true" />
</component>
<component name="CodeStyleManager">
<option name="USE_DEFAULT_CODE_STYLE_SCHEME" value="true" />
<option name="CODE_STYLE_SCHEME" value="" />
</component>
<component name="CodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS" />
<option name="USE_PER_PROJECT_SETTINGS" value="false" />
</component>
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
<option name="CLEAR_OUTPUT_DIRECTORY" value="false" />
<resourceExtensions>
<entry name=".+\.(properties|xml|html)" />
<entry name=".+\.(gif|png|jpeg)" />
</resourceExtensions>
<wildcardResourcePatterns>
<entry name="?*.properties" />
<entry name="?*.xml" />
<entry name="?*.html" />
<entry name="?*.gif" />
<entry name="?*.png" />
<entry name="?*.jpeg" />
</wildcardResourcePatterns>
</component>
<component name="DataSourceManagerImpl" />
<component name="DependencyValidationManager">
<option name="UI_FLATTEN_PACKAGES" value="true" />
<option name="UI_SHOW_FILES" value="false" />
<option name="UI_SHOW_MODULES" value="true" />
<option name="UI_FILTER_LEGALS" value="false" />
</component>
<component name="EjbActionsConfiguration">
<option name="NEW_MESSAGE_BEAN_LAST_PACKAGE" value="" />
<option name="NEW_ENTITY_BEAN_LAST_PACKAGE" value="" />
<option name="NEW_SESSION_BEAN_LAST_PACKAGE" value="" />
</component>
<component name="EjbManager" enabled="false" />
<component name="EntryPointsManager">
<entry_points />
</component>
<component name="ExportToHTMLSettings">
<option name="PRINT_LINE_NUMBERS" value="false" />
<option name="OPEN_IN_BROWSER" value="false" />
<option name="OUTPUT_DIRECTORY" />
</component>
<component name="GUI Designer component loader factory" />
<component name="JUnitProjectSettings">
<option name="TEST_RUNNER" value="UI" />
</component>
<component name="JavacSettings">
<option name="DEBUGGING_INFO" value="true" />
<option name="GENERATE_NO_WARNINGS" value="false" />
<option name="DEPRECATION" value="true" />
<option name="ADDITIONAL_OPTIONS_STRING" value="-source 1.5" />
<option name="MAXIMUM_HEAP_SIZE" value="128" />
<option name="USE_GENERICS_COMPILER" value="false" />
</component>
<component name="JavadocGenerationManager">
<option name="OUTPUT_DIRECTORY" />
<option name="OPTION_SCOPE" value="protected" />
<option name="OPTION_HIERARCHY" value="false" />
<option name="OPTION_NAVIGATOR" value="false" />
<option name="OPTION_INDEX" value="false" />
<option name="OPTION_SEPARATE_INDEX" value="false" />
<option name="OPTION_DOCUMENT_TAG_USE" value="false" />
<option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
<option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
<option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="false" />
<option name="OPTION_DEPRECATED_LIST" value="false" />
<option name="OTHER_OPTIONS" />
<option name="HEAP_SIZE" />
<option name="OPEN_IN_BROWSER" value="false" />
</component>
<component name="JikesSettings">
<option name="JIKES_PATH" value="" />
<option name="DEBUGGING_INFO" value="true" />
<option name="DEPRECATION" value="true" />
<option name="GENERATE_NO_WARNINGS" value="false" />
<option name="IS_EMACS_ERRORS_MODE" value="true" />
<option name="ADDITIONAL_OPTIONS_STRING" value="" />
</component>
<component name="Palette" />
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/cls.iml" filepath="$PROJECT_DIR$/cls.iml" />
</modules>
</component>
<component name="ProjectRootManager" version="2" assert-keyword="false" jdk-15="false" project-jdk-name="java version &quot;1.5.0-beta&quot;" />
<component name="RmicSettings">
<option name="IS_EANABLED" value="false" />
<option name="DEBUGGING_INFO" value="true" />
<option name="GENERATE_NO_WARNINGS" value="false" />
<option name="GENERATE_IIOP_STUBS" value="false" />
<option name="ADDITIONAL_OPTIONS_STRING" value="" />
</component>
<component name="WebManager">
<option enabled="false" />
</component>
<component name="WebReferencesManager" />
<component name="WebRootContainer" />
<component name="libraryTable" />
<component name="org.tmatesoft.tmate.projectComponent" />
<component name="uidesigner-configuration">
<option name="INSTRUMENT_CLASSES" value="true" />
<option name="COPY_FORMS_RUNTIME_TO_OUTPUT" value="true" />
</component>
</project>
@@ -1,109 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="3" relativePaths="false">
<component name="ProjectRootManager" version="2">
<jdk name="java version &quot;1.4.1&quot;" />
<projectPath>
<root type="composite">
<root type="simple" url="file://$PROJECT_DIR$" />
</root>
</projectPath>
<sourcePath>
<root type="composite">
<root type="jdk" rootType="sourcePath" name="java version &quot;1.4.1&quot;" />
<root type="simple" url="file://$PROJECT_DIR$/src" />
</root>
</sourcePath>
<classPath>
<root type="composite">
<root type="jdk" rootType="classPath" name="java version &quot;1.4.1&quot;" />
<root type="output" />
</root>
</classPath>
<excludePath>
<root type="composite">
<root type="excludedOutput" />
</root>
</excludePath>
<javadocPath>
<root type="composite">
<root type="jdk" rootType="javadocPath" name="java version &quot;1.4.1&quot;" />
</root>
</javadocPath>
<assert_keyword enabled="no" />
<exclude_output enabled="yes" />
</component>
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
<option name="SYNCHRONIZE_OUTPUT_DIRECTORY" value="false" />
<option name="DEFAULT_OUTPUT_PATH" value="$PROJECT_DIR$" />
<option name="OUTPUT_MODE" value="single" />
<resourceExtensions>
<entry name=".+\.(properties|xml|html)" />
<entry name=".+\.(gif|png|jpeg)" />
</resourceExtensions>
</component>
<component name="JavacSettings">
<option name="DEBUGGING_INFO" value="true" />
<option name="GENERATE_NO_WARNINGS" value="false" />
<option name="DEPRECATION" value="true" />
<option name="ADDITIONAL_OPTIONS_STRING" value="" />
<option name="MAXIMUM_HEAP_SIZE" value="128" />
</component>
<component name="JikesSettings">
<option name="JIKES_PATH" value="" />
<option name="DEBUGGING_INFO" value="true" />
<option name="DEPRECATION" value="true" />
<option name="GENERATE_NO_WARNINGS" value="false" />
<option name="GENERATE_MAKE_FILE_DEPENDENCIES" value="false" />
<option name="DO_FULL_DEPENDENCE_CHECK" value="false" />
<option name="IS_EMACS_ERRORS_MODE" value="true" />
<option name="ADDITIONAL_OPTIONS_STRING" value="" />
</component>
<component name="AntConfiguration">
<option name="IS_AUTOSCROLL_TO_SOURCE" value="false" />
<option name="FILTER_TARGETS" value="false" />
</component>
<component name="JavadocGenerationManager">
<option name="OUTPUT_DIRECTORY" />
<option name="OPTION_SCOPE" value="protected" />
<option name="OPTION_HIERARCHY" value="false" />
<option name="OPTION_NAVIGATOR" value="false" />
<option name="OPTION_INDEX" value="false" />
<option name="OPTION_SEPARATE_INDEX" value="false" />
<option name="OPTION_DOCUMENT_TAG_USE" value="false" />
<option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
<option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
<option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="false" />
<option name="OPTION_DEPRECATED_LIST" value="false" />
<option name="OTHER_OPTIONS" />
<option name="HEAP_SIZE" />
<option name="OPEN_IN_BROWSER" value="false" />
</component>
<component name="WebManager">
<option enabled="false" />
</component>
<component name="WebRootContainer" />
<component name="EjbManager" enabled="false" />
<component name="JUnitProjectSettings">
<option name="TEST_RUNNER" value="UI" />
</component>
<component name="EntryPointsManager">
<entry_points />
</component>
<component name="EjbActionsConfiguration">
<option name="NEW_MESSAGE_BEAN_LAST_PACKAGE" value="" />
<option name="NEW_ENTITY_BEAN_LAST_PACKAGE" value="" />
<option name="NEW_SESSION_BEAN_LAST_PACKAGE" value="" />
</component>
<component name="CodeStyleManager">
<option name="USE_DEFAULT_CODE_STYLE_SCHEME" value="true" />
<option name="CODE_STYLE_SCHEME" value="" />
</component>
<component name="ExportToHTMLSettings">
<option name="PRINT_LINE_NUMBERS" value="false" />
<option name="OPEN_IN_BROWSER" value="false" />
<option name="OUTPUT_DIRECTORY" />
</component>
<component name="WebReferencesManager" />
</project>
@@ -0,0 +1,11 @@
package pack;
public @interface Annotation2 {
float f1() default Float.NEGATIVE_INFINITY;
float f2() default Float.NaN;
float f3() default Float.POSITIVE_INFINITY;
double d1() default Double.NEGATIVE_INFINITY;
double d2() default Double.NaN;
double d3() default Double.POSITIVE_INFINITY;
}
@@ -1,6 +1,3 @@
/*
* @author max
*/
package com.intellij.psi;
import com.intellij.JavaTestUtil;
@@ -15,11 +12,14 @@ import com.intellij.psi.stubs.StubBase;
import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.util.cls.ClsFormatException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author max
*/
public class ClsBuilderTest extends LightIdeaTestCase {
public void testUtilList() throws Exception {
doTest("java/util/List.class");
@@ -67,41 +67,46 @@ public class ClsBuilderTest extends LightIdeaTestCase {
doTest(clsFile, getTestName(false) + ".txt");
}
private void doTest(final String classname) throws IOException, ClsFormatException {
VirtualFile vFile = findFile(classname);
private void doTest(final String className) throws IOException, ClsFormatException {
VirtualFile vFile = findFile(className);
doTest(vFile, getTestName(false)+".txt");
}
private static void doTest(VirtualFile vFile, String goldFile) throws ClsFormatException, IOException {
final PsiFileStub stub = ClsStubBuilder.build(vFile, vFile.contentsToByteArray());
assert stub != null : vFile;
final String butWas = ((StubBase)stub).printTree();
final String goldFilePath = JavaTestUtil.getJavaTestDataPath() + "/psi/cls/stubBuilder/" + goldFile;
String expected = "";
try {
expected = FileUtil.loadTextAndClose(new FileReader(goldFilePath));
expected = new String(FileUtil.loadFileText(new File(goldFilePath)));
expected = StringUtil.convertLineSeparators(expected);
}
catch (FileNotFoundException e) {
System.out.println("No expected data found at:" + goldFilePath);
System.out.println("Creating one.");
System.out.println("No expected data found at: " + goldFilePath + ", creating one.");
final FileWriter fileWriter = new FileWriter(goldFilePath);
fileWriter.write(butWas);
fileWriter.close();
fail("No test data found. Created one");
try {
fileWriter.write(butWas);
fileWriter.close();
}
finally {
fileWriter.close();
fail("No test data found. Created one");
}
}
assertEquals(expected, butWas);
}
private VirtualFile findFile(final String classname) {
private VirtualFile findFile(final String className) {
final VirtualFile[] roots = getProjectJDK().getRootProvider().getFiles(OrderRootType.CLASSES);
for (VirtualFile root : roots) {
VirtualFile vFile = root.findFileByRelativePath(classname);
VirtualFile vFile = root.findFileByRelativePath(className);
if (vFile != null) return vFile;
}
fail("Cannot file classfile for: " + classname);
fail("Cannot file class file for: " + className);
return null;
}
}
@@ -11,6 +11,7 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.psi.impl.java.stubs.PsiMethodStub;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtil;
import com.intellij.testFramework.PlatformTestCase;
@@ -22,6 +23,7 @@ import java.io.File;
@PlatformTestCase.WrapInCommand
public class ClsRepositoryUseTest extends PsiTestCase{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.ClsRepositoryUseTest");
private static final String TEST_ROOT = PathManagerEx.getTestDataPath() + "/psi/repositoryUse/cls";
private GlobalSearchScope RESOLVE_SCOPE;
@@ -33,13 +35,13 @@ public class ClsRepositoryUseTest extends PsiTestCase{
new Runnable() {
@Override
public void run() {
try{
try {
VirtualFile vDir = getRootFile();
PsiTestUtil.removeAllRoots(myModule, JavaSdkImpl.getMockJdk17());
addLibraryToRoots(vDir, OrderRootType.CLASSES);
// PsiTestUtil.addSourceContentToRoots(myProject, vDir);
}
catch(Exception e){
catch (Exception e) {
LOG.error(e);
}
}
@@ -59,13 +61,14 @@ public class ClsRepositoryUseTest extends PsiTestCase{
final File classes = createTempDir("classes");
final File com = new File(classes, "com");
//noinspection ResultOfMethodCallIgnored
com.mkdir();
File dataPath = new File(PathManagerEx.getTestDataPath() + "/psi/cls");
final File target = new File(com, "TestClass.class");
FileUtil.copy(new File(dataPath, "1/TestClass.class"), target);
//noinspection ResultOfMethodCallIgnored
target.setLastModified(System.currentTimeMillis());
ApplicationManager.getApplication().runWriteAction(
@@ -85,6 +88,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
);
PsiClass psiClass = myJavaFacade.findClass("com.TestClass", GlobalSearchScope.allScope(myProject));
assert psiClass != null;
PsiJavaFile psiFile = (PsiJavaFile)psiClass.getContainingFile();
final VirtualFile vFile = psiFile.getVirtualFile();
@@ -104,8 +108,10 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertEquals("method1", psiClass.getMethods()[1].getName());
FileUtil.copy(new File(dataPath, "2/TestClass.class"), target);
//noinspection ResultOfMethodCallIgnored
target.setLastModified(System.currentTimeMillis() + 5000);
assert vFile != null;
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
@Override
@@ -139,18 +145,22 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertEquals("method2", psiClass.getMethods()[1].getName());
}
private static VirtualFile getRootFile() {
VirtualFile vDir = LocalFileSystem.getInstance().findFileByPath(TEST_ROOT.replace(File.separatorChar, '/'));
final String path = TEST_ROOT.replace(File.separatorChar, '/');
final VirtualFile vDir = LocalFileSystem.getInstance().findFileByPath(path);
assert vDir != null : path;
return vDir;
}
public void testGetClasses(){
final VirtualFile rootFile = getRootFile();
VirtualFile child = rootFile.findChild("pack").findChild("MyClass.class");
final VirtualFile pack = rootFile.findChild("pack");
assert pack != null;
VirtualFile child = pack.findChild("MyClass.class");
assertNotNull(child);
PsiJavaFile file = (PsiJavaFile)myPsiManager.findFile(child);
checkValid(file);
assert file != null;
PsiClass[] classes = file.getClasses();
assertTrue(classes.length == 1);
PsiClass aClass = classes[0];
@@ -160,9 +170,12 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetClassName(){
final VirtualFile rootFile = getRootFile();
VirtualFile child = rootFile.findChild("pack").findChild("MyClass.class");
final VirtualFile pack = rootFile.findChild("pack");
assert pack != null;
VirtualFile child = pack.findChild("MyClass.class");
assertNotNull(child);
PsiJavaFile file = (PsiJavaFile)myPsiManager.findFile(child);
assert file != null;
PsiClass[] classes = file.getClasses();
assertTrue(classes.length == 1);
@@ -173,9 +186,12 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetClassQName(){
final VirtualFile rootFile = getRootFile();
VirtualFile child = rootFile.findChild("pack").findChild("MyClass.class");
final VirtualFile pack = rootFile.findChild("pack");
assert pack != null;
VirtualFile child = pack.findChild("MyClass.class");
assertNotNull(child);
PsiJavaFile file = (PsiJavaFile)myPsiManager.findFile(child);
assert file != null;
PsiClass[] classes = file.getClasses();
assertTrue(classes.length == 1);
@@ -186,9 +202,12 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetContainingFile(){
final VirtualFile rootFile = getRootFile();
VirtualFile child = rootFile.findChild("pack").findChild("MyClass.class");
final VirtualFile pack = rootFile.findChild("pack");
assert pack != null;
VirtualFile child = pack.findChild("MyClass.class");
assertNotNull(child);
PsiJavaFile file = (PsiJavaFile)myPsiManager.findFile(child);
assert file != null;
PsiClass[] classes = file.getClasses();
assertTrue(classes.length == 1);
@@ -209,6 +228,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testIsInterface(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
assertTrue(!aClass.isInterface());
}
@@ -219,6 +239,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testPackageName(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
String packageName = ((PsiJavaFile)aClass.getContainingFile()).getPackageName();
assertEquals("pack", packageName);
@@ -226,6 +247,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetFields(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField[] fields = aClass.getFields();
assertEquals(2, fields.length);
@@ -234,6 +256,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetMethods(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiMethod[] methods = aClass.getMethods();
assertEquals(3, methods.length);
@@ -242,6 +265,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetInnerClasses(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiClass[] inners = aClass.getInnerClasses();
assertEquals(1, inners.length);
@@ -250,14 +274,18 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testModifierList() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiModifierList modifierList = aClass.getModifierList();
assert modifierList != null : aClass;
assertTrue(modifierList.hasModifierProperty(PsiModifier.PUBLIC));
assertFalse(modifierList.hasModifierProperty(PsiModifier.STATIC));
assertEquals(modifierList.getParent(), aClass);
PsiField field = aClass.getFields()[0];
modifierList = field.getModifierList();
assert modifierList != null : field;
assertTrue(modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL));
assertEquals(modifierList.getParent(), field);
@@ -269,18 +297,21 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testGetFieldName(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
assertEquals("field1", aClass.getFields()[0].getName());
}
public void testGetMethodName(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
assertEquals("method1", aClass.getMethods()[0].getName());
}
public void testFindFieldByName(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField field = aClass.findFieldByName("field1", false);
assertNotNull(field);
@@ -288,15 +319,18 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testIsDeprecated(){
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
assertTrue(!aClass.isDeprecated());
PsiField field = aClass.findFieldByName("field1", false);
assert field != null : aClass;
assertTrue(field.isDeprecated());
}
public void testFieldType() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField field1 = aClass.getFields()[0];
@@ -312,17 +346,18 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertEquals("Object[]", type2.getPresentableText());
assertTrue(type1 instanceof PsiPrimitiveType);
assertTrue(!(type1 instanceof PsiArrayType));
assertTrue(!(type2 instanceof PsiPrimitiveType));
assertTrue(type2 instanceof PsiArrayType);
}
public void testMethodType() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiMethod method1 = aClass.getMethods()[0];
PsiTypeElement type1 = method1.getReturnTypeElement();
assert type1 != null : method1;
assertEquals(method1, type1.getParent());
assertEquals("void", type1.getText());
@@ -335,6 +370,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testIsConstructor() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiMethod method1 = aClass.getMethods()[0];
@@ -346,6 +382,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testComponentType() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField field = aClass.getFields()[1];
@@ -361,6 +398,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testTypeReference() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField field1 = aClass.getFields()[0];
@@ -377,6 +415,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testResolveTypeReference() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiType type1 = aClass.getFields()[1].getType();
@@ -388,11 +427,13 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testInitializer() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiField field1 = aClass.getFields()[0];
assertTrue(field1.hasInitializer());
PsiLiteralExpression initializer = (PsiLiteralExpression)field1.getInitializer();
assert initializer != null : field1;
assertEquals("123", initializer.getText());
assertEquals(new Integer(123), initializer.getValue());
assertEquals(PsiType.INT, initializer.getType());
@@ -404,10 +445,11 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testExtendsList() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiReferenceList list = aClass.getExtendsList();
assert list != null : aClass;
PsiClassType[] refs = list.getReferencedTypes();
assertEquals(1, refs.length);
assertEquals("ArrayList", refs[0].getPresentableText());
@@ -416,10 +458,11 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testImplementsList() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiReferenceList list = aClass.getImplementsList();
assert list != null : aClass;
PsiClassType[] refs = list.getReferencedTypes();
assertEquals(1, refs.length);
assertEquals("Cloneable", refs[0].getPresentableText());
@@ -428,6 +471,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testThrowsList() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiReferenceList list = aClass.getMethods()[0].getThrowsList();
@@ -443,21 +487,21 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testParameters() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyClass", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiParameterList list = aClass.getMethods()[0].getParameterList();
PsiParameter[] parms = list.getParameters();
assertEquals(2, parms.length);
PsiParameter[] parameters = list.getParameters();
assertEquals(2, parameters.length);
PsiType type1 = parms[0].getType();
PsiType type1 = parameters[0].getType();
assertEquals("int[]", type1.getPresentableText());
assertTrue(type1.equalsToText("int[]"));
assertTrue(type1 instanceof PsiArrayType);
assertFalse(type1 instanceof PsiPrimitiveType);
assertNull(PsiUtil.resolveClassInType(type1));
PsiType type2 = parms[1].getType();
PsiType type2 = parameters[1].getType();
assertEquals("Object", type2.getPresentableText());
assertTrue(type2.equalsToText("java.lang.Object"));
assertFalse(type2 instanceof PsiArrayType);
@@ -467,26 +511,33 @@ public class ClsRepositoryUseTest extends PsiTestCase{
PsiClass objectClass = myJavaFacade.findClass("java.lang.Object", RESOLVE_SCOPE);
assertEquals(objectClass, target2);
parms[0].getModifierList();
parameters[0].getModifierList();
}
public void testGenericClass() throws Exception {
disableJdk();
PsiClass map = myJavaFacade.findClass("java.util.HashMap", RESOLVE_SCOPE);
assert map != null;
PsiMethod entrySet = map.findMethodsByName("entrySet", false)[0];
PsiClassType ret = (PsiClassType) entrySet.getReturnType();
assert ret != null : entrySet;
final PsiClassType.ClassResolveResult setResolveResult = ret.resolveGenerics();
assertEquals("java.util.Set", setResolveResult.getElement().getQualifiedName());
final PsiTypeParameter typeParameter = setResolveResult.getElement().getTypeParameters()[0];
final PsiClass setResolveResultElement = setResolveResult.getElement();
assert setResolveResultElement != null : setResolveResult;
assertEquals("java.util.Set", setResolveResultElement.getQualifiedName());
final PsiTypeParameter typeParameter = setResolveResultElement.getTypeParameters()[0];
final PsiType substResult = setResolveResult.getSubstitutor().substitute(typeParameter);
assertTrue(substResult instanceof PsiWildcardType);
assertTrue(((PsiWildcardType)substResult).isExtends());
PsiClassType setType = (PsiClassType)((PsiWildcardType)substResult).getBound();
final PsiType substitutedResult = setResolveResult.getSubstitutor().substitute(typeParameter);
assertTrue(substitutedResult instanceof PsiWildcardType);
assertTrue(((PsiWildcardType)substitutedResult).isExtends());
PsiClassType setType = (PsiClassType)((PsiWildcardType)substitutedResult).getBound();
assert setType != null;
final PsiClassType.ClassResolveResult setTypeResolveResult = setType.resolveGenerics();
assertEquals("java.util.Map.Entry", setTypeResolveResult.getElement().getQualifiedName());
final PsiTypeParameter[] typeParameters = setTypeResolveResult.getElement().getTypeParameters();
final PsiClass setTypeResolveResultElement = setTypeResolveResult.getElement();
assert setTypeResolveResultElement != null : setTypeResolveResult;
assertEquals("java.util.Map.Entry", setTypeResolveResultElement.getQualifiedName());
final PsiTypeParameter[] typeParameters = setTypeResolveResultElement.getTypeParameters();
assertEquals(2, typeParameters.length);
PsiType[] mapParams = new PsiType[]{
setTypeResolveResult.getSubstitutor().substitute(typeParameters[0]),
@@ -507,31 +558,25 @@ public class ClsRepositoryUseTest extends PsiTestCase{
rootModel.setSdk(null);
rootModel.commit();
}
}
);
});
}
public void testGenericReturnType() throws Exception {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final ModifiableRootModel rootModel = ModuleRootManager.getInstance(myModule).getModifiableModel();
rootModel.setSdk(null);
rootModel.commit();
}
}
);
disableJdk();
final PsiClass map = myJavaFacade.findClass("java.util.Map", RESOLVE_SCOPE);
assert map != null;
final PsiElementFactory factory = myJavaFacade.getElementFactory();
final PsiClassType typeMapStringToInteger =
(PsiClassType) factory.createTypeFromText("java.util.Map <java.lang.String,java.lang.Integer>", null);
final PsiClassType.ClassResolveResult mapResolveResult = typeMapStringToInteger.resolveGenerics();
assertTrue(mapResolveResult.getElement().equals(map));
final PsiClass mapResolveResultElement = mapResolveResult.getElement();
assert mapResolveResultElement != null : typeMapStringToInteger;
assertTrue(mapResolveResultElement.equals(map));
final PsiMethod entrySetMethod = map.findMethodsByName("entrySet", false)[0];
final PsiType entrySetReturnType = entrySetMethod.getReturnType();
assert entrySetReturnType != null : entrySetMethod;
assertEquals("java.util.Set<? extends java.util.Map.Entry<K,V>>", entrySetReturnType.getCanonicalText());
final PsiSubstitutor substitutor = ((PsiClassType)entrySetReturnType).resolveGenerics().getSubstitutor();
assertEquals("E of java.util.Set -> ? extends java.util.Map.Entry<K,V>\n", substitutor.toString());
@@ -542,30 +587,37 @@ public class ClsRepositoryUseTest extends PsiTestCase{
}
public void testGenericInheritance() throws Exception {
PsiJavaFile file = (PsiJavaFile)PsiFileFactory.getInstance(getProject()).createFileFromText("Dummy.java", "import java.util.*;\n" +
"class Dummy {\n" +
"{ Map<Integer, Integer> list = new HashMap<Integer, Integer>();}\n" +
"}");
final String text = "import java.util.*;\n" +
"class Dummy {\n" +
" { Map<Integer, Integer> list = new HashMap<Integer, Integer>();}\n" +
"}";
PsiJavaFile file = (PsiJavaFile)PsiFileFactory.getInstance(getProject()).createFileFromText("Dummy.java", text);
PsiDeclarationStatement decl = (PsiDeclarationStatement) file.getClasses()[0].getInitializers()[0].getBody().getStatements()[0];
PsiVariable list = (PsiVariable) decl.getDeclaredElements()[0];
assertTrue(list.getType().isAssignableFrom(list.getInitializer().getType()));
final PsiExpression initializer = list.getInitializer();
assert initializer != null : list;
final PsiType type = initializer.getType();
assert type != null : initializer;
assertTrue(list.getType().isAssignableFrom(type));
}
public void testSimplerGenericInheritance() throws Exception {
PsiElementFactory factory = myJavaFacade.getElementFactory();
PsiClass map = myJavaFacade.findClass("java.util.Map", RESOLVE_SCOPE);
PsiClass hashMap = myJavaFacade.findClass("java.util.HashMap", RESOLVE_SCOPE);
assert map != null && hashMap != null;
assertTrue(factory.createType(map).isAssignableFrom(factory.createType(hashMap)));
}
public void testAnnotations () throws Exception {
public void testAnnotations() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.Annotated", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiAnnotation[] annotations = aClass.getModifierList().getAnnotations();
PsiModifierList modifierList = aClass.getModifierList();
assert modifierList != null : aClass;
PsiAnnotation[] annotations = modifierList.getAnnotations();
assertTrue(annotations.length == 1);
assertTrue(annotations[0].getText().equals("@pack.Annotation"));
@@ -577,19 +629,24 @@ public class ClsRepositoryUseTest extends PsiTestCase{
PsiParameter[] params = methods[0].getParameterList().getParameters();
assertTrue(params.length == 1);
annotations = params[0].getModifierList().getAnnotations();
modifierList = params[0].getModifierList();
assert modifierList != null : params[0];
annotations = modifierList.getAnnotations();
assertTrue(annotations.length == 1);
assertTrue(annotations[0].getText().equals("@pack.Annotation"));
PsiField[] fields = aClass.getFields();
assertTrue(fields.length == 1);
annotations = fields[0].getModifierList().getAnnotations();
modifierList = fields[0].getModifierList();
assert modifierList != null : fields[0];
annotations = modifierList.getAnnotations();
assertTrue(annotations.length == 1);
assertTrue(annotations[0].getText().equals("@pack.Annotation"));
}
public void testAnnotationMethodDefault () throws Exception {
public void testAnnotationMethodDefault() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.Annotation", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
PsiMethod[] methods = aClass.findMethodsByName("value", false);
@@ -598,8 +655,29 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertTrue(defaultValue != null);
}
public void testIndeterminateInAnnotationMethodDefault() throws Exception {
final PsiClass aClass = myJavaFacade.findClass("pack.Annotation2", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
for (PsiMethod method : aClass.getMethods()) {
assert method instanceof PsiAnnotationMethod : method;
try {
final PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)method).getDefaultValue();
assert defaultValue instanceof PsiReferenceExpression : defaultValue;
final String type = method.getName().startsWith("f") ? "Float." : "Double";
assert defaultValue.getText().contains(type) : defaultValue;
}
catch (Exception e) {
final String valueText = ((PsiMethodStub)((StubBasedPsiElement)method).getStub()).getDefaultValueText();
fail("Unable to compute default value of method " + method + " from text '" + valueText + "': " + e.getMessage());
}
}
}
public void testEnum() throws Exception {
PsiClass aClass = myJavaFacade.findClass("pack.MyEnum", GlobalSearchScope.allScope(myProject));
assert aClass != null;
checkValid(aClass);
assertTrue(aClass.isEnum());
@@ -612,11 +690,14 @@ public class ClsRepositoryUseTest extends PsiTestCase{
public void testVariance() throws Exception {
final PsiClass aClass = myJavaFacade.findClass("pack.Variance", RESOLVE_SCOPE);
assert aClass != null;
checkValid(aClass);
final PsiMethod[] methodsByName = aClass.findMethodsByName("method", false);
assertEquals(1, methodsByName.length);
final PsiMethod methodsWithReturnType = methodsByName[0];
final PsiType returnType = methodsWithReturnType.getReturnType();
assert returnType != null : methodsWithReturnType;
assertEquals("pack.Parametrized<? extends T>", returnType.getCanonicalText());
//TODO[ven, max]: After fix for loading decompiled stuff the result had been change. Need to discuss whether this is important
@@ -625,7 +706,7 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertEquals("public pack.Parametrized<? extends T> method() { /* compiled code */ }", methodsWithReturnType.getText());
}
private void checkEnumConstant(String name, PsiField field, PsiClassType type) {
private static void checkEnumConstant(String name, PsiField field, PsiClassType type) {
assertEquals(name, field.getName());
assertTrue(field instanceof PsiEnumConstant);
assertEquals(type, field.getType());
@@ -642,7 +723,9 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertTrue(parameterType instanceof PsiClassType);
final PsiClassType psiClassType = ((PsiClassType)parameterType);
final PsiClassType.ClassResolveResult resolveResult = psiClassType.resolveGenerics();
final PsiTypeParameter[] typeParameters = resolveResult.getElement().getTypeParameters();
final PsiClass resolveResultElement = resolveResult.getElement();
assert resolveResultElement != null : psiClassType;
final PsiTypeParameter[] typeParameters = resolveResultElement.getTypeParameters();
assertEquals(1, typeParameters.length);
final PsiType substitution = resolveResult.getSubstitutor().substitute(typeParameters[0]);
assertTrue(substitution instanceof PsiWildcardType);
@@ -661,11 +744,12 @@ public class ClsRepositoryUseTest extends PsiTestCase{
assertTrue(parameterType instanceof PsiClassType);
final PsiClassType psiClassType = ((PsiClassType)parameterType);
final PsiClassType.ClassResolveResult resolveResult = psiClassType.resolveGenerics();
final PsiTypeParameter[] typeParameters = resolveResult.getElement().getTypeParameters();
final PsiClass resolveResultElement = resolveResult.getElement();
assert resolveResultElement != null : psiClassType;
final PsiTypeParameter[] typeParameters = resolveResultElement.getTypeParameters();
assertEquals(1, typeParameters.length);
final PsiType substitution = resolveResult.getSubstitutor().substitute(typeParameters[0]);
assertTrue(substitution instanceof PsiWildcardType);
assertEquals(PsiWildcardType.createUnbounded(myPsiManager), substitution);
}
}