Reformat code to use 4 spaces indent

This commit is contained in:
Andrey Breslav
2012-01-27 17:33:00 +04:00
parent e678e072f1
commit 6c5bfc3b8e
93 changed files with 3856 additions and 3667 deletions
+88 -40
View File
@@ -68,25 +68,30 @@ public class Converter {
@NotNull @NotNull
public static String elementToKotlin(@NotNull PsiElement element) { public static String elementToKotlin(@NotNull PsiElement element) {
if (element instanceof PsiJavaFile) if (element instanceof PsiJavaFile) {
return fileToFile((PsiJavaFile) element).toKotlin(); return fileToFile((PsiJavaFile) element).toKotlin();
}
if (element instanceof PsiClass) if (element instanceof PsiClass) {
return classToClass((PsiClass) element).toKotlin(); return classToClass((PsiClass) element).toKotlin();
}
if (element instanceof PsiMethod) if (element instanceof PsiMethod) {
return methodToFunction((PsiMethod) element).toKotlin(); return methodToFunction((PsiMethod) element).toKotlin();
}
if (element instanceof PsiField) { if (element instanceof PsiField) {
PsiField field = (PsiField) element; PsiField field = (PsiField) element;
return fieldToField(field, field.getContainingClass()).toKotlin(); return fieldToField(field, field.getContainingClass()).toKotlin();
} }
if (element instanceof PsiStatement) if (element instanceof PsiStatement) {
return statementToStatement((PsiStatement) element).toKotlin(); return statementToStatement((PsiStatement) element).toKotlin();
}
if (element instanceof PsiExpression) if (element instanceof PsiExpression) {
return expressionToExpression((PsiExpression) element).toKotlin(); return expressionToExpression((PsiExpression) element).toKotlin();
}
return ""; return "";
} }
@@ -104,7 +109,9 @@ public class Converter {
@NotNull @NotNull
private static File fileToFile(PsiJavaFile javaFile, List<String> additionalImports) { private static File fileToFile(PsiJavaFile javaFile, List<String> additionalImports) {
final PsiImportList importList = javaFile.getImportList(); final PsiImportList importList = javaFile.getImportList();
List<Import> imports = importList == null ? Collections.<Import>emptyList() : importsToImportList(importList.getAllImportStatements()); List<Import> imports = importList == null
? Collections.<Import>emptyList()
: importsToImportList(importList.getAllImportStatements());
for (String i : additionalImports) for (String i : additionalImports)
imports.add(new Import(i)); imports.add(new Import(i));
return new File(quoteKeywords(javaFile.getPackageName()), imports, classesToClassList(javaFile.getClasses()), createMainFunction(javaFile)); return new File(quoteKeywords(javaFile.getPackageName()), imports, classesToClassList(javaFile.getClasses()), createMainFunction(javaFile));
@@ -134,10 +141,18 @@ public class Converter {
private static List<Member> getMembers(@NotNull PsiClass psiClass) { private static List<Member> getMembers(@NotNull PsiClass psiClass) {
List<Member> members = new LinkedList<Member>(); List<Member> members = new LinkedList<Member>();
for (PsiElement e : psiClass.getChildren()) { for (PsiElement e : psiClass.getChildren()) {
if (e instanceof PsiMethod) members.add(methodToFunction((PsiMethod) e, true)); if (e instanceof PsiMethod) {
else if (e instanceof PsiField) members.add(fieldToField((PsiField) e, psiClass)); members.add(methodToFunction((PsiMethod) e, true));
else if (e instanceof PsiClass) members.add(classToClass((PsiClass) e)); }
else if (e instanceof PsiClassInitializer) members.add(initializerToInitializer((PsiClassInitializer) e)); else if (e instanceof PsiField) {
members.add(fieldToField((PsiField) e, psiClass));
}
else if (e instanceof PsiClass) {
members.add(classToClass((PsiClass) e));
}
else if (e instanceof PsiClassInitializer) {
members.add(initializerToInitializer((PsiClassInitializer) e));
}
else if (e instanceof PsiMember) System.out.println(e.getClass() + " " + e.getText()); else if (e instanceof PsiMember) System.out.println(e.getClass() + " " + e.getText());
} }
return members; return members;
@@ -147,8 +162,9 @@ public class Converter {
private static List<Field> getFinalOrWithEmptyInitializer(@NotNull List<? extends Field> fields) { private static List<Field> getFinalOrWithEmptyInitializer(@NotNull List<? extends Field> fields) {
List<Field> result = new LinkedList<Field>(); List<Field> result = new LinkedList<Field>();
for (Field f : fields) for (Field f : fields)
if (f.isVal() || f.getInitializer().toKotlin().isEmpty()) if (f.isVal() || f.getInitializer().toKotlin().isEmpty()) {
result.add(f); result.add(f);
}
return result; return result;
} }
@@ -196,12 +212,13 @@ public class Converter {
final SuperVisitor visitor = new SuperVisitor(); final SuperVisitor visitor = new SuperVisitor();
psiClass.accept(visitor); psiClass.accept(visitor);
final HashSet<PsiExpressionList> resolvedSuperCallParameters = visitor.getResolvedSuperCallParameters(); final HashSet<PsiExpressionList> resolvedSuperCallParameters = visitor.getResolvedSuperCallParameters();
if (resolvedSuperCallParameters.size() == 1) if (resolvedSuperCallParameters.size() == 1) {
baseClassParams.addAll( baseClassParams.addAll(
expressionsToExpressionList( expressionsToExpressionList(
resolvedSuperCallParameters.toArray(new PsiExpressionList[1])[0].getExpressions() resolvedSuperCallParameters.toArray(new PsiExpressionList[1])[0].getExpressions()
) )
); );
}
// we create primary constructor from all non final fields and fields without initializers // we create primary constructor from all non final fields and fields without initializers
if (!psiClass.isEnum() && !psiClass.isInterface() && psiClass.getConstructors().length > 1 && getPrimaryConstructorForThisCase(psiClass) == null) { if (!psiClass.isEnum() && !psiClass.isInterface() && psiClass.getConstructors().length > 1 && getPrimaryConstructorForThisCase(psiClass) == null) {
@@ -266,10 +283,12 @@ public class Converter {
); );
} }
if (psiClass.isInterface()) if (psiClass.isInterface()) {
return new Trait(name, modifiers, typeParameters, extendsTypes, Collections.<Expression>emptyList(), implementsTypes, members); return new Trait(name, modifiers, typeParameters, extendsTypes, Collections.<Expression>emptyList(), implementsTypes, members);
if (psiClass.isEnum()) }
if (psiClass.isEnum()) {
return new Enum(name, modifiers, typeParameters, Collections.<Type>emptyList(), Collections.<Expression>emptyList(), implementsTypes, members); return new Enum(name, modifiers, typeParameters, Collections.<Type>emptyList(), Collections.<Expression>emptyList(), implementsTypes, members);
}
return new Class(name, modifiers, typeParameters, extendsTypes, baseClassParams, implementsTypes, members); return new Class(name, modifiers, typeParameters, extendsTypes, baseClassParams, implementsTypes, members);
} }
@@ -283,8 +302,9 @@ public class Converter {
@NotNull @NotNull
public static String getDefaultInitializer(@NotNull Field f) { public static String getDefaultInitializer(@NotNull Field f) {
if (f.getType().isNullable()) if (f.getType().isNullable()) {
return "null"; return "null";
}
else { else {
final String typeToKotlin = f.getType().toKotlin(); final String typeToKotlin = f.getType().toKotlin();
if (typeToKotlin.equals("Boolean")) return "false"; if (typeToKotlin.equals("Boolean")) return "false";
@@ -306,12 +326,14 @@ public class Converter {
private static Field fieldToField(@NotNull PsiField field, PsiClass psiClass) { private static Field fieldToField(@NotNull PsiField field, PsiClass psiClass) {
Set<String> modifiers = modifiersListToModifiersSet(field.getModifierList()); Set<String> modifiers = modifiersListToModifiersSet(field.getModifierList());
if (field instanceof PsiEnumConstant) // TODO: remove instanceof if (field instanceof PsiEnumConstant) // TODO: remove instanceof
{
return new EnumConstant( return new EnumConstant(
new IdentifierImpl(field.getName()), // TODO new IdentifierImpl(field.getName()), // TODO
modifiers, modifiers,
typeToType(field.getType()), typeToType(field.getType()),
elementToElement(((PsiEnumConstant) field).getArgumentList()) elementToElement(((PsiEnumConstant) field).getArgumentList())
); );
}
return new Field( return new Field(
new IdentifierImpl(field.getName()), // TODO new IdentifierImpl(field.getName()), // TODO
modifiers, modifiers,
@@ -331,14 +353,16 @@ public class Converter {
public static boolean isConstructorPrimary(@NotNull PsiMethod constructor) { public static boolean isConstructorPrimary(@NotNull PsiMethod constructor) {
if (constructor.getParent() instanceof PsiClass) { if (constructor.getParent() instanceof PsiClass) {
final PsiClass parent = (PsiClass) constructor.getParent(); final PsiClass parent = (PsiClass) constructor.getParent();
if (parent.getConstructors().length == 1) if (parent.getConstructors().length == 1) {
return true; return true;
}
else { else {
PsiMethod c = getPrimaryConstructorForThisCase(parent); // TODO: move up to classToClass() method PsiMethod c = getPrimaryConstructorForThisCase(parent); // TODO: move up to classToClass() method
if (c != null && c.hashCode() == constructor.hashCode()) if (c != null && c.hashCode() == constructor.hashCode()) {
return true; return true;
} }
} }
}
return false; return false;
} }
@@ -346,8 +370,9 @@ public class Converter {
private static List<Statement> removeEmpty(@NotNull List<Statement> statements) { private static List<Statement> removeEmpty(@NotNull List<Statement> statements) {
List<Statement> result = new LinkedList<Statement>(); List<Statement> result = new LinkedList<Statement>();
for (Statement s : statements) for (Statement s : statements)
if (s != Statement.EMPTY_STATEMENT && s != Expression.EMPTY_EXPRESSION) if (s != Statement.EMPTY_STATEMENT && s != Expression.EMPTY_EXPRESSION) {
result.add(s); result.add(s);
}
return result; return result;
} }
@@ -358,26 +383,33 @@ public class Converter {
@NotNull @NotNull
private static Function methodToFunction(@NotNull PsiMethod method, boolean notEmpty) { private static Function methodToFunction(@NotNull PsiMethod method, boolean notEmpty) {
if (isOverrideObjectDirect(method)) if (isOverrideObjectDirect(method)) {
ourDispatcher.setExpressionVisitor(new ExpressionVisitorForDirectObjectInheritors()); ourDispatcher.setExpressionVisitor(new ExpressionVisitorForDirectObjectInheritors());
else }
else {
ourDispatcher.setExpressionVisitor(new ExpressionVisitor()); ourDispatcher.setExpressionVisitor(new ExpressionVisitor());
}
ourMethodReturnType = method.getReturnType(); ourMethodReturnType = method.getReturnType();
final IdentifierImpl identifier = new IdentifierImpl(method.getName()); final IdentifierImpl identifier = new IdentifierImpl(method.getName());
final Type returnType = typeToType(method.getReturnType(), ConverterUtil.isAnnotatedAsNotNull(method.getModifierList())); final Type returnType = typeToType(method.getReturnType(), ConverterUtil.isAnnotatedAsNotNull(method.getModifierList()));
final Block body = hasSetting("declarations-only") ? Block.EMPTY_BLOCK : blockToBlock(method.getBody(), notEmpty); // #TODO final Block body = hasSetting("declarations-only")
? Block.EMPTY_BLOCK
: blockToBlock(method.getBody(), notEmpty); // #TODO
final Element params = createFunctionParameters(method); final Element params = createFunctionParameters(method);
final List<Element> typeParameters = elementsToElementList(method.getTypeParameters()); final List<Element> typeParameters = elementsToElementList(method.getTypeParameters());
final Set<String> modifiers = modifiersListToModifiersSet(method.getModifierList()); final Set<String> modifiers = modifiersListToModifiersSet(method.getModifierList());
if (isOverrideAnyMethodExceptMethodsFromObject(method)) if (isOverrideAnyMethodExceptMethodsFromObject(method)) {
modifiers.add(Modifier.OVERRIDE); modifiers.add(Modifier.OVERRIDE);
if (method.getParent() instanceof PsiClass && ((PsiClass) method.getParent()).isInterface()) }
if (method.getParent() instanceof PsiClass && ((PsiClass) method.getParent()).isInterface()) {
modifiers.remove(Modifier.ABSTRACT); modifiers.remove(Modifier.ABSTRACT);
if (isNotOpenMethod(method)) }
if (isNotOpenMethod(method)) {
modifiers.add(Modifier.NOT_OPEN); modifiers.add(Modifier.NOT_OPEN);
}
if (method.isConstructor()) { // TODO: simplify if (method.isConstructor()) { // TODO: simplify
boolean isPrimary = isConstructorPrimary(method); boolean isPrimary = isConstructorPrimary(method);
@@ -417,18 +449,21 @@ public class Converter {
private static boolean isNotOpenMethod(@NotNull final PsiMethod method) { private static boolean isNotOpenMethod(@NotNull final PsiMethod method) {
if (method.getParent() instanceof PsiClass) { if (method.getParent() instanceof PsiClass) {
final PsiModifierList parentModifierList = ((PsiClass) method.getParent()).getModifierList(); final PsiModifierList parentModifierList = ((PsiClass) method.getParent()).getModifierList();
if ((parentModifierList != null && parentModifierList.hasExplicitModifier(Modifier.FINAL)) || ((PsiClass) method.getParent()).isEnum()) if ((parentModifierList != null && parentModifierList.hasExplicitModifier(Modifier.FINAL)) || ((PsiClass) method.getParent()).isEnum()) {
return true; return true;
} }
}
return false; return false;
} }
private static boolean isOverrideAnyMethodExceptMethodsFromObject(@NotNull PsiMethod method) { private static boolean isOverrideAnyMethodExceptMethodsFromObject(@NotNull PsiMethod method) {
boolean counter = normalCase(method); boolean counter = normalCase(method);
if (counter) if (counter) {
return true; return true;
if (isInheritFromObject(method)) }
if (isInheritFromObject(method)) {
return caseForObject(method); return caseForObject(method);
}
return false; return false;
} }
@@ -450,9 +485,10 @@ public class Converter {
for (HierarchicalMethodSignature s : method.getHierarchicalMethodSignature().getSuperSignatures()) { for (HierarchicalMethodSignature s : method.getHierarchicalMethodSignature().getSuperSignatures()) {
PsiClass containingClass = s.getMethod().getContainingClass(); PsiClass containingClass = s.getMethod().getContainingClass();
String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : ""; String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : "";
if (qualifiedName != null && !qualifiedName.equals(JAVA_LANG_OBJECT)) if (qualifiedName != null && !qualifiedName.equals(JAVA_LANG_OBJECT)) {
counter++; counter++;
} }
}
return counter > 0; return counter > 0;
} }
@@ -461,9 +497,10 @@ public class Converter {
for (HierarchicalMethodSignature s : superSignatures) { for (HierarchicalMethodSignature s : superSignatures) {
PsiClass containingClass = s.getMethod().getContainingClass(); PsiClass containingClass = s.getMethod().getContainingClass();
String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : ""; String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : "";
if (qualifiedName != null && qualifiedName.equals(JAVA_LANG_OBJECT)) if (qualifiedName != null && qualifiedName.equals(JAVA_LANG_OBJECT)) {
return true; return true;
} }
}
return false; return false;
} }
@@ -472,9 +509,10 @@ public class Converter {
if (superSignatures.size() == 1) { if (superSignatures.size() == 1) {
final PsiClass containingClass = superSignatures.get(0).getMethod().getContainingClass(); final PsiClass containingClass = superSignatures.get(0).getMethod().getContainingClass();
final String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : ""; final String qualifiedName = containingClass != null ? containingClass.getQualifiedName() : "";
if (qualifiedName != null && qualifiedName.equals(JAVA_LANG_OBJECT)) if (qualifiedName != null && qualifiedName.equals(JAVA_LANG_OBJECT)) {
return true; return true;
} }
}
return false; return false;
} }
@@ -559,8 +597,9 @@ public class Converter {
@NotNull @NotNull
public static Type typeToType(PsiType type, boolean notNull) { public static Type typeToType(PsiType type, boolean notNull) {
Type result = typeToType(type); Type result = typeToType(type);
if (notNull) if (notNull) {
result.convertedToNotNull(); result.convertedToNotNull();
}
return result; return result;
} }
@@ -577,17 +616,19 @@ public class Converter {
for (PsiImportStatementBase i : imports) { for (PsiImportStatementBase i : imports) {
Import anImport = importToImport(i); Import anImport = importToImport(i);
String name = anImport.getName(); String name = anImport.getName();
if (!name.isEmpty() && !NOT_NULL_ANNOTATIONS.contains(name)) if (!name.isEmpty() && !NOT_NULL_ANNOTATIONS.contains(name)) {
result.add(anImport); result.add(anImport);
} }
}
return result; return result;
} }
@NotNull @NotNull
private static Import importToImport(@NotNull PsiImportStatementBase i) { private static Import importToImport(@NotNull PsiImportStatementBase i) {
final PsiJavaCodeReferenceElement reference = i.getImportReference(); final PsiJavaCodeReferenceElement reference = i.getImportReference();
if (reference != null) if (reference != null) {
return new Import(quoteKeywords(reference.getQualifiedName()) + (i.isOnDemand() ? ".*" : "")); return new Import(quoteKeywords(reference.getQualifiedName()) + (i.isOnDemand() ? ".*" : ""));
}
return new Import(""); return new Import("");
} }
@@ -685,19 +726,23 @@ public class Converter {
boolean isRef = (expression instanceof PsiReferenceExpression && ((PsiReferenceExpression) expression).isQualified() || expression instanceof PsiMethodCallExpression); boolean isRef = (expression instanceof PsiReferenceExpression && ((PsiReferenceExpression) expression).isQualified() || expression instanceof PsiMethodCallExpression);
boolean containsQuestDot = expressionToExpression(expression).toKotlin().contains("?."); boolean containsQuestDot = expressionToExpression(expression).toKotlin().contains("?.");
if (isPrimitiveTypeOrNull && isRef && containsQuestDot) if (isPrimitiveTypeOrNull && isRef && containsQuestDot) {
conversion += ".sure()"; conversion += ".sure()";
}
if (actualType != null) if (actualType != null) {
if (isConversionNeeded(actualType, expectedType)) if (isConversionNeeded(actualType, expectedType)) {
conversion += getPrimitiveTypeConversion(expectedType.getCanonicalText()); conversion += getPrimitiveTypeConversion(expectedType.getCanonicalText());
} }
}
}
return conversion; return conversion;
} }
private static boolean isConversionNeeded(@Nullable final PsiType actual, @Nullable final PsiType expected) { private static boolean isConversionNeeded(@Nullable final PsiType actual, @Nullable final PsiType expected) {
if (actual == null || expected == null) if (actual == null || expected == null) {
return false; return false;
}
Map<String, String> typeMap = new HashMap<String, String>(); Map<String, String> typeMap = new HashMap<String, String>();
typeMap.put(JAVA_LANG_BYTE, "byte"); typeMap.put(JAVA_LANG_BYTE, "byte");
typeMap.put(JAVA_LANG_SHORT, "short"); typeMap.put(JAVA_LANG_SHORT, "short");
@@ -732,8 +777,9 @@ public class Converter {
conversions.put(JAVA_LANG_DOUBLE, "dbl"); conversions.put(JAVA_LANG_DOUBLE, "dbl");
conversions.put(JAVA_LANG_CHARACTER, "chr"); conversions.put(JAVA_LANG_CHARACTER, "chr");
if (conversions.containsKey(type)) if (conversions.containsKey(type)) {
return "." + conversions.get(type); return "." + conversions.get(type);
}
return ""; return "";
} }
@@ -746,8 +792,10 @@ public class Converter {
@NotNull @NotNull
public static SureCallChainExpression createSureCallOnlyForChain(@Nullable PsiExpression expression, @NotNull PsiType type) { public static SureCallChainExpression createSureCallOnlyForChain(@Nullable PsiExpression expression, @NotNull PsiType type) {
String conversion = (expression != null && (expression instanceof PsiReferenceExpression || expression instanceof PsiMethodCallExpression)) ? String conversion = (expression != null && (expression instanceof PsiReferenceExpression || expression instanceof PsiMethodCallExpression))
createConversionForExpression(expression, type) : ""; ?
createConversionForExpression(expression, type)
: "";
return new SureCallChainExpression(expressionToExpression(expression), conversion); return new SureCallChainExpression(expressionToExpression(expression), conversion);
} }
@@ -78,9 +78,10 @@ public class ConverterUtil {
ReferenceCollector visitor = new ReferenceCollector(); ReferenceCollector visitor = new ReferenceCollector();
container.accept(visitor); container.accept(visitor);
for (PsiReferenceExpression e : visitor.getCollectedReferences()) for (PsiReferenceExpression e : visitor.getCollectedReferences())
if (e.isReferenceTo(element) && PsiUtil.isAccessedForWriting(e)) if (e.isReferenceTo(element) && PsiUtil.isAccessedForWriting(e)) {
counter++; counter++;
} }
}
return counter; return counter;
} }
@@ -93,10 +94,11 @@ public class ConverterUtil {
PsiAnnotation[] annotations = modifierList.getAnnotations(); PsiAnnotation[] annotations = modifierList.getAnnotations();
for (PsiAnnotation a : annotations) { for (PsiAnnotation a : annotations) {
String qualifiedName = a.getQualifiedName(); String qualifiedName = a.getQualifiedName();
if (qualifiedName != null && NOT_NULL_ANNOTATIONS.contains(qualifiedName)) if (qualifiedName != null && NOT_NULL_ANNOTATIONS.contains(qualifiedName)) {
return true; return true;
} }
} }
}
return false; return false;
} }
@@ -74,8 +74,9 @@ public class JavaToKotlinTranslator {
@NotNull @NotNull
static String prettify(@Nullable String code) { static String prettify(@Nullable String code) {
if (code == null) if (code == null) {
return ""; return "";
}
return code return code
.trim() .trim()
.replaceAll("\r\n", "\n") .replaceAll("\r\n", "\n")
@@ -97,7 +98,8 @@ public class JavaToKotlinTranslator {
if (rtJar == null) { if (rtJar == null) {
throw new SetupJavaCoreEnvironmentException("JAVA_HOME environment variable needs to be defined"); throw new SetupJavaCoreEnvironmentException("JAVA_HOME environment variable needs to be defined");
} }
} else { }
else {
rtJar = findRtJar(javaHome); rtJar = findRtJar(javaHome);
} }
@@ -131,9 +133,10 @@ public class JavaToKotlinTranslator {
if (systemClassLoader instanceof URLClassLoader) { if (systemClassLoader instanceof URLClassLoader) {
URLClassLoader loader = (URLClassLoader) systemClassLoader; URLClassLoader loader = (URLClassLoader) systemClassLoader;
for (URL url : loader.getURLs()) for (URL url : loader.getURLs())
if ("file".equals(url.getProtocol()) && url.getFile().endsWith("/annotations.jar")) if ("file".equals(url.getProtocol()) && url.getFile().endsWith("/annotations.jar")) {
return new File(url.getFile()); return new File(url.getFile());
} }
}
return null; return null;
} }
@@ -161,7 +164,8 @@ public class JavaToKotlinTranslator {
} }
}, ", ")); }, ", "));
} }
} else if (failOnError) { }
else if (failOnError) {
throw new SetupJavaCoreEnvironmentException("System class loader is not an URLClassLoader: " + systemClassLoader); throw new SetupJavaCoreEnvironmentException("System class loader is not an URLClassLoader: " + systemClassLoader);
} }
return null; return null;
@@ -204,11 +208,14 @@ public class JavaToKotlinTranslator {
} catch (Exception e) { } catch (Exception e) {
out.println("EXCEPTION: " + e.getMessage()); out.println("EXCEPTION: " + e.getMessage());
} }
if (kotlinCode.isEmpty()) if (kotlinCode.isEmpty()) {
out.println("EXCEPTION: generated code is empty."); out.println("EXCEPTION: generated code is empty.");
else }
else {
out.println(kotlinCode); out.println(kotlinCode);
} else { }
}
else {
out.println("EXCEPTION: wrong number of arguments (should be 1)."); out.println("EXCEPTION: wrong number of arguments (should be 1).");
} }
} }
@@ -20,8 +20,9 @@ public class ArrayInitializerExpression extends Expression {
@NotNull @NotNull
private static String createArrayFunction(@NotNull final Type type) { private static String createArrayFunction(@NotNull final Type type) {
String sType = innerTypeStr(type); String sType = innerTypeStr(type);
if (PRIMITIVE_TYPES.contains(sType)) if (PRIMITIVE_TYPES.contains(sType)) {
return sType + "Array"; // intArray return sType + "Array"; // intArray
}
return AstUtil.lowerFirstCharacter(type.convertedToNotNull().toKotlin()); // array<Foo?> return AstUtil.lowerFirstCharacter(type.convertedToNotNull().toKotlin()); // array<Foo?>
} }
@@ -46,8 +47,9 @@ public class ArrayInitializerExpression extends Expression {
String afterReplace = innerTypeStr(type).replace(">", "").replace("<", "").replace("?", ""); String afterReplace = innerTypeStr(type).replace(">", "").replace("<", "").replace("?", "");
if (doubleOrFloatTypes.contains(afterReplace)) { if (doubleOrFloatTypes.contains(afterReplace)) {
if (i.getKind() == Kind.LITERAL) { if (i.getKind() == Kind.LITERAL) {
if (i.toKotlin().contains(".")) if (i.toKotlin().contains(".")) {
return i.toKotlin(); return i.toKotlin();
}
return i.toKotlin() + DOT + ZERO; return i.toKotlin() + DOT + ZERO;
} }
return "(" + i.toKotlin() + ")" + getConversion(afterReplace); return "(" + i.toKotlin() + ")" + getConversion(afterReplace);
@@ -25,8 +25,9 @@ public class ArrayType extends Type {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (PRIMITIVE_TYPES.contains(myType.toKotlin().toLowerCase())) if (PRIMITIVE_TYPES.contains(myType.toKotlin().toLowerCase())) {
return myType.toKotlin() + "Array" + isNullableStr(); // returns IntArray, BooleanArray, etc. return myType.toKotlin() + "Array" + isNullableStr(); // returns IntArray, BooleanArray, etc.
}
return "Array" + "<" + myType.toKotlin() + ">" + isNullableStr(); return "Array" + "<" + myType.toKotlin() + ">" + isNullableStr();
} }
} }
@@ -20,18 +20,21 @@ public class ArrayWithoutInitializationExpression extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myType.getKind() == Kind.ARRAY_TYPE) if (myType.getKind() == Kind.ARRAY_TYPE) {
return constructInnerType((ArrayType) myType, myExpressions); return constructInnerType((ArrayType) myType, myExpressions);
}
return getConstructorName(myType); return getConstructorName(myType);
} }
@NotNull @NotNull
private static String constructInnerType(@NotNull ArrayType hostType, @NotNull List<Expression> expressions) { private static String constructInnerType(@NotNull ArrayType hostType, @NotNull List<Expression> expressions) {
if (expressions.size() == 1) if (expressions.size() == 1) {
return oneDim(hostType, expressions.get(0)); return oneDim(hostType, expressions.get(0));
}
Type innerType = hostType.getInnerType(); Type innerType = hostType.getInnerType();
if (expressions.size() > 1 && innerType.getKind() == Kind.ARRAY_TYPE) if (expressions.size() > 1 && innerType.getKind() == Kind.ARRAY_TYPE) {
return oneDim(hostType, expressions.get(0), "{" + constructInnerType((ArrayType) innerType, expressions.subList(1, expressions.size())) + "}"); return oneDim(hostType, expressions.get(0), "{" + constructInnerType((ArrayType) innerType, expressions.subList(1, expressions.size())) + "}");
}
return getConstructorName(hostType); return getConstructorName(hostType);
} }
+2 -1
View File
@@ -42,10 +42,11 @@ public class Block extends Statement {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (!isEmpty()) if (!isEmpty()) {
return "{" + N + return "{" + N +
AstUtil.joinNodes(myStatements, N) + N + AstUtil.joinNodes(myStatements, N) + N +
"}"; "}";
}
return EMPTY; return EMPTY;
} }
} }
@@ -24,8 +24,9 @@ public class BreakStatement extends Statement {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myLabel.isEmpty()) if (myLabel.isEmpty()) {
return "break"; return "break";
}
return "break" + AT + myLabel.toKotlin(); return "break" + AT + myLabel.toKotlin();
} }
} }
@@ -32,11 +32,14 @@ public class CallChainExpression extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (!myExpression.isEmpty()) if (!myExpression.isEmpty()) {
if (myExpression.isNullable()) if (myExpression.isNullable()) {
return myExpression.toKotlin() + QUESTDOT + myIdentifier.toKotlin(); return myExpression.toKotlin() + QUESTDOT + myIdentifier.toKotlin();
else }
else {
return myExpression.toKotlin() + DOT + myIdentifier.toKotlin(); return myExpression.toKotlin() + DOT + myIdentifier.toKotlin();
}
}
return myIdentifier.toKotlin(); return myIdentifier.toKotlin();
} }
} }
@@ -17,8 +17,9 @@ public class CaseContainer extends Statement {
myCaseStatement = caseStatement; myCaseStatement = caseStatement;
List<Statement> newStatements = new LinkedList<Statement>(); List<Statement> newStatements = new LinkedList<Statement>();
for (Statement s : statements) for (Statement s : statements)
if (s.getKind() != Kind.BREAK && s.getKind() != Kind.CONTINUE) if (s.getKind() != Kind.BREAK && s.getKind() != Kind.CONTINUE) {
newStatements.add(s); newStatements.add(s);
}
myBlock = new Block(newStatements); myBlock = new Block(newStatements);
} }
+32 -16
View File
@@ -33,7 +33,7 @@ public class Class extends Member {
myTypeParameters = typeParameters; myTypeParameters = typeParameters;
myExtendsTypes = extendsTypes; myExtendsTypes = extendsTypes;
myImplementsTypes = implementsTypes; myImplementsTypes = implementsTypes;
myMembers= getMembers(members); myMembers = getMembers(members);
} }
static List<Member> getMembers(List<Member> members) { static List<Member> getMembers(List<Member> members) {
@@ -44,7 +44,8 @@ public class Class extends Member {
withoutPrivate.add(m); withoutPrivate.add(m);
} }
} }
} else { }
else {
withoutPrivate = members; withoutPrivate = members;
} }
return withoutPrivate; return withoutPrivate;
@@ -54,30 +55,35 @@ public class Class extends Member {
@Nullable @Nullable
private Constructor getPrimaryConstructor() { private Constructor getPrimaryConstructor() {
for (Member m : myMembers) for (Member m : myMembers)
if (m.getKind() == Kind.CONSTRUCTOR) if (m.getKind() == Kind.CONSTRUCTOR) {
if (((Constructor) m).isPrimary()) if (((Constructor) m).isPrimary()) {
return (Constructor) m; return (Constructor) m;
}
}
return null; return null;
} }
String primaryConstructorSignatureToKotlin() { String primaryConstructorSignatureToKotlin() {
Constructor maybeConstructor = getPrimaryConstructor(); Constructor maybeConstructor = getPrimaryConstructor();
if (maybeConstructor != null) if (maybeConstructor != null) {
return maybeConstructor.primarySignatureToKotlin(); return maybeConstructor.primarySignatureToKotlin();
}
return "(" + ")"; return "(" + ")";
} }
String primaryConstructorBodyToKotlin() { String primaryConstructorBodyToKotlin() {
Constructor maybeConstructor = getPrimaryConstructor(); Constructor maybeConstructor = getPrimaryConstructor();
if (maybeConstructor != null && !maybeConstructor.getBlock().isEmpty()) if (maybeConstructor != null && !maybeConstructor.getBlock().isEmpty()) {
return maybeConstructor.primaryBodyToKotlin(); return maybeConstructor.primaryBodyToKotlin();
}
return EMPTY; return EMPTY;
} }
private boolean hasWhere() { private boolean hasWhere() {
for (Element t : myTypeParameters) for (Element t : myTypeParameters)
if (t instanceof TypeParameter && ((TypeParameter) t).hasWhere()) if (t instanceof TypeParameter && ((TypeParameter) t).hasWhere()) {
return true; return true;
}
return false; return false;
} }
@@ -86,8 +92,9 @@ public class Class extends Member {
if (hasWhere()) { if (hasWhere()) {
List<String> wheres = new LinkedList<String>(); List<String> wheres = new LinkedList<String>();
for (Element t : myTypeParameters) for (Element t : myTypeParameters)
if (t instanceof TypeParameter) if (t instanceof TypeParameter) {
wheres.add(((TypeParameter) t).getWhereToKotlin()); wheres.add(((TypeParameter) t).getWhereToKotlin());
}
return SPACE + "where" + SPACE + join(wheres, COMMA_WITH_SPACE) + SPACE; return SPACE + "where" + SPACE + join(wheres, COMMA_WITH_SPACE) + SPACE;
} }
return EMPTY; return EMPTY;
@@ -97,8 +104,9 @@ public class Class extends Member {
LinkedList<Member> membersExceptConstructors() { LinkedList<Member> membersExceptConstructors() {
final LinkedList<Member> result = new LinkedList<Member>(); final LinkedList<Member> result = new LinkedList<Member>();
for (Member m : myMembers) for (Member m : myMembers)
if (m.getKind() != Kind.CONSTRUCTOR) if (m.getKind() != Kind.CONSTRUCTOR) {
result.add(m); result.add(m);
}
return result; return result;
} }
@@ -116,8 +124,9 @@ public class Class extends Member {
final Block block = new Block(statements); final Block block = new Block(statements);
final List<Element> typeParameters = new LinkedList<Element>(); final List<Element> typeParameters = new LinkedList<Element>();
if (f.getTypeParameters().size() == 0) if (f.getTypeParameters().size() == 0) {
typeParameters.addAll(myTypeParameters); typeParameters.addAll(myTypeParameters);
}
else { else {
typeParameters.addAll(myTypeParameters); typeParameters.addAll(myTypeParameters);
typeParameters.addAll(f.getTypeParameters()); typeParameters.addAll(f.getTypeParameters());
@@ -145,9 +154,11 @@ public class Class extends Member {
LinkedList<String> result = new LinkedList<String>(); LinkedList<String> result = new LinkedList<String>();
result.add(myExtendsTypes.get(0).toKotlin() + "(" + joinNodes(myBaseClassParams, COMMA_WITH_SPACE) + ")"); result.add(myExtendsTypes.get(0).toKotlin() + "(" + joinNodes(myBaseClassParams, COMMA_WITH_SPACE) + ")");
return result; return result;
} else }
else {
return nodesToKotlin(myExtendsTypes); return nodesToKotlin(myExtendsTypes);
} }
}
@NotNull @NotNull
String implementTypesToKotlin() { String implementTypesToKotlin() {
@@ -164,16 +175,19 @@ public class Class extends Member {
String modifiersToKotlin() { String modifiersToKotlin() {
List<String> modifierList = new LinkedList<String>(); List<String> modifierList = new LinkedList<String>();
if (needAbstractModifier()) if (needAbstractModifier()) {
modifierList.add(Modifier.ABSTRACT); modifierList.add(Modifier.ABSTRACT);
}
modifierList.add(accessModifier()); modifierList.add(accessModifier());
if (needOpenModifier()) if (needOpenModifier()) {
modifierList.add(Modifier.OPEN); modifierList.add(Modifier.OPEN);
}
if (modifierList.size() > 0) if (modifierList.size() > 0) {
return join(modifierList, SPACE) + SPACE; return join(modifierList, SPACE) + SPACE;
}
return EMPTY; return EMPTY;
} }
@@ -199,8 +213,9 @@ public class Class extends Member {
private static List<Member> getStatic(@NotNull List<? extends Member> members) { private static List<Member> getStatic(@NotNull List<? extends Member> members) {
List<Member> result = new LinkedList<Member>(); List<Member> result = new LinkedList<Member>();
for (Member m : members) for (Member m : members)
if (m.isStatic()) if (m.isStatic()) {
result.add(m); result.add(m);
}
return result; return result;
} }
@@ -208,8 +223,9 @@ public class Class extends Member {
private static List<Member> getNonStatic(@NotNull List<? extends Member> members) { private static List<Member> getNonStatic(@NotNull List<? extends Member> members) {
List<Member> result = new LinkedList<Member>(); List<Member> result = new LinkedList<Member>();
for (Member m : members) for (Member m : members)
if (!m.isStatic()) if (!m.isStatic()) {
result.add(m); result.add(m);
}
return result; return result;
} }
@@ -33,7 +33,9 @@ public class ClassType extends Type {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
String params = myParameters.size() == 0 ? EMPTY : "<" + AstUtil.joinNodes(myParameters, COMMA_WITH_SPACE) + ">"; String params = myParameters.size() == 0
? EMPTY
: "<" + AstUtil.joinNodes(myParameters, COMMA_WITH_SPACE) + ">";
return myType.toKotlin() + params + isNullableStr(); return myType.toKotlin() + params + isNullableStr();
} }
} }
@@ -24,8 +24,9 @@ public class ContinueStatement extends Statement {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myLabel.isEmpty()) if (myLabel.isEmpty()) {
return "continue"; return "continue";
}
return "continue" + AT + myLabel.toKotlin(); return "continue" + AT + myLabel.toKotlin();
} }
} }
@@ -15,8 +15,9 @@ public class EnumConstant extends Field {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myInitializer.toKotlin().isEmpty()) if (myInitializer.toKotlin().isEmpty()) {
return myIdentifier.toKotlin(); return myIdentifier.toKotlin();
}
return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin() + "(" + myInitializer.toKotlin() + ")"; return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin() + "(" + myInitializer.toKotlin() + ")";
} }
} }
+9 -4
View File
@@ -42,15 +42,17 @@ public class Field extends Member {
String modifiersToKotlin() { String modifiersToKotlin() {
List<String> modifierList = new LinkedList<String>(); List<String> modifierList = new LinkedList<String>();
if (isAbstract()) if (isAbstract()) {
modifierList.add(Modifier.ABSTRACT); modifierList.add(Modifier.ABSTRACT);
}
modifierList.add(accessModifier()); modifierList.add(accessModifier());
modifierList.add(isVal() ? "val" : "var"); modifierList.add(isVal() ? "val" : "var");
if (modifierList.size() > 0) if (modifierList.size() > 0) {
return AstUtil.join(modifierList, SPACE) + SPACE; return AstUtil.join(modifierList, SPACE) + SPACE;
}
return EMPTY; return EMPTY;
} }
@@ -69,8 +71,11 @@ public class Field extends Member {
public String toKotlin() { public String toKotlin() {
final String declaration = modifiersToKotlin() + myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin(); final String declaration = modifiersToKotlin() + myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin();
if (myInitializer.isEmpty()) if (myInitializer.isEmpty()) {
return declaration + (isVal() && !isStatic() && myWritingAccesses == 1 ? EMPTY : SPACE + EQUAL + SPACE + getDefaultInitializer(this)); return declaration + (isVal() && !isStatic() && myWritingAccesses == 1
? EMPTY
: SPACE + EQUAL + SPACE + getDefaultInitializer(this));
}
return declaration + SPACE + EQUAL + SPACE + myInitializer.toKotlin(); return declaration + SPACE + EQUAL + SPACE + myInitializer.toKotlin();
} }
+2 -1
View File
@@ -25,8 +25,9 @@ public class File extends Node {
@Override @Override
public String toKotlin() { public String toKotlin() {
final String common = AstUtil.joinNodes(myImports, N) + N2 + AstUtil.joinNodes(myClasses, N) + N + myMainFunction; final String common = AstUtil.joinNodes(myImports, N) + N2 + AstUtil.joinNodes(myClasses, N) + N + myMainFunction;
if (myPackageName.isEmpty()) if (myPackageName.isEmpty()) {
return common; return common;
}
return "package" + SPACE + myPackageName + N + return "package" + SPACE + myPackageName + N +
common; common;
} }
@@ -51,8 +51,9 @@ public class Function extends Member {
private boolean hasWhere() { private boolean hasWhere() {
for (Element t : myTypeParameters) for (Element t : myTypeParameters)
if (t instanceof TypeParameter && ((TypeParameter) t).hasWhere()) if (t instanceof TypeParameter && ((TypeParameter) t).hasWhere()) {
return true; return true;
}
return false; return false;
} }
@@ -60,8 +61,9 @@ public class Function extends Member {
if (hasWhere()) { if (hasWhere()) {
List<String> wheres = new LinkedList<String>(); List<String> wheres = new LinkedList<String>();
for (Element t : myTypeParameters) for (Element t : myTypeParameters)
if (t instanceof TypeParameter) if (t instanceof TypeParameter) {
wheres.add(((TypeParameter) t).getWhereToKotlin()); wheres.add(((TypeParameter) t).getWhereToKotlin());
}
return SPACE + "where" + SPACE + AstUtil.join(wheres, COMMA_WITH_SPACE) + SPACE; return SPACE + "where" + SPACE + AstUtil.join(wheres, COMMA_WITH_SPACE) + SPACE;
} }
return EMPTY; return EMPTY;
@@ -70,24 +72,30 @@ public class Function extends Member {
String modifiersToKotlin() { String modifiersToKotlin() {
List<String> modifierList = new LinkedList<String>(); List<String> modifierList = new LinkedList<String>();
if (isAbstract()) if (isAbstract()) {
modifierList.add(Modifier.ABSTRACT); modifierList.add(Modifier.ABSTRACT);
}
if (myModifiers.contains(Modifier.OVERRIDE)) if (myModifiers.contains(Modifier.OVERRIDE)) {
modifierList.add(Modifier.OVERRIDE); modifierList.add(Modifier.OVERRIDE);
}
if (!myModifiers.contains(Modifier.OVERRIDE) && !myModifiers.contains(Modifier.FINAL)) if (!myModifiers.contains(Modifier.OVERRIDE) && !myModifiers.contains(Modifier.FINAL)) {
modifierList.add(Modifier.OPEN); modifierList.add(Modifier.OPEN);
}
if (myModifiers.contains(Modifier.NOT_OPEN)) if (myModifiers.contains(Modifier.NOT_OPEN)) {
modifierList.remove(Modifier.OPEN); modifierList.remove(Modifier.OPEN);
}
String accessModifier = accessModifier(); String accessModifier = accessModifier();
if (!accessModifier.isEmpty()) if (!accessModifier.isEmpty()) {
modifierList.add(accessModifier); modifierList.add(accessModifier);
}
if (modifierList.size() > 0) if (modifierList.size() > 0) {
return AstUtil.join(modifierList, SPACE) + SPACE; return AstUtil.join(modifierList, SPACE) + SPACE;
}
return EMPTY; return EMPTY;
} }
@@ -46,8 +46,9 @@ public class IdentifierImpl extends Expression implements Identifier {
} }
private String ifNeedQuote() { private String ifNeedQuote() {
if (myQuotingNeeded && (ONLY_KOTLIN_KEYWORDS.contains(myName) || myName.contains("$"))) if (myQuotingNeeded && (ONLY_KOTLIN_KEYWORDS.contains(myName) || myName.contains("$"))) {
return quote(myName); return quote(myName);
}
return myName; return myName;
} }
@@ -21,10 +21,11 @@ public class IfStatement extends Expression {
public String toKotlin() { public String toKotlin() {
String result = "if" + SPACE + "(" + myCondition.toKotlin() + ")" + N + myThenStatement.toKotlin() + N; String result = "if" + SPACE + "(" + myCondition.toKotlin() + ")" + N + myThenStatement.toKotlin() + N;
if (myElseStatement != Statement.EMPTY_STATEMENT) if (myElseStatement != Statement.EMPTY_STATEMENT) {
return result + return result +
"else" + N + "else" + N +
myElseStatement.toKotlin(); myElseStatement.toKotlin();
}
return result; return result;
} }
@@ -27,8 +27,9 @@ public class LocalVariable extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myInitializer.isEmpty()) if (myInitializer.isEmpty()) {
return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin(); return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin();
}
return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin() + SPACE + return myIdentifier.toKotlin() + SPACE + COLON + SPACE + myType.toKotlin() + SPACE +
EQUAL + SPACE + myInitializer.toKotlin(); EQUAL + SPACE + myInitializer.toKotlin();
@@ -13,8 +13,9 @@ public abstract class Member extends Node implements IMember {
@NotNull @NotNull
String accessModifier() { String accessModifier() {
for (String m : myModifiers) for (String m : myModifiers)
if (m.equals(Modifier.PUBLIC) || m.equals(Modifier.PROTECTED) || m.equals(Modifier.PRIVATE)) if (m.equals(Modifier.PUBLIC) || m.equals(Modifier.PROTECTED) || m.equals(Modifier.PRIVATE)) {
return m; return m;
}
return EMPTY; // package local converted to internal, but we use internal by default return EMPTY; // package local converted to internal, but we use internal by default
} }
@@ -35,7 +35,9 @@ public class MethodCallExpression extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
String typeParamsToKotlin = myTypeParameters.size() > 0 ? "<" + AstUtil.joinNodes(myTypeParameters, COMMA_WITH_SPACE) + ">" : EMPTY; String typeParamsToKotlin = myTypeParameters.size() > 0
? "<" + AstUtil.joinNodes(myTypeParameters, COMMA_WITH_SPACE) + ">"
: EMPTY;
List<String> applyConversions = AstUtil.applyConversions(AstUtil.nodesToKotlin(myArguments), myConversions); List<String> applyConversions = AstUtil.applyConversions(AstUtil.nodesToKotlin(myArguments), myConversions);
return myMethodCall.toKotlin() + typeParamsToKotlin + "(" + AstUtil.join(applyConversions, COMMA_WITH_SPACE) + ")"; return myMethodCall.toKotlin() + typeParamsToKotlin + "(" + AstUtil.join(applyConversions, COMMA_WITH_SPACE) + ")";
} }
@@ -40,7 +40,8 @@ public class NewClassExpression extends Expression {
List<String> applyConversions = AstUtil.applyConversions(AstUtil.nodesToKotlin(myArguments), myConversions); List<String> applyConversions = AstUtil.applyConversions(AstUtil.nodesToKotlin(myArguments), myConversions);
String appliedArguments = AstUtil.join(applyConversions, COMMA_WITH_SPACE); String appliedArguments = AstUtil.join(applyConversions, COMMA_WITH_SPACE);
return myAnonymousClass != null ? return myAnonymousClass != null ?
"object" + SPACE + ":" + SPACE + qualifier + myName.toKotlin() + "(" + appliedArguments + ")" + myAnonymousClass.toKotlin() : "object" + SPACE + ":" + SPACE + qualifier + myName.toKotlin() + "(" + appliedArguments + ")" + myAnonymousClass.toKotlin()
:
qualifier + myName.toKotlin() + "(" + appliedArguments + ")"; qualifier + myName.toKotlin() + "(" + appliedArguments + ")";
} }
} }
@@ -15,7 +15,7 @@ public class StarProjectionType extends Type {
} }
} }
class G <T extends String> { class G<T extends String> {
public <T> G(T t) { public <T> G(T t) {
} }
} }
@@ -15,8 +15,9 @@ public class SuperExpression extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myIdentifier.isEmpty()) if (myIdentifier.isEmpty()) {
return "super"; return "super";
}
return "super" + AT + myIdentifier.toKotlin(); return "super" + AT + myIdentifier.toKotlin();
} }
} }
@@ -15,8 +15,9 @@ public class ThisExpression extends Expression {
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myIdentifier.isEmpty()) if (myIdentifier.isEmpty()) {
return "this"; return "this";
}
return "this" + AT + myIdentifier.toKotlin(); return "this" + AT + myIdentifier.toKotlin();
} }
} }
@@ -22,16 +22,18 @@ public class TypeParameter extends Element {
@NotNull @NotNull
public String getWhereToKotlin() { public String getWhereToKotlin() {
if (hasWhere()) if (hasWhere()) {
return myName.toKotlin() + SPACE + COLON + SPACE + myExtendsTypes.get(1).toKotlin(); return myName.toKotlin() + SPACE + COLON + SPACE + myExtendsTypes.get(1).toKotlin();
}
return EMPTY; return EMPTY;
} }
@NotNull @NotNull
@Override @Override
public String toKotlin() { public String toKotlin() {
if (myExtendsTypes.size() > 0) if (myExtendsTypes.size() > 0) {
return myName.toKotlin() + SPACE + COLON + SPACE + myExtendsTypes.get(0).toKotlin(); return myName.toKotlin() + SPACE + COLON + SPACE + myExtendsTypes.get(0).toKotlin();
}
return myName.toKotlin(); return myName.toKotlin();
} }
} }
@@ -22,9 +22,10 @@ public class AstUtil {
for (int i = 0; i < array.length; i++) { for (int i = 0; i < array.length; i++) {
buffer.append(array[i]); buffer.append(array[i]);
if (haveDelimiter && (i + 1) < array.length) if (haveDelimiter && (i + 1) < array.length) {
buffer.append(delimiter); buffer.append(delimiter);
} }
}
return buffer.toString(); return buffer.toString();
} }
@@ -75,23 +76,27 @@ public class AstUtil {
@NotNull @NotNull
public static String applyConversionForOneItem(@NotNull String f, @NotNull String s) { public static String applyConversionForOneItem(@NotNull String f, @NotNull String s) {
if (s.isEmpty()) if (s.isEmpty()) {
return f; return f;
else }
else {
return "(" + f + ")" + s; return "(" + f + ")" + s;
} }
}
@NotNull @NotNull
public static <T> T getOrElse(@NotNull Map<T, T> map, @NotNull T e, @NotNull T orElse) { public static <T> T getOrElse(@NotNull Map<T, T> map, @NotNull T e, @NotNull T orElse) {
if (map.containsKey(e)) if (map.containsKey(e)) {
return map.get(e); return map.get(e);
}
return orElse; return orElse;
} }
@NotNull @NotNull
public static String replaceLastQuest(@NotNull String str) { public static String replaceLastQuest(@NotNull String str) {
if (str.endsWith("?")) if (str.endsWith("?")) {
return str.substring(0, str.length() - 1); return str.substring(0, str.length() - 1);
}
return str; return str;
} }
} }
@@ -7,7 +7,7 @@ import org.jetbrains.jet.j2k.ast.*;
import java.util.List; import java.util.List;
import static org.jetbrains.jet.j2k.Converter.*; import static org.jetbrains.jet.j2k.Converter.*;
import static org.jetbrains.jet.j2k.ConverterUtil.*; import static org.jetbrains.jet.j2k.ConverterUtil.isAnnotatedAsNotNull;
/** /**
* @author ignatov * @author ignatov
@@ -52,7 +52,8 @@ public class ElementVisitor extends JavaElementVisitor {
new IdentifierImpl(reference.getReferenceName()), new IdentifierImpl(reference.getReferenceName()),
types types
); );
} else { }
else {
String result = new IdentifierImpl(reference.getReferenceName()).toKotlin(); String result = new IdentifierImpl(reference.getReferenceName()).toKotlin();
PsiElement qualifier = reference.getQualifier(); PsiElement qualifier = reference.getQualifier();
while (qualifier != null) { while (qualifier != null) {
@@ -65,6 +65,7 @@ public class ExpressionVisitor extends StatementVisitor {
if (tokenType == JavaTokenType.GTGTGTEQ) secondOp = "ushr"; if (tokenType == JavaTokenType.GTGTGTEQ) secondOp = "ushr";
if (!secondOp.isEmpty()) // if not Kotlin operators if (!secondOp.isEmpty()) // if not Kotlin operators
{
myResult = new AssignmentExpression( myResult = new AssignmentExpression(
expressionToExpression(expression.getLExpression()), expressionToExpression(expression.getLExpression()),
new BinaryExpression( new BinaryExpression(
@@ -74,13 +75,15 @@ public class ExpressionVisitor extends StatementVisitor {
), ),
"=" "="
); );
else }
else {
myResult = new AssignmentExpression( myResult = new AssignmentExpression(
expressionToExpression(expression.getLExpression()), expressionToExpression(expression.getLExpression()),
expressionToExpression(expression.getRExpression()), expressionToExpression(expression.getRExpression()),
expression.getOperationSign().getText() // TODO expression.getOperationSign().getText() // TODO
); );
} }
}
@NotNull @NotNull
private static String getOperatorString(@NotNull IElementType tokenType) { private static String getOperatorString(@NotNull IElementType tokenType) {
@@ -115,12 +118,13 @@ public class ExpressionVisitor extends StatementVisitor {
public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) { public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) {
super.visitBinaryExpression(expression); super.visitBinaryExpression(expression);
if (expression.getOperationSign().getTokenType() == JavaTokenType.GTGTGT) if (expression.getOperationSign().getTokenType() == JavaTokenType.GTGTGT) {
myResult = new DummyMethodCallExpression( myResult = new DummyMethodCallExpression(
expressionToExpression(expression.getLOperand()), expressionToExpression(expression.getLOperand()),
"ushr", "ushr",
expressionToExpression(expression.getROperand())); expressionToExpression(expression.getROperand()));
else }
else {
myResult = myResult =
new BinaryExpression( new BinaryExpression(
expressionToExpression(expression.getLOperand()), expressionToExpression(expression.getLOperand()),
@@ -129,6 +133,7 @@ public class ExpressionVisitor extends StatementVisitor {
createConversions(expression, PsiType.BOOLEAN) createConversions(expression, PsiType.BOOLEAN)
); );
} }
}
@Override @Override
public void visitClassObjectAccessExpression(@NotNull PsiClassObjectAccessExpression expression) { public void visitClassObjectAccessExpression(@NotNull PsiClassObjectAccessExpression expression) {
@@ -178,20 +183,27 @@ public class ExpressionVisitor extends StatementVisitor {
final PsiType type = expression.getType(); final PsiType type = expression.getType();
if (type != null) { if (type != null) {
String canonicalTypeStr = type.getCanonicalText(); String canonicalTypeStr = type.getCanonicalText();
if (canonicalTypeStr.equals("double") || canonicalTypeStr.equals(JAVA_LANG_DOUBLE)) if (canonicalTypeStr.equals("double") || canonicalTypeStr.equals(JAVA_LANG_DOUBLE)) {
text = text.replace("D", "").replace("d", ""); text = text.replace("D", "").replace("d", "");
if (canonicalTypeStr.equals("float") || canonicalTypeStr.equals(JAVA_LANG_FLOAT)) }
if (canonicalTypeStr.equals("float") || canonicalTypeStr.equals(JAVA_LANG_FLOAT)) {
text = text.replace("F", "").replace("f", "") + "." + "flt"; text = text.replace("F", "").replace("f", "") + "." + "flt";
if (canonicalTypeStr.equals("long") || canonicalTypeStr.equals(JAVA_LANG_LONG)) }
if (canonicalTypeStr.equals("long") || canonicalTypeStr.equals(JAVA_LANG_LONG)) {
text = text.replace("L", "").replace("l", ""); text = text.replace("L", "").replace("l", "");
}
if (canonicalTypeStr.equals("int") || canonicalTypeStr.equals(JAVA_LANG_INTEGER)) // need for hex support if (canonicalTypeStr.equals("int") || canonicalTypeStr.equals(JAVA_LANG_INTEGER)) // need for hex support
{
text = value != null ? value.toString() : text; text = value != null ? value.toString() : text;
}
if (canonicalTypeStr.equals(JAVA_LANG_STRING)) if (canonicalTypeStr.equals(JAVA_LANG_STRING)) {
isQuotingNeeded = false; isQuotingNeeded = false;
if (canonicalTypeStr.equals("char") || canonicalTypeStr.equals(JAVA_LANG_CHARACTER)) }
if (canonicalTypeStr.equals("char") || canonicalTypeStr.equals(JAVA_LANG_CHARACTER)) {
isQuotingNeeded = false; isQuotingNeeded = false;
} }
}
myResult = new LiteralExpression(new IdentifierImpl(text, false, isQuotingNeeded)); myResult = new LiteralExpression(new IdentifierImpl(text, false, isQuotingNeeded));
} }
@@ -219,10 +231,13 @@ public class ExpressionVisitor extends StatementVisitor {
public void visitNewExpression(@NotNull PsiNewExpression expression) { public void visitNewExpression(@NotNull PsiNewExpression expression) {
super.visitNewExpression(expression); super.visitNewExpression(expression);
if (expression.getArrayInitializer() != null) // new Foo[] {Foo(1), Foo(2)} if (expression.getArrayInitializer() != null) // new Foo[] {Foo(1), Foo(2)}
{
myResult = createNewEmptyArray(expression); myResult = createNewEmptyArray(expression);
}
else if (expression.getArrayDimensions().length > 0) { // new Foo[5] else if (expression.getArrayDimensions().length > 0) { // new Foo[5]
myResult = createNewEmptyArrayWithoutInitialization(expression); myResult = createNewEmptyArrayWithoutInitialization(expression);
} else { // new Class(): common case }
else { // new Class(): common case
myResult = createNewClassExpression(expression); myResult = createNewClassExpression(expression);
} }
} }
@@ -246,7 +261,9 @@ public class ExpressionVisitor extends StatementVisitor {
} }
// is constructor secondary // is constructor secondary
final PsiJavaCodeReferenceElement reference = expression.getClassReference(); final PsiJavaCodeReferenceElement reference = expression.getClassReference();
final List<Type> typeParameters = reference != null ? typesToTypeList(reference.getTypeParameters()) : Collections.<Type>emptyList(); final List<Type> typeParameters = reference != null
? typesToTypeList(reference.getTypeParameters())
: Collections.<Type>emptyList();
return new CallChainExpression( return new CallChainExpression(
new IdentifierImpl(constructor.getName(), false), new IdentifierImpl(constructor.getName(), false),
new MethodCallExpression( new MethodCallExpression(
@@ -288,16 +305,18 @@ public class ExpressionVisitor extends StatementVisitor {
@Override @Override
public void visitPrefixExpression(@NotNull PsiPrefixExpression expression) { public void visitPrefixExpression(@NotNull PsiPrefixExpression expression) {
super.visitPrefixExpression(expression); super.visitPrefixExpression(expression);
if (expression.getOperationTokenType() == JavaTokenType.TILDE) if (expression.getOperationTokenType() == JavaTokenType.TILDE) {
myResult = new DummyMethodCallExpression( myResult = new DummyMethodCallExpression(
new ParenthesizedExpression(expressionToExpression(expression.getOperand())), "inv", Expression.EMPTY_EXPRESSION new ParenthesizedExpression(expressionToExpression(expression.getOperand())), "inv", Expression.EMPTY_EXPRESSION
); );
else }
else {
myResult = new PrefixOperator( myResult = new PrefixOperator(
getOperatorString(expression.getOperationSign().getTokenType()), getOperatorString(expression.getOperationSign().getTokenType()),
expressionToExpression(expression.getOperand()) expressionToExpression(expression.getOperand())
); );
} }
}
@Override @Override
public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) { public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
@@ -313,10 +332,12 @@ public class ExpressionVisitor extends StatementVisitor {
Expression identifier = new IdentifierImpl(expression.getReferenceName(), isNullable); Expression identifier = new IdentifierImpl(expression.getReferenceName(), isNullable);
final String __ = "__"; final String __ = "__";
if (hasReceiver) if (hasReceiver) {
identifier = new CallChainExpression(new IdentifierImpl(__, false), new IdentifierImpl(expression.getReferenceName(), isNullable)); identifier = new CallChainExpression(new IdentifierImpl(__, false), new IdentifierImpl(expression.getReferenceName(), isNullable));
else if (insideSecondaryConstructor && isThis) }
else if (insideSecondaryConstructor && isThis) {
identifier = new IdentifierImpl("val __ = " + className); // TODO: hack identifier = new IdentifierImpl("val __ = " + className); // TODO: hack
}
myResult = new CallChainExpression( myResult = new CallChainExpression(
expressionToExpression(expression.getQualifierExpression()), expressionToExpression(expression.getQualifierExpression()),
@@ -332,10 +353,11 @@ public class ExpressionVisitor extends StatementVisitor {
final PsiClass containingClass = ((PsiMethod) context).getContainingClass(); final PsiClass containingClass = ((PsiMethod) context).getContainingClass();
if (containingClass != null) { if (containingClass != null) {
final PsiIdentifier identifier = containingClass.getNameIdentifier(); final PsiIdentifier identifier = containingClass.getNameIdentifier();
if (identifier != null) if (identifier != null) {
return identifier.getText(); return identifier.getText();
} }
} }
}
context = context.getContext(); context = context.getContext();
} }
return ""; return "";
@@ -348,9 +370,10 @@ public class ExpressionVisitor extends StatementVisitor {
if (context instanceof PsiClass) { if (context instanceof PsiClass) {
final PsiClass containingClass = (PsiClass) context; final PsiClass containingClass = (PsiClass) context;
final PsiIdentifier identifier = containingClass.getNameIdentifier(); final PsiIdentifier identifier = containingClass.getNameIdentifier();
if (identifier != null) if (identifier != null) {
return identifier.getText(); return identifier.getText();
} }
}
context = context.getContext(); context = context.getContext();
} }
return ""; return "";
@@ -372,8 +395,9 @@ public class ExpressionVisitor extends StatementVisitor {
private static boolean isInsideSecondaryConstructor(@NotNull PsiReferenceExpression expression) { private static boolean isInsideSecondaryConstructor(@NotNull PsiReferenceExpression expression) {
PsiElement context = expression.getContext(); PsiElement context = expression.getContext();
while (context != null) { while (context != null) {
if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) {
return !isConstructorPrimary((PsiMethod) context); return !isConstructorPrimary((PsiMethod) context);
}
context = context.getContext(); context = context.getContext();
} }
return false; return false;
@@ -382,8 +406,9 @@ public class ExpressionVisitor extends StatementVisitor {
private static boolean isInsidePrimaryConstructor(@NotNull PsiExpression expression) { private static boolean isInsidePrimaryConstructor(@NotNull PsiExpression expression) {
PsiElement context = expression.getContext(); PsiElement context = expression.getContext();
while (context != null) { while (context != null) {
if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) {
return isConstructorPrimary((PsiMethod) context); return isConstructorPrimary((PsiMethod) context);
}
context = context.getContext(); context = context.getContext();
} }
return false; return false;
@@ -393,8 +418,9 @@ public class ExpressionVisitor extends StatementVisitor {
private static PsiClass getContainingClass(@NotNull PsiExpression expression) { private static PsiClass getContainingClass(@NotNull PsiExpression expression) {
PsiElement context = expression.getContext(); PsiElement context = expression.getContext();
while (context != null) { while (context != null) {
if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) if (context instanceof PsiMethod && ((PsiMethod) context).isConstructor()) {
return ((PsiMethod) context).getContainingClass(); return ((PsiMethod) context).getContainingClass();
}
context = context.getContext(); context = context.getContext();
} }
return null; return null;
@@ -404,9 +430,10 @@ public class ExpressionVisitor extends StatementVisitor {
for (PsiReference r : expression.getReferences()) for (PsiReference r : expression.getReferences())
if (r.getCanonicalText().equals("this")) { if (r.getCanonicalText().equals("this")) {
final PsiElement res = r.resolve(); final PsiElement res = r.resolve();
if (res != null && res instanceof PsiMethod && ((PsiMethod) res).isConstructor()) if (res != null && res instanceof PsiMethod && ((PsiMethod) res).isConstructor()) {
return true; return true;
} }
}
return false; return false;
} }
@@ -15,15 +15,19 @@ import static org.jetbrains.jet.j2k.visitors.TypeVisitor.JAVA_LANG_OBJECT;
public class ExpressionVisitorForDirectObjectInheritors extends ExpressionVisitor { public class ExpressionVisitorForDirectObjectInheritors extends ExpressionVisitor {
@Override @Override
public void visitMethodCallExpression(@NotNull final PsiMethodCallExpression expression) { public void visitMethodCallExpression(@NotNull final PsiMethodCallExpression expression) {
if (superMethodInvocation(expression.getMethodExpression(), "hashCode")) if (superMethodInvocation(expression.getMethodExpression(), "hashCode")) {
myResult = new DummyMethodCallExpression(new IdentifierImpl("System"), "identityHashCode", new IdentifierImpl("this")); myResult = new DummyMethodCallExpression(new IdentifierImpl("System"), "identityHashCode", new IdentifierImpl("this"));
else if (superMethodInvocation(expression.getMethodExpression(), "equals")) }
else if (superMethodInvocation(expression.getMethodExpression(), "equals")) {
myResult = new DummyMethodCallExpression(new IdentifierImpl("this"), "identityEquals", Converter.elementToElement(expression.getArgumentList())); myResult = new DummyMethodCallExpression(new IdentifierImpl("this"), "identityEquals", Converter.elementToElement(expression.getArgumentList()));
else if (superMethodInvocation(expression.getMethodExpression(), "toString")) }
else if (superMethodInvocation(expression.getMethodExpression(), "toString")) {
myResult = new DummyStringExpression(String.format("getJavaClass<%s>.getName() + '@' + Integer.toHexString(hashCode())", getClassName(expression.getMethodExpression()))); myResult = new DummyStringExpression(String.format("getJavaClass<%s>.getName() + '@' + Integer.toHexString(hashCode())", getClassName(expression.getMethodExpression())));
else }
else {
super.visitMethodCallExpression(expression); super.visitMethodCallExpression(expression);
} }
}
@Override @Override
public void visitReferenceExpression(@NotNull final PsiReferenceExpression expression) { public void visitReferenceExpression(@NotNull final PsiReferenceExpression expression) {
@@ -36,10 +40,11 @@ public class ExpressionVisitorForDirectObjectInheritors extends ExpressionVisito
if (referenceName != null && referenceName.equals(methodName)) { if (referenceName != null && referenceName.equals(methodName)) {
if (qualifierExpression instanceof PsiSuperExpression) { if (qualifierExpression instanceof PsiSuperExpression) {
PsiType type = qualifierExpression.getType(); PsiType type = qualifierExpression.getType();
if (type != null && type.getCanonicalText().equals(JAVA_LANG_OBJECT)) if (type != null && type.getCanonicalText().equals(JAVA_LANG_OBJECT)) {
return true; return true;
} }
} }
}
return false; return false;
} }
} }
@@ -48,24 +48,28 @@ public class StatementVisitor extends ElementVisitor {
@Override @Override
public void visitBreakStatement(@NotNull PsiBreakStatement statement) { public void visitBreakStatement(@NotNull PsiBreakStatement statement) {
super.visitBreakStatement(statement); super.visitBreakStatement(statement);
if (statement.getLabelIdentifier() == null) if (statement.getLabelIdentifier() == null) {
myResult = new BreakStatement(); myResult = new BreakStatement();
else }
else {
myResult = new BreakStatement( myResult = new BreakStatement(
identifierToIdentifier(statement.getLabelIdentifier()) identifierToIdentifier(statement.getLabelIdentifier())
); );
} }
}
@Override @Override
public void visitContinueStatement(@NotNull PsiContinueStatement statement) { public void visitContinueStatement(@NotNull PsiContinueStatement statement) {
super.visitContinueStatement(statement); super.visitContinueStatement(statement);
if (statement.getLabelIdentifier() == null) if (statement.getLabelIdentifier() == null) {
myResult = new ContinueStatement(); myResult = new ContinueStatement();
else }
else {
myResult = new ContinueStatement( myResult = new ContinueStatement(
identifierToIdentifier(statement.getLabelIdentifier()) identifierToIdentifier(statement.getLabelIdentifier())
); );
} }
}
@Override @Override
public void visitDeclarationStatement(@NotNull PsiDeclarationStatement statement) { public void visitDeclarationStatement(@NotNull PsiDeclarationStatement statement) {
@@ -111,8 +115,10 @@ public class StatementVisitor extends ElementVisitor {
final PsiExpression condition = statement.getCondition(); final PsiExpression condition = statement.getCondition();
final PsiStatement body = statement.getBody(); final PsiStatement body = statement.getBody();
final PsiLocalVariable firstChild = initialization != null && initialization.getFirstChild() instanceof PsiLocalVariable ? final PsiLocalVariable firstChild = initialization != null && initialization.getFirstChild() instanceof PsiLocalVariable
(PsiLocalVariable) initialization.getFirstChild() : null; ?
(PsiLocalVariable) initialization.getFirstChild()
: null;
int bodyWriteCount = countWritingAccesses(firstChild, body); int bodyWriteCount = countWritingAccesses(firstChild, body);
int conditionWriteCount = countWritingAccesses(firstChild, condition); int conditionWriteCount = countWritingAccesses(firstChild, condition);
@@ -147,7 +153,8 @@ public class StatementVisitor extends ElementVisitor {
endExpression, endExpression,
statementToStatement(body) statementToStatement(body)
); );
} else { // common case: while loop instead of for loop }
else { // common case: while loop instead of for loop
List<Statement> forStatements = new LinkedList<Statement>(); List<Statement> forStatements = new LinkedList<Statement>();
forStatements.add(statementToStatement(initialization)); forStatements.add(statementToStatement(initialization));
forStatements.add(new WhileStatement( forStatements.add(new WhileStatement(
@@ -218,7 +225,9 @@ public class StatementVisitor extends ElementVisitor {
@NotNull @NotNull
private static List<CaseContainer> switchBodyToCases(@Nullable final PsiCodeBlock body) { private static List<CaseContainer> switchBodyToCases(@Nullable final PsiCodeBlock body) {
final List<List<PsiStatement>> cases = splitToCases(body); final List<List<PsiStatement>> cases = splitToCases(body);
final List<PsiStatement> allSwitchStatements = body != null ? Arrays.asList(body.getStatements()) : Collections.<PsiStatement>emptyList(); final List<PsiStatement> allSwitchStatements = body != null
? Arrays.asList(body.getStatements())
: Collections.<PsiStatement>emptyList();
List<CaseContainer> result = new LinkedList<CaseContainer>(); List<CaseContainer> result = new LinkedList<CaseContainer>();
List<Statement> pendingLabels = new LinkedList<Statement>(); List<Statement> pendingLabels = new LinkedList<Statement>();
@@ -241,12 +250,16 @@ public class StatementVisitor extends ElementVisitor {
); );
result.add(new CaseContainer(pendingLabels, statements)); result.add(new CaseContainer(pendingLabels, statements));
pendingLabels = new LinkedList<Statement>(); pendingLabels = new LinkedList<Statement>();
} else { }
else {
result.add(new CaseContainer(pendingLabels, statementsToStatementList(slice))); result.add(new CaseContainer(pendingLabels, statementsToStatementList(slice)));
pendingLabels = new LinkedList<Statement>(); pendingLabels = new LinkedList<Statement>();
} }
} else // ls.size() == 1 }
else // ls.size() == 1
{
pendingLabels.add(statementToStatement(label)); pendingLabels.add(statementToStatement(label));
}
i += ls.size(); i += ls.size();
} }
return result; return result;
@@ -254,8 +267,9 @@ public class StatementVisitor extends ElementVisitor {
private static boolean containsBreak(@NotNull final List<PsiStatement> slice) { private static boolean containsBreak(@NotNull final List<PsiStatement> slice) {
for (PsiStatement s : slice) for (PsiStatement s : slice)
if (s instanceof PsiBreakStatement) if (s instanceof PsiBreakStatement) {
return true; return true;
}
return false; return false;
} }
@@ -264,11 +278,13 @@ public class StatementVisitor extends ElementVisitor {
List<PsiStatement> result = new LinkedList<PsiStatement>(); List<PsiStatement> result = new LinkedList<PsiStatement>();
for (int i = start; i < allStatements.size(); i++) { for (int i = start; i < allStatements.size(); i++) {
PsiStatement s = allStatements.get(i); PsiStatement s = allStatements.get(i);
if (s instanceof PsiBreakStatement || s instanceof PsiReturnStatement) if (s instanceof PsiBreakStatement || s instanceof PsiReturnStatement) {
return result; return result;
if (!(s instanceof PsiSwitchLabelStatement)) }
if (!(s instanceof PsiSwitchLabelStatement)) {
result.add(s); result.add(s);
} }
}
return result; return result;
} }
@@ -280,8 +296,9 @@ public class StatementVisitor extends ElementVisitor {
if (body != null) { if (body != null) {
for (PsiStatement s : body.getStatements()) { for (PsiStatement s : body.getStatements()) {
if (s instanceof PsiSwitchLabelStatement) { if (s instanceof PsiSwitchLabelStatement) {
if (isFirst) if (isFirst) {
isFirst = false; isFirst = false;
}
else { else {
cases.add(currentCaseStatements); cases.add(currentCaseStatements);
currentCaseStatements = new LinkedList<PsiStatement>(); currentCaseStatements = new LinkedList<PsiStatement>();
@@ -25,9 +25,10 @@ public class SuperVisitor extends JavaRecursiveElementVisitor {
@Override @Override
public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) { public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression); super.visitMethodCallExpression(expression);
if (isSuper(expression.getMethodExpression())) if (isSuper(expression.getMethodExpression())) {
myResolvedSuperCallParameters.add(expression.getArgumentList()); myResolvedSuperCallParameters.add(expression.getArgumentList());
} }
}
static boolean isSuper(@NotNull PsiReference r) { static boolean isSuper(@NotNull PsiReference r) {
if (r.getCanonicalText().equals("super")) { if (r.getCanonicalText().equals("super")) {
@@ -18,18 +18,20 @@ public class ThisVisitor extends JavaRecursiveElementVisitor {
for (PsiReference r : expression.getReferences()) for (PsiReference r : expression.getReferences())
if (r.getCanonicalText().equals("this")) { if (r.getCanonicalText().equals("this")) {
final PsiElement res = r.resolve(); final PsiElement res = r.resolve();
if (res != null && res instanceof PsiMethod && ((PsiMethod) res).isConstructor()) if (res != null && res instanceof PsiMethod && ((PsiMethod) res).isConstructor()) {
myResolvedConstructors.add((PsiMethod) res); myResolvedConstructors.add((PsiMethod) res);
} }
} }
}
@Nullable @Nullable
public PsiMethod getPrimaryConstructor() { public PsiMethod getPrimaryConstructor() {
if (myResolvedConstructors.size() > 0) { if (myResolvedConstructors.size() > 0) {
PsiMethod first = myResolvedConstructors.toArray(new PsiMethod[myResolvedConstructors.size()])[0]; PsiMethod first = myResolvedConstructors.toArray(new PsiMethod[myResolvedConstructors.size()])[0];
for (PsiMethod m : myResolvedConstructors) for (PsiMethod m : myResolvedConstructors)
if (m.hashCode() != first.hashCode()) if (m.hashCode() != first.hashCode()) {
return null; return null;
}
return first; return first;
} }
return null; return null;
@@ -41,19 +41,23 @@ public class TypeVisitor extends PsiTypeVisitor<Type> {
final String name = primitiveType.getCanonicalText(); final String name = primitiveType.getCanonicalText();
final IdentifierImpl identifier = new IdentifierImpl(name); final IdentifierImpl identifier = new IdentifierImpl(name);
if (name.equals("void")) if (name.equals("void")) {
myResult = new PrimitiveType(new IdentifierImpl("Unit")); myResult = new PrimitiveType(new IdentifierImpl("Unit"));
else if (Node.PRIMITIVE_TYPES.contains(name)) }
else if (Node.PRIMITIVE_TYPES.contains(name)) {
myResult = new PrimitiveType(new IdentifierImpl(AstUtil.upperFirstCharacter(name))); myResult = new PrimitiveType(new IdentifierImpl(AstUtil.upperFirstCharacter(name)));
else }
else {
myResult = new PrimitiveType(identifier); myResult = new PrimitiveType(identifier);
}
return super.visitPrimitiveType(primitiveType); return super.visitPrimitiveType(primitiveType);
} }
@Override @Override
public Type visitArrayType(@NotNull PsiArrayType arrayType) { public Type visitArrayType(@NotNull PsiArrayType arrayType) {
if (myResult == Type.EMPTY_TYPE) if (myResult == Type.EMPTY_TYPE) {
myResult = new ArrayType(typeToType(arrayType.getComponentType())); myResult = new ArrayType(typeToType(arrayType.getComponentType()));
}
return super.visitArrayType(arrayType); return super.visitArrayType(arrayType);
} }
@@ -62,10 +66,12 @@ public class TypeVisitor extends PsiTypeVisitor<Type> {
final IdentifierImpl identifier = constructClassTypeIdentifier(classType); final IdentifierImpl identifier = constructClassTypeIdentifier(classType);
final List<Type> resolvedClassTypeParams = createRawTypesForResolvedReference(classType); final List<Type> resolvedClassTypeParams = createRawTypesForResolvedReference(classType);
if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) {
myResult = new ClassType(identifier, resolvedClassTypeParams); myResult = new ClassType(identifier, resolvedClassTypeParams);
else }
else {
myResult = new ClassType(identifier, typesToTypeList(classType.getParameters())); myResult = new ClassType(identifier, typesToTypeList(classType.getParameters()));
}
return super.visitClassType(classType); return super.visitClassType(classType);
} }
@@ -75,18 +81,22 @@ public class TypeVisitor extends PsiTypeVisitor<Type> {
if (psiClass != null) { if (psiClass != null) {
String qualifiedName = psiClass.getQualifiedName(); String qualifiedName = psiClass.getQualifiedName();
if (qualifiedName != null) { if (qualifiedName != null) {
if (!qualifiedName.equals("java.lang.Object") && Converter.hasSetting("fqn")) if (!qualifiedName.equals("java.lang.Object") && Converter.hasSetting("fqn")) {
return new IdentifierImpl(qualifiedName); return new IdentifierImpl(qualifiedName);
if (qualifiedName.equals(JAVA_LANG_ITERABLE)) }
if (qualifiedName.equals(JAVA_LANG_ITERABLE)) {
return new IdentifierImpl(JAVA_LANG_ITERABLE); return new IdentifierImpl(JAVA_LANG_ITERABLE);
if (qualifiedName.equals(JAVA_UTIL_ITERATOR)) }
if (qualifiedName.equals(JAVA_UTIL_ITERATOR)) {
return new IdentifierImpl(JAVA_UTIL_ITERATOR); return new IdentifierImpl(JAVA_UTIL_ITERATOR);
} }
} }
}
final String classTypeName = createQualifiedName(classType); final String classTypeName = createQualifiedName(classType);
if (classTypeName.isEmpty()) if (classTypeName.isEmpty()) {
return new IdentifierImpl(getClassTypeName(classType)); return new IdentifierImpl(getClassTypeName(classType));
}
return new IdentifierImpl(classTypeName); return new IdentifierImpl(classTypeName);
} }
@@ -119,15 +129,18 @@ public class TypeVisitor extends PsiTypeVisitor<Type> {
if (resolve != null) { if (resolve != null) {
if (resolve instanceof PsiClass) if (resolve instanceof PsiClass)
//noinspection UnusedDeclaration //noinspection UnusedDeclaration
{
for (PsiTypeParameter p : ((PsiClass) resolve).getTypeParameters()) { for (PsiTypeParameter p : ((PsiClass) resolve).getTypeParameters()) {
Type boundType = p.getSuperTypes().length > 0 ? Type boundType = p.getSuperTypes().length > 0 ?
new ClassType(new IdentifierImpl(getClassTypeName(p.getSuperTypes()[0])), typesToTypeList(p.getSuperTypes()[0].getParameters()), true) : new ClassType(new IdentifierImpl(getClassTypeName(p.getSuperTypes()[0])), typesToTypeList(p.getSuperTypes()[0].getParameters()), true)
:
new StarProjectionType(); new StarProjectionType();
typeParams.add(boundType); typeParams.add(boundType);
} }
} }
} }
}
return typeParams; return typeParams;
} }
@@ -148,12 +161,15 @@ public class TypeVisitor extends PsiTypeVisitor<Type> {
@Override @Override
public Type visitWildcardType(@NotNull PsiWildcardType wildcardType) { public Type visitWildcardType(@NotNull PsiWildcardType wildcardType) {
if (wildcardType.isExtends()) if (wildcardType.isExtends()) {
myResult = new OutProjectionType(typeToType(wildcardType.getExtendsBound())); myResult = new OutProjectionType(typeToType(wildcardType.getExtendsBound()));
else if (wildcardType.isSuper()) }
else if (wildcardType.isSuper()) {
myResult = new InProjectionType(typeToType(wildcardType.getSuperBound())); myResult = new InProjectionType(typeToType(wildcardType.getSuperBound()));
else }
else {
myResult = new StarProjectionType(); myResult = new StarProjectionType();
}
return super.visitWildcardType(wildcardType); return super.visitWildcardType(wildcardType);
} }
@@ -62,7 +62,8 @@ abstract class TestCaseBuilder {
return extensionFilter.accept(file, s) && filter.accept(file, s); return extensionFilter.accept(file, s) && filter.accept(file, s);
} }
}; };
} else { }
else {
resultFilter = extensionFilter; resultFilter = extensionFilter;
} }
File dir = new File(baseDataDir + dataPath); File dir = new File(baseDataDir + dataPath);