From 4746bcd8f1da9a9a2fc71594615f009ed8727047 Mon Sep 17 00:00:00 2001 From: Kun Li Date: Wed, 8 Nov 2023 17:00:26 -0800 Subject: [PATCH] Clean up warnings --- .../org/openrewrite/kotlin/AddImport.java | 4 +- .../org/openrewrite/kotlin/Assertions.java | 28 ++--- .../openrewrite/kotlin/FindKotlinSources.java | 22 ++-- .../org/openrewrite/kotlin/KotlinParser.java | 4 +- .../cleanup/ImplicitParameterInLambda.java | 4 +- .../kotlin/internal/KotlinPrinter.java | 46 ++++--- .../internal/KotlinTreeParserVisitor.java | 34 +---- .../kotlin/internal/PsiTreePrinter.java | 21 ++-- .../java/org/openrewrite/kotlin/tree/K.java | 21 +++- .../openrewrite/kotlin/tree/KContainer.java | 1 + .../openrewrite/kotlin/tree/KLeftPadded.java | 2 + .../openrewrite/kotlin/tree/KRightPadded.java | 1 + .../kotlin/KotlinTypeIrSignatureBuilder.kt | 23 ++-- .../openrewrite/kotlin/KotlinTypeMapping.kt | 118 +++++++++--------- .../kotlin/internal/PsiElementAssociations.kt | 15 +-- .../internal/PsiElementIrAssociations.kt | 1 + .../kotlin/tree/AssignmentTest.java | 1 + .../org/openrewrite/kotlin/tree/CRLFTest.java | 1 - .../openrewrite/kotlin/tree/UnaryTest.java | 1 - 19 files changed, 160 insertions(+), 188 deletions(-) diff --git a/src/main/java/org/openrewrite/kotlin/AddImport.java b/src/main/java/org/openrewrite/kotlin/AddImport.java index a66840256..0267918f1 100644 --- a/src/main/java/org/openrewrite/kotlin/AddImport.java +++ b/src/main/java/org/openrewrite/kotlin/AddImport.java @@ -188,7 +188,7 @@ public AddImport(@Nullable String packageName, String typeName, @Nullable String // ImportLayoutStyle::addImport adds always `\n` as newlines. Checking if we need to fix them GeneralFormatStyle generalFormatStyle = Optional.ofNullable(cu.getStyle(GeneralFormatStyle.class)) .orElse(autodetectGeneralFormatStyle(cu)); - newImports = checkCRLF(cu, newImports, generalFormatStyle); + newImports = checkCRLF(newImports, generalFormatStyle); cu = cu.getPadding().withImports(newImports); @@ -204,7 +204,7 @@ public AddImport(@Nullable String packageName, String typeName, @Nullable String } // TODO refactor ImportLayoutStyle so that this method can be removed - private List> checkCRLF(JavaSourceFile cu, List> newImports, GeneralFormatStyle generalFormatStyle) { + private List> checkCRLF(List> newImports, GeneralFormatStyle generalFormatStyle) { if (generalFormatStyle.isUseCRLFNewLines()) { return ListUtils.map(newImports, rp -> rp.map( i -> i.withPrefix(i.getPrefix().withWhitespace(i.getPrefix().getWhitespace() diff --git a/src/main/java/org/openrewrite/kotlin/Assertions.java b/src/main/java/org/openrewrite/kotlin/Assertions.java index e0884969c..2704669a5 100644 --- a/src/main/java/org/openrewrite/kotlin/Assertions.java +++ b/src/main/java/org/openrewrite/kotlin/Assertions.java @@ -43,6 +43,7 @@ import static org.openrewrite.java.Assertions.sourceSet; import static org.openrewrite.test.SourceSpecs.dir; +@SuppressWarnings({"unused", "unchecked", "OptionalGetWithoutIsPresent", "DataFlowIssue"}) public final class Assertions { private Assertions() { @@ -56,6 +57,7 @@ static void customizeExecutionContext(ExecutionContext ctx) { // A helper method to adjust white spaces in the input kotlin source to help us detect parse-to-print idempotent issues // Just change from `before` to `adjustSpaces(before)` below in the `kotlin()` method to test locally + @SuppressWarnings("IfStatementWithIdenticalBranches") @Nullable private static String adjustSpaces(@Nullable String input) { if (input == null) { @@ -164,22 +166,20 @@ private static void acceptSpec(Consumer> spec, Sou } public static ThrowingConsumer isFullyParsed() { - return cu -> { - new KotlinIsoVisitor() { - @Override - public J visitUnknown(J.Unknown unknown, Integer integer) { - throw new AssertionFailedError("Parsing error, J.Unknown detected"); - } + return cu -> new KotlinIsoVisitor() { + @Override + public J visitUnknown(J.Unknown unknown, Integer integer) { + throw new AssertionFailedError("Parsing error, J.Unknown detected"); + } - @Override - public Space visitSpace(Space space, Space.Location loc, Integer integer) { - if (!space.getWhitespace().trim().isEmpty()) { - throw new AssertionFailedError("Parsing error detected, whitespace contains non-whitespace characters: " + space.getWhitespace()); - } - return super.visitSpace(space, loc, integer); + @Override + public Space visitSpace(Space space, Space.Location loc, Integer integer) { + if (!space.getWhitespace().trim().isEmpty()) { + throw new AssertionFailedError("Parsing error detected, whitespace contains non-whitespace characters: " + space.getWhitespace()); } - }.visit(cu, 0); - }; + return super.visitSpace(space, loc, integer); + } + }.visit(cu, 0); } public static UncheckedConsumer> spaceConscious() { diff --git a/src/main/java/org/openrewrite/kotlin/FindKotlinSources.java b/src/main/java/org/openrewrite/kotlin/FindKotlinSources.java index 332592850..92a50dcd7 100644 --- a/src/main/java/org/openrewrite/kotlin/FindKotlinSources.java +++ b/src/main/java/org/openrewrite/kotlin/FindKotlinSources.java @@ -48,20 +48,26 @@ public Tree visit(@Nullable Tree tree, ExecutionContext ctx) { if(tree instanceof SourceFile) { SourceFile sourceFile = (SourceFile) tree; if (sourceFile.getSourcePath().toString().endsWith(".kt")) { - KotlinSourceFile.SourceFileType sourceFileType = null; - if (sourceFile instanceof K.CompilationUnit) { - sourceFileType = KotlinSourceFile.SourceFileType.Kotlin; - } else if (sourceFile instanceof Quark) { - sourceFileType = KotlinSourceFile.SourceFileType.Quark; - } else if (sourceFile instanceof PlainText) { - sourceFileType = KotlinSourceFile.SourceFileType.PlainText; - } + KotlinSourceFile.SourceFileType sourceFileType = getSourceFileType(sourceFile); kotlinSourceFile.insertRow(ctx, new KotlinSourceFile.Row(sourceFile.getSourcePath().toString(), sourceFileType)); return SearchResult.found(sourceFile); } } return tree; } + + @Nullable + private KotlinSourceFile.SourceFileType getSourceFileType(SourceFile sourceFile) { + KotlinSourceFile.SourceFileType sourceFileType = null; + if (sourceFile instanceof K.CompilationUnit) { + sourceFileType = KotlinSourceFile.SourceFileType.Kotlin; + } else if (sourceFile instanceof Quark) { + sourceFileType = KotlinSourceFile.SourceFileType.Quark; + } else if (sourceFile instanceof PlainText) { + sourceFileType = KotlinSourceFile.SourceFileType.PlainText; + } + return sourceFileType; + } }; } } diff --git a/src/main/java/org/openrewrite/kotlin/KotlinParser.java b/src/main/java/org/openrewrite/kotlin/KotlinParser.java index e2f24880b..82694526f 100644 --- a/src/main/java/org/openrewrite/kotlin/KotlinParser.java +++ b/src/main/java/org/openrewrite/kotlin/KotlinParser.java @@ -44,8 +44,6 @@ import org.jetbrains.kotlin.com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile; import org.jetbrains.kotlin.config.*; -import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory; -import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector; import org.jetbrains.kotlin.fir.DependencyListForCliModule; import org.jetbrains.kotlin.fir.FirSession; import org.jetbrains.kotlin.fir.declarations.FirFile; @@ -100,6 +98,7 @@ import static org.jetbrains.kotlin.config.JVMConfigurationKeys.LINK_VIA_SIGNATURES; import static org.jetbrains.kotlin.incremental.IncrementalFirJvmCompilerRunnerKt.configureBaseRoots; +@SuppressWarnings("CommentedOutCode") @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class KotlinParser implements Parser { public static final String SKIP_SOURCE_SET_TYPE_GENERATION = "org.openrewrite.kotlin.skipSourceSetTypeGeneration"; @@ -394,7 +393,6 @@ public CompiledSource parse(List sources, Disposable disposable, E kotlinSources.add(new KotlinSource(source, file, cRLFLocations)); } - BaseDiagnosticsCollector diagnosticsReporter = DiagnosticReporterFactory.INSTANCE.createReporter(false); Function1 providerFunction1 = environment::createPackagePartProvider; VfsBasedProjectEnvironment projectEnvironment = new VfsBasedProjectEnvironment( environment.getProject(), diff --git a/src/main/java/org/openrewrite/kotlin/cleanup/ImplicitParameterInLambda.java b/src/main/java/org/openrewrite/kotlin/cleanup/ImplicitParameterInLambda.java index dab430e1d..f6abd7839 100644 --- a/src/main/java/org/openrewrite/kotlin/cleanup/ImplicitParameterInLambda.java +++ b/src/main/java/org/openrewrite/kotlin/cleanup/ImplicitParameterInLambda.java @@ -89,9 +89,7 @@ private static boolean isParameterExplicitIt(J.Lambda lambda) { } J.VariableDeclarations.NamedVariable v = vs.getVariables().get(0); - if ("it".equals(v.getSimpleName())) { - return true; - } + return "it".equals(v.getSimpleName()); } return false; } diff --git a/src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java b/src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java index c44dc8c3c..07dd01fcf 100755 --- a/src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java +++ b/src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java @@ -39,6 +39,7 @@ import java.util.Optional; import java.util.function.UnaryOperator; +@SuppressWarnings("SwitchStatementWithTooFewBranches") public class KotlinPrinter

extends KotlinVisitor> { private final KotlinJavaPrinter

delegate; @@ -253,7 +254,7 @@ public J visitFunctionTypeParameter(K.FunctionType.Parameter parameter, PrintOut @Override public J visitKReturn(K.KReturn kReturn, PrintOutputCapture

p) { // backwards compatibility: leave this in until `K.KReturn#annotations` has been deleted - visit(kReturn.getAnnotations(), p); + // visit(kReturn.getAnnotations(), p); J.Return return_ = kReturn.getExpression(); if (kReturn.getLabel() != null) { beforeSyntax(return_, Space.Location.RETURN_PREFIX, p); @@ -618,15 +619,7 @@ private J.ClassDeclaration visitClassDeclaration0(J.ClassDeclaration classDecl, visitModifier(m, p); } - String kind; - if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Class || classDecl.getKind() == J.ClassDeclaration.Kind.Type.Enum || classDecl.getKind() == J.ClassDeclaration.Kind.Type.Annotation) { - kind = "class"; - } else if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Interface) { - kind = "interface"; - } else { - throw new UnsupportedOperationException("Class kind is not supported: " + classDecl.getKind()); - } - + String kind = getClassKind(classDecl); visit(classDecl.getAnnotations().getKind().getAnnotations(), p); visitSpace(classDecl.getAnnotations().getKind().getPrefix(), Space.Location.CLASS_KIND, p); @@ -671,7 +664,7 @@ private J.ClassDeclaration visitClassDeclaration0(J.ClassDeclaration classDecl, if (classDecl.getImplements() != null) { JContainer container = classDecl.getPadding().getImplements(); - beforeSyntax(container.getBefore(), container.getMarkers(), JContainer.Location.IMPLEMENTS.getBeforeLocation(), p); + beforeSyntax(Objects.requireNonNull(container).getBefore(), container.getMarkers(), JContainer.Location.IMPLEMENTS.getBeforeLocation(), p); p.append(":"); List> nodes = container.getPadding().getElements(); for (int i = 0; i < nodes.size(); i++) { @@ -991,11 +984,6 @@ private void visitArgumentsContainer(JContainer argContainer, Space. p.append(','); } - SpreadArgument spread = arg.getElement().getMarkers().findFirst(SpreadArgument.class).orElse(null); - if (spread != null) { - kotlinPrinter.visitSpace(spread.getPrefix(), KSpace.Location.SPREAD_ARGUMENT_PREFIX, p); - p.append('*'); - } visitRightPadded(arg, JRightPadded.Location.METHOD_INVOCATION_ARGUMENT, p); } @@ -1011,13 +999,11 @@ public J visitNewClass(J.NewClass newClass, PrintOutputCapture

p) { KObject kObject = newClass.getMarkers().findFirst(KObject.class).orElse(null); if (kObject != null) { p.append("object"); - kotlinPrinter.visitSpace(kObject.getPrefix(), KSpace.Location.OBJECT_PREFIX, p); + // kotlinPrinter.visitSpace(kObject.getPrefix(), KSpace.Location.OBJECT_PREFIX, p); } - TypeReferencePrefix typeReferencePrefix = newClass.getMarkers().findFirst(TypeReferencePrefix.class).orElse(null); - if (typeReferencePrefix != null) { - kotlinPrinter.visitSpace(typeReferencePrefix.getPrefix(), KSpace.Location.TYPE_REFERENCE_PREFIX, p); - } + newClass.getMarkers().findFirst(TypeReferencePrefix.class).ifPresent(typeReferencePrefix -> + kotlinPrinter.visitSpace(typeReferencePrefix.getPrefix(), KSpace.Location.TYPE_REFERENCE_PREFIX, p)); if (kObject != null && newClass.getClazz() != null) { p.append(":"); @@ -1306,12 +1292,22 @@ protected void afterSyntax(J j, PrintOutputCapture

p) { } } + @NotNull + private static String getClassKind(J.ClassDeclaration classDecl) { + String kind; + if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Class || classDecl.getKind() == J.ClassDeclaration.Kind.Type.Enum || classDecl.getKind() == J.ClassDeclaration.Kind.Type.Annotation) { + kind = "class"; + } else if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Interface) { + kind = "interface"; + } else { + throw new UnsupportedOperationException("Class kind is not supported: " + classDecl.getKind()); + } + return kind; + } + private void trailingMarkers(Markers markers, PrintOutputCapture

p) { for (Marker marker : markers.getMarkers()) { - if (marker instanceof CheckNotNull) { - KotlinPrinter.this.visitSpace(((CheckNotNull) marker).getPrefix(), KSpace.Location.CHECK_NOT_NULL_PREFIX, p); - p.append("!!"); - } else if (marker instanceof IsNullable) { + if (marker instanceof IsNullable) { KotlinPrinter.this.visitSpace(((IsNullable) marker).getPrefix(), KSpace.Location.TYPE_REFERENCE_PREFIX, p); p.append("?"); } diff --git a/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java b/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java index 8bde65a88..deab76ead 100644 --- a/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java +++ b/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java @@ -66,6 +66,7 @@ /** * PSI based parser */ +@SuppressWarnings({"DataFlowIssue", "ConstantValue"}) public class KotlinTreeParserVisitor extends KtVisitor { private final KotlinSource kotlinSource; private final PsiElementAssociations psiElementAssociations; @@ -1643,9 +1644,7 @@ public J visitKtFile(KtFile file, ExecutionContext data) { List> statements = new ArrayList<>(file.getDeclarations().size()); List declarations = file.getDeclarations(); - for (int i = 0; i < declarations.size(); i++) { - boolean last = i == declarations.size() - 1; - KtDeclaration declaration = declarations.get(i); + for (KtDeclaration declaration : declarations) { Statement statement = convertToStatement(declaration.accept(this, data)); statements.add(padRight(statement, Space.EMPTY)); } @@ -3514,27 +3513,16 @@ private Space infix(@Nullable PsiElement element, @Nullable Set cons } private Space endFix(@Nullable PsiElement element) { - return endFix(element, null); - } - - private Space endFix(@Nullable PsiElement element, @Nullable Set consumedSpaces) { if (element == null) { return Space.EMPTY; } Space end = endFix(findLastNotSpaceChild(element)); PsiElement lastSpace = findLastSpaceChild(element); - if (consumedSpaces != null && consumedSpaces.contains(element)) { - return end; - } return merge(end, space(lastSpace)); } - private Space prefixAndInfix(@Nullable PsiElement element) { - return prefixAndInfix(element, null); - } - private Space endFixPrefixAndInfix(@Nullable PsiElement element) { return merge(endFix(findFirstNonSpacePrevSibling(element)), prefixAndInfix(element, null)); } @@ -3872,11 +3860,6 @@ private Space space(@Nullable PsiElement node) { return space; } - @Nullable - private PsiElement next(PsiElement node) { - return node.getNextSibling(); - } - private Space merge(@Nullable Space s1, @Nullable Space s2) { if (s1 == null || s1.isEmpty()) { return s2 != null ? s2 : Space.EMPTY; @@ -3904,19 +3887,6 @@ private J.Modifier buildFinalModifier() { ); } - @Nullable - private PsiElement findFirstNotSpaceChild(PsiElement parent) { - Iterator iterator = PsiUtilsKt.getAllChildren(parent).iterator(); - while (iterator.hasNext()) { - PsiElement it = iterator.next(); - IElementType type = it.getNode().getElementType(); - if (!isSpace(it.getNode())) { - return it; - } - } - return null; - } - @Nullable private PsiElement findLastNotSpaceChild(@Nullable PsiElement parent) { if (parent == null) { diff --git a/src/main/java/org/openrewrite/kotlin/internal/PsiTreePrinter.java b/src/main/java/org/openrewrite/kotlin/internal/PsiTreePrinter.java index a65b0c946..c077f9ca4 100644 --- a/src/main/java/org/openrewrite/kotlin/internal/PsiTreePrinter.java +++ b/src/main/java/org/openrewrite/kotlin/internal/PsiTreePrinter.java @@ -53,7 +53,7 @@ import static java.util.stream.StreamSupport.stream; -@SuppressWarnings("unused") +@SuppressWarnings({"unused", "DuplicatedCode"}) public class PsiTreePrinter { private static final String TAB = " "; private static final String ELEMENT_PREFIX = "\\---"; @@ -63,7 +63,7 @@ public class PsiTreePrinter { private static final String CONTINUE_PREFIX = "----"; private static final String UNVISITED_PREFIX = "#"; - private static KotlinIrTypeMapping irTypeMapping = new KotlinIrTypeMapping(new JavaTypeCache()); + private static final KotlinIrTypeMapping irTypeMapping = new KotlinIrTypeMapping(new JavaTypeCache()); // Set to true to print types and verify, otherwise just verify the parse to print idempotent. private final static boolean printTypes = true; @@ -393,13 +393,12 @@ private static String printTreeElement(Tree tree) { } private static String printSpace(Space space) { - StringBuilder sb = new StringBuilder(); - sb.append(" whitespace=\"") - .append(space.getWhitespace()).append("\""); - sb.append(" comments=\"") - .append(String.join(",", space.getComments().stream().map(c -> c.printComment(new Cursor(null, "root"))).collect(Collectors.toList()))) - .append("\""); - return sb.toString().replace("\n", "\\s\n"); + String sb = " whitespace=\"" + + space.getWhitespace() + "\"" + + " comments=\"" + + space.getComments().stream().map(c -> c.printComment(new Cursor(null, "root"))).collect(Collectors.joining(",")) + + "\""; + return sb.replace("\n", "\\s\n"); } public static String printJTree(Tree tree) { @@ -497,8 +496,8 @@ private static String printConeKotlinType(ConeTypeProjection coneKotlinType) { ConeTypeProjection[] typeArguments = coneClassLikeType.getTypeArguments(); if (typeArguments != null && typeArguments.length > 0) { sb.append(" typeArgument: "); - for (int i = 0; i < typeArguments.length; i++) { - sb.append(printConeKotlinType(typeArguments[i])); + for (ConeTypeProjection typeArgument : typeArguments) { + sb.append(printConeKotlinType(typeArgument)); } } } diff --git a/src/main/java/org/openrewrite/kotlin/tree/K.java b/src/main/java/org/openrewrite/kotlin/tree/K.java index d60107dfd..3e7d7d2e3 100644 --- a/src/main/java/org/openrewrite/kotlin/tree/K.java +++ b/src/main/java/org/openrewrite/kotlin/tree/K.java @@ -48,6 +48,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; +import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; @@ -74,7 +75,7 @@ default List getComments() { return getPrefix().getComments(); } - @SuppressWarnings("DataFlowIssue") + @SuppressWarnings({"DataFlowIssue", "DuplicatedCode"}) @ToString @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @@ -672,7 +673,7 @@ public Space getPrefix() { @Override public CoordinateBuilder.Statement getCoordinates() { - return null; + return new CoordinateBuilder.Statement(this); } @Override @@ -775,7 +776,7 @@ public String toString() { } } - @SuppressWarnings("unused") + @SuppressWarnings({"unused", "unchecked"}) @Getter @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @@ -1001,6 +1002,7 @@ public CoordinateBuilder.Statement getCoordinates() { } } + @SuppressWarnings({"unused", "EqualsBetweenInconvertibleTypes", "DuplicatedCode"}) @ToString @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @@ -1021,7 +1023,7 @@ class FunctionType implements K, TypeTree, Expression { public FunctionType(UUID id, Space prefix, Markers markers, List leadingAnnotations, List modifiers, @Nullable JRightPadded receiver, - JContainer parameters, @Nullable Space arrow, TypedTree returnType) { + @Nullable JContainer parameters, @Nullable Space arrow, TypedTree returnType) { this.id = id; this.prefix = prefix; this.markers = markers; @@ -1071,10 +1073,11 @@ public List getModifiers() { @Getter JRightPadded receiver; + @Nullable JContainer parameters; public List getParameters() { - return parameters.getElements(); + return parameters != null ? parameters.getElements() : emptyList(); } public FunctionType withParameters(List parameters) { @@ -1113,6 +1116,7 @@ public

J acceptKotlin(KotlinVisitor

v, P p) { return v.visitFunctionType(this, p); } + @SuppressWarnings({"unchecked", "LombokGetterMayBeUsed"}) @ToString @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @@ -1199,6 +1203,7 @@ public FunctionType withParameters(@Nullable JContainer parameters) { } } + @SuppressWarnings("DeprecatedIsStillUsed") @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @Data @@ -1496,7 +1501,7 @@ public ListLiteral withElements(JContainer elements) { } } - @SuppressWarnings("unused") + @SuppressWarnings({"unused", "unchecked"}) @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @Data @@ -1646,6 +1651,7 @@ public String toString() { return withPrefix(Space.EMPTY).printTrimmed(new KotlinPrinter<>()); } + @SuppressWarnings("unused") @RequiredArgsConstructor public static class Padding { private final Property t; @@ -1817,6 +1823,7 @@ public CoordinateBuilder.Statement getCoordinates() { } } + @SuppressWarnings("unchecked") @Getter @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @@ -2127,6 +2134,7 @@ public WhenBranch withExpressions(JContainer expressions) { } } + @SuppressWarnings("unused") @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) @RequiredArgsConstructor @@ -2189,6 +2197,7 @@ public List getSideEffects() { return getOperator().isModifying() ? singletonList(this) : expression.getSideEffects(); } + @SuppressWarnings("SwitchStatementWithTooFewBranches") public enum Type { NotNull; diff --git a/src/main/java/org/openrewrite/kotlin/tree/KContainer.java b/src/main/java/org/openrewrite/kotlin/tree/KContainer.java index 6387b92e0..5027696de 100644 --- a/src/main/java/org/openrewrite/kotlin/tree/KContainer.java +++ b/src/main/java/org/openrewrite/kotlin/tree/KContainer.java @@ -16,6 +16,7 @@ package org.openrewrite.kotlin.tree; public class KContainer { + @SuppressWarnings("LombokGetterMayBeUsed") public enum Location { DESTRUCT_ASSIGNMENTS(KSpace.Location.DESTRUCT_ELEMENTS, KRightPadded.Location.DESTRUCT_SUFFIX), FUNCTION_TYPE_PARAMETERS(KSpace.Location.FUNCTION_TYPE_PARAMETERS, KRightPadded.Location.FUNCTION_TYPE_PARAMETER_SUFFIX), diff --git a/src/main/java/org/openrewrite/kotlin/tree/KLeftPadded.java b/src/main/java/org/openrewrite/kotlin/tree/KLeftPadded.java index dad6e8b0f..139fd406e 100644 --- a/src/main/java/org/openrewrite/kotlin/tree/KLeftPadded.java +++ b/src/main/java/org/openrewrite/kotlin/tree/KLeftPadded.java @@ -15,7 +15,9 @@ */ package org.openrewrite.kotlin.tree; +@SuppressWarnings("unused") public class KLeftPadded { + @SuppressWarnings("LombokGetterMayBeUsed") public enum Location { BINARY_OPERATOR(KSpace.Location.BINARY_OPERATOR); diff --git a/src/main/java/org/openrewrite/kotlin/tree/KRightPadded.java b/src/main/java/org/openrewrite/kotlin/tree/KRightPadded.java index 54f41b139..54f10519e 100644 --- a/src/main/java/org/openrewrite/kotlin/tree/KRightPadded.java +++ b/src/main/java/org/openrewrite/kotlin/tree/KRightPadded.java @@ -16,6 +16,7 @@ package org.openrewrite.kotlin.tree; public class KRightPadded { + @SuppressWarnings("LombokGetterMayBeUsed") public enum Location { DESTRUCT_SUFFIX(KSpace.Location.DESTRUCT_SUFFIX), FUNCTION_TYPE_PARAMETER_SUFFIX(KSpace.Location.FUNCTION_TYPE_PARAMETER_SUFFIX), diff --git a/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeIrSignatureBuilder.kt b/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeIrSignatureBuilder.kt index a2eb1300a..b3732ccdb 100644 --- a/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeIrSignatureBuilder.kt +++ b/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeIrSignatureBuilder.kt @@ -27,9 +27,9 @@ import org.jetbrains.kotlin.ir.util.kotlinFqName import org.jetbrains.kotlin.ir.util.packageFqName import org.jetbrains.kotlin.types.Variance import org.openrewrite.java.JavaTypeSignatureBuilder -import org.openrewrite.java.tree.JavaType import java.util.* +@Suppress("DuplicatedCode") class KotlinTypeIrSignatureBuilder : JavaTypeSignatureBuilder { private var typeVariableNameStack: MutableSet? = null @@ -343,13 +343,19 @@ class KotlinTypeIrSignatureBuilder : JavaTypeSignatureBuilder { fun methodSignature(function: IrFunctionAccessExpression): String { val parent = classSignature(function.symbol.owner.parent) val signature = StringBuilder(parent) - if (function is IrConstructorCall) { - signature.append("{name=,return=$parent") - } else if (function is IrCall) { - signature.append("{name=").append(function.symbol.owner.name) - signature.append(",return=").append(signature(function.symbol.owner.returnType)) - } else { - throw UnsupportedOperationException("Unsupported method signature for IrFunctionAccessExpression " + function.javaClass) + when (function) { + is IrConstructorCall -> { + signature.append("{name=,return=$parent") + } + + is IrCall -> { + signature.append("{name=").append(function.symbol.owner.name) + signature.append(",return=").append(signature(function.symbol.owner.returnType)) + } + + else -> { + throw UnsupportedOperationException("Unsupported method signature for IrFunctionAccessExpression " + function.javaClass) + } } signature.append(",parameters=").append(methodArgumentSignature(function)).append("}") return signature.toString() @@ -368,6 +374,7 @@ class KotlinTypeIrSignatureBuilder : JavaTypeSignatureBuilder { return genericArgumentTypes.toString() } + @Suppress("UNUSED_PARAMETER") private fun methodSignature(baseType: IrTypeOperatorCall): String { return "" } diff --git a/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeMapping.kt b/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeMapping.kt index bdc63e053..5f551a900 100644 --- a/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeMapping.kt +++ b/src/main/kotlin/org/openrewrite/kotlin/KotlinTypeMapping.kt @@ -28,15 +28,12 @@ import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.declarations.impl.FirOuterClassTypeParameterRef import org.jetbrains.kotlin.fir.declarations.utils.isLocal import org.jetbrains.kotlin.fir.declarations.utils.modality -import org.jetbrains.kotlin.fir.declarations.utils.nameOrSpecialName import org.jetbrains.kotlin.fir.declarations.utils.visibility import org.jetbrains.kotlin.fir.expressions.* import org.jetbrains.kotlin.fir.java.declarations.FirJavaField import org.jetbrains.kotlin.fir.references.FirErrorNamedReference import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference import org.jetbrains.kotlin.fir.references.toResolvedBaseSymbol -import org.jetbrains.kotlin.fir.resolve.dfa.DfaInternals -import org.jetbrains.kotlin.fir.resolve.dfa.symbol import org.jetbrains.kotlin.fir.resolve.providers.toSymbol import org.jetbrains.kotlin.fir.resolve.toFirRegularClass import org.jetbrains.kotlin.fir.resolve.toSymbol @@ -59,6 +56,7 @@ import org.openrewrite.kotlin.KotlinTypeSignatureBuilder.Companion.convertClassI import org.openrewrite.kotlin.KotlinTypeSignatureBuilder.Companion.convertKotlinFqToJavaFq import kotlin.collections.ArrayList +@Suppress("DuplicatedCode") class KotlinTypeMapping( private val typeCache: JavaTypeCache, private val firSession: FirSession, @@ -69,7 +67,7 @@ class KotlinTypeMapping( override fun type(type: Any?): JavaType { if (type == null || type is FirErrorTypeRef || type is FirExpression && type.typeRef is FirErrorTypeRef) { - return JavaType.Unknown.getInstance() + return Unknown.getInstance() } val signature = signatureBuilder.signature(type) @@ -78,12 +76,12 @@ class KotlinTypeMapping( return existing } - return type(type, firFile, signature) ?: JavaType.Unknown.getInstance() + return type(type, firFile, signature) ?: Unknown.getInstance() } fun type(type: Any?, parent: Any?): JavaType? { if (type == null || type is FirErrorTypeRef || type is FirExpression && type.typeRef is FirErrorTypeRef) { - return JavaType.Unknown.getInstance() + return Unknown.getInstance() } val signature = signatureBuilder.signature(type, parent) val existing = typeCache.get(signature) @@ -117,11 +115,11 @@ class KotlinTypeMapping( // There is an issue in the KotlinTreeParserVisitor, PsiElementVisitor, // or no FIR element associated to the Kt that requested a type. // Example: AssignmentOperationTest#augmentedAssignmentAnnotation - JavaType.Unknown.getInstance() + Unknown.getInstance() } is FirErrorNamedReference -> { - JavaType.Unknown.getInstance() + Unknown.getInstance() } is FirFile -> { @@ -185,7 +183,7 @@ class KotlinTypeMapping( } else -> { - JavaType.Unknown.getInstance() + Unknown.getInstance() } } } @@ -278,8 +276,8 @@ class KotlinTypeMapping( params = type.typeArguments } if (ref == null) { - typeCache.put(signature, JavaType.Unknown.getInstance()) - return JavaType.Unknown.getInstance() + typeCache.put(signature, Unknown.getInstance()) + return Unknown.getInstance() } ref.fir } @@ -297,17 +295,17 @@ class KotlinTypeMapping( params = type.typeArguments.toList() } if (ref == null) { - typeCache.put(signature, JavaType.Unknown.getInstance()) - return JavaType.Unknown.getInstance() + typeCache.put(signature, Unknown.getInstance()) + return Unknown.getInstance() } ref.fir } else -> throw UnsupportedOperationException("Unexpected classType: ${type.javaClass}") } - var clazz: JavaType.Class? = (if (fq is JavaType.Parameterized) fq.type else fq) as JavaType.Class? + var clazz: Class? = (if (fq is Parameterized) fq.type else fq) as Class? if (clazz == null) { - clazz = JavaType.Class( + clazz = Class( null, mapToFlagsBitmap(firClass.visibility, firClass.modality()), fqn, @@ -372,7 +370,7 @@ class KotlinTypeMapping( } } - var fields: MutableList? = null + var fields: MutableList? = null if (enumEntries.isNotEmpty()) { fields = ArrayList(properties.size + enumEntries.size) for (enumEntry: FirEnumEntry in enumEntries) { @@ -433,10 +431,10 @@ class KotlinTypeMapping( // The signature for a ConeClassLikeType may be aliases without type parameters. if (firClass.typeParameters.isNotEmpty() && signature.contains("<")) { - var pt = typeCache.get(signature) + var pt = typeCache.get(signature) if (pt == null) { val typeParameters: MutableList = ArrayList(firClass.typeParameters.size) - pt = JavaType.Parameterized(null, null, null) + pt = Parameterized(null, null, null) typeCache.put(signature, pt) if (params == null) { params = firClass.typeParameters @@ -493,7 +491,7 @@ class KotlinTypeMapping( if (parentType is Method) { parentType = parentType.declaringType } - if (parentType is JavaType.Parameterized) { + if (parentType is Parameterized) { parentType = parentType.type } val resolvedDeclaringType = TypeUtils.asFullyQualified(parentType) @@ -557,7 +555,7 @@ class KotlinTypeMapping( defaultValues.add(javaMethod.annotationParameterDefaultValue!!.name!!.asString()) } } - val method: Method = Method( + val method = Method( null, (if (javaMethod is BinaryJavaMethod) { javaMethod.access.toLong() @@ -773,9 +771,9 @@ class KotlinTypeMapping( return gtv } - fun variableType(variable: FirVariable, parent: Any?): JavaType.Variable { + fun variableType(variable: FirVariable, parent: Any?): Variable { val signature = signatureBuilder.variableSignature(variable, parent) - val existing = typeCache.get(signature) + val existing = typeCache.get(signature) if (existing != null) { return existing } @@ -783,8 +781,8 @@ class KotlinTypeMapping( } @OptIn(SymbolInternals::class) - fun variableType(variable: FirVariable, parent: Any?, signature: String): JavaType.Variable { - val vt = JavaType.Variable( + fun variableType(variable: FirVariable, parent: Any?, signature: String): Variable { + val vt = Variable( null, mapToFlagsBitmap(variable.visibility, variable.modality), variable.name.asString(), @@ -815,7 +813,7 @@ class KotlinTypeMapping( else -> declaringType = TypeUtils.asFullyQualified(type(firFile)) } - if (declaringType is JavaType.Parameterized) { + if (declaringType is Parameterized) { declaringType = declaringType.type } @@ -839,7 +837,7 @@ class KotlinTypeMapping( } private fun javaArrayType(type: JavaArrayType, signature: String): JavaType { - val arrayType = JavaType.Array( + val arrayType = Array( null, null ) @@ -854,9 +852,9 @@ class KotlinTypeMapping( throw UnsupportedOperationException("Unsupported JavaClassifier: ${type.javaClass.name}") } val fqn = type.fqName.asString() - var clazz = typeCache.get(fqn) + var clazz = typeCache.get(fqn) if (clazz == null) { - clazz = JavaType.Class( + clazz = Class( null, type.access.toLong(), type.fqName.asString(), @@ -888,7 +886,7 @@ class KotlinTypeMapping( if (type.outerClass != null) { owner = TypeUtils.asFullyQualified(type(type.outerClass)) } - var fields: MutableList? = null + var fields: MutableList? = null if (type.fields.isNotEmpty()) { fields = ArrayList(type.fields.size) for (field: JavaField in type.fields) { @@ -939,9 +937,9 @@ class KotlinTypeMapping( ) } if (type.typeParameters.isNotEmpty()) { - var pt = typeCache.get(signature) + var pt = typeCache.get(signature) if (pt == null) { - pt = JavaType.Parameterized(null, null, null) + pt = Parameterized(null, null, null) typeCache.put(signature, pt) val typeParameters: MutableList = ArrayList(type.typeParameters.size) for (typeArgument: JavaTypeParameter in type.typeParameters) { @@ -965,15 +963,15 @@ class KotlinTypeMapping( if (type.typeArguments.isNotEmpty()) { val ptSig = signatureBuilder.signature(type) - var pt = typeCache.get(ptSig) + var pt = typeCache.get(ptSig) if (pt == null) { - pt = JavaType.Parameterized(null, null, null) + pt = Parameterized(null, null, null) typeCache.put(signature, pt) val typeParameters: MutableList = ArrayList(type.typeArguments.size) for (typeArgument: org.jetbrains.kotlin.load.java.structure.JavaType? in type.typeArguments) { typeParameters.add(type(typeArgument)) } - if (clazz is JavaType.Parameterized) { + if (clazz is Parameterized) { clazz = clazz.type } pt.unsafeSet(clazz, typeParameters) @@ -1001,7 +999,7 @@ class KotlinTypeMapping( } } val defaultValues: List? = null - val method: Method = Method( + val method = Method( null, (if (constructor is BinaryJavaConstructor) { constructor.access.toLong() @@ -1047,15 +1045,15 @@ class KotlinTypeMapping( private fun javaPrimitiveType(type: JavaPrimitiveType): JavaType { return when (type.type) { - PrimitiveType.BOOLEAN -> JavaType.Primitive.Boolean - PrimitiveType.BYTE -> JavaType.Primitive.Byte - PrimitiveType.CHAR -> JavaType.Primitive.Char - PrimitiveType.DOUBLE -> JavaType.Primitive.Double - PrimitiveType.FLOAT -> JavaType.Primitive.Float - PrimitiveType.INT -> JavaType.Primitive.Int - PrimitiveType.LONG -> JavaType.Primitive.Long - PrimitiveType.SHORT -> JavaType.Primitive.Short - null -> JavaType.Primitive.Null + PrimitiveType.BOOLEAN -> Primitive.Boolean + PrimitiveType.BYTE -> Primitive.Byte + PrimitiveType.CHAR -> Primitive.Char + PrimitiveType.DOUBLE -> Primitive.Double + PrimitiveType.FLOAT -> Primitive.Float + PrimitiveType.INT -> Primitive.Int + PrimitiveType.LONG -> Primitive.Long + PrimitiveType.SHORT -> Primitive.Short + null -> Primitive.Null } } @@ -1106,13 +1104,13 @@ class KotlinTypeMapping( return gtv } - private fun javaVariableType(javaField: JavaField, owner: JavaType?): JavaType.Variable { + private fun javaVariableType(javaField: JavaField, owner: JavaType?): Variable { val signature = signatureBuilder.javaVariableSignature(javaField) - val existing = typeCache.get(signature) + val existing = typeCache.get(signature) if (existing != null) { return existing } - val variable = JavaType.Variable( + val variable = Variable( null, convertToFlagsBitMap(javaField.visibility, javaField.isStatic, javaField.isFinal, javaField.isAbstract), javaField.name.asString(), @@ -1235,29 +1233,29 @@ class KotlinTypeMapping( return bitMask } - fun primitive(type: FirElement): JavaType.Primitive { + fun primitive(type: FirElement): Primitive { return when (type) { is FirConstExpression<*> -> { when (type.kind) { - ConstantValueKind.Boolean -> JavaType.Primitive.Boolean - ConstantValueKind.Byte, ConstantValueKind.UnsignedByte -> JavaType.Primitive.Byte - ConstantValueKind.Char -> JavaType.Primitive.Char - ConstantValueKind.Double -> JavaType.Primitive.Double - ConstantValueKind.Float -> JavaType.Primitive.Float + ConstantValueKind.Boolean -> Primitive.Boolean + ConstantValueKind.Byte, ConstantValueKind.UnsignedByte -> Primitive.Byte + ConstantValueKind.Char -> Primitive.Char + ConstantValueKind.Double -> Primitive.Double + ConstantValueKind.Float -> Primitive.Float ConstantValueKind.Int, ConstantValueKind.IntegerLiteral, - ConstantValueKind.UnsignedInt, ConstantValueKind.UnsignedIntegerLiteral -> JavaType.Primitive.Int + ConstantValueKind.UnsignedInt, ConstantValueKind.UnsignedIntegerLiteral -> Primitive.Int - ConstantValueKind.Long, ConstantValueKind.UnsignedLong -> JavaType.Primitive.Long - ConstantValueKind.Null -> JavaType.Primitive.Null - ConstantValueKind.Short, ConstantValueKind.UnsignedShort -> JavaType.Primitive.Short - ConstantValueKind.String -> JavaType.Primitive.String - ConstantValueKind.Error -> JavaType.Primitive.None + ConstantValueKind.Long, ConstantValueKind.UnsignedLong -> Primitive.Long + ConstantValueKind.Null -> Primitive.Null + ConstantValueKind.Short, ConstantValueKind.UnsignedShort -> Primitive.Short + ConstantValueKind.String -> Primitive.String + ConstantValueKind.Error -> Primitive.None else -> throw UnsupportedOperationException("Unexpected constant value kind: ${type.kind}") } } else -> { - JavaType.Primitive.None + Primitive.None } } } diff --git a/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementAssociations.kt b/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementAssociations.kt index c297a1eb4..079ffffef 100644 --- a/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementAssociations.kt +++ b/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementAssociations.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.fir.expressions.impl.FirSingleExpressionBlock import org.jetbrains.kotlin.fir.references.FirErrorNamedReference import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference import org.jetbrains.kotlin.fir.references.resolved -import org.jetbrains.kotlin.fir.resolve.dfa.DfaInternals import org.jetbrains.kotlin.fir.symbols.SymbolInternals import org.jetbrains.kotlin.fir.symbols.impl.FirConstructorSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol @@ -191,7 +190,6 @@ class PsiElementAssociations(val typeMapping: KotlinTypeMapping, val file: FirFi enum class ExpressionType { CONSTRUCTOR, METHOD_INVOCATION, - RETURN_EXPRESSION, QUALIFIER } @@ -224,17 +222,6 @@ class PsiElementAssociations(val typeMapping: KotlinTypeMapping, val file: FirFi } } - @OptIn(DfaInternals::class) - fun getExpressionType(psi: KtExpression): ExpressionType? { - val fir = fir(psi) { it is FirExpression } - return if (fir is FirReturnExpression) { - ExpressionType.RETURN_EXPRESSION - } else { - // TODO, other expression type if needed - null - } - } - private fun PsiElement.customToString(): String { return "PSI ${this.textRange} $this" } @@ -264,7 +251,7 @@ class PsiElementAssociations(val typeMapping: KotlinTypeMapping, val file: FirFi companion object { fun printElement(firElement: FirElement) : String { if (firElement is FirSingleExpressionBlock) { - return PsiTreePrinter.firElementToString(firElement.statement) + return PsiTreePrinter.firElementToString(firElement.statement) ?: "" } else if (firElement is FirElseIfTrueCondition) { return "true" } diff --git a/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementIrAssociations.kt b/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementIrAssociations.kt index 3e021e944..3dd15e723 100644 --- a/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementIrAssociations.kt +++ b/src/main/kotlin/org/openrewrite/kotlin/internal/PsiElementIrAssociations.kt @@ -32,6 +32,7 @@ import org.jetbrains.kotlin.psi.* import org.openrewrite.java.tree.JavaType import org.openrewrite.kotlin.KotlinIrTypeMapping +@Suppress("unused") class PsiElementIrAssociations(val typeMapping: KotlinIrTypeMapping, private val psiFile: PsiFile, val file: IrFile) { private val notMapped: MutableList = ArrayList() diff --git a/src/test/java/org/openrewrite/kotlin/tree/AssignmentTest.java b/src/test/java/org/openrewrite/kotlin/tree/AssignmentTest.java index e55bbd76b..353110f14 100644 --- a/src/test/java/org/openrewrite/kotlin/tree/AssignmentTest.java +++ b/src/test/java/org/openrewrite/kotlin/tree/AssignmentTest.java @@ -20,6 +20,7 @@ import static org.openrewrite.kotlin.Assertions.kotlin; +@SuppressWarnings("All") class AssignmentTest implements RewriteTest { @Test diff --git a/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java b/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java index 49bf2131a..829008f97 100644 --- a/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java +++ b/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java @@ -16,7 +16,6 @@ package org.openrewrite.kotlin.tree; import org.junit.jupiter.api.Test; -import org.junitpioneer.jupiter.ExpectedToFail; import org.openrewrite.test.RewriteTest; import static org.openrewrite.kotlin.Assertions.kotlin; diff --git a/src/test/java/org/openrewrite/kotlin/tree/UnaryTest.java b/src/test/java/org/openrewrite/kotlin/tree/UnaryTest.java index f7fd432da..a0a160029 100644 --- a/src/test/java/org/openrewrite/kotlin/tree/UnaryTest.java +++ b/src/test/java/org/openrewrite/kotlin/tree/UnaryTest.java @@ -22,7 +22,6 @@ class UnaryTest implements RewriteTest { - @Test void unary() { rewriteRun(