Skip to content

Commit

Permalink
Clean up warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
kunli2 committed Nov 9, 2023
1 parent 8659547 commit 4746bcd
Show file tree
Hide file tree
Showing 19 changed files with 160 additions and 188 deletions.
4 changes: 2 additions & 2 deletions src/main/java/org/openrewrite/kotlin/AddImport.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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<JRightPadded<J.Import>> checkCRLF(JavaSourceFile cu, List<JRightPadded<J.Import>> newImports, GeneralFormatStyle generalFormatStyle) {
private List<JRightPadded<J.Import>> checkCRLF(List<JRightPadded<J.Import>> newImports, GeneralFormatStyle generalFormatStyle) {
if (generalFormatStyle.isUseCRLFNewLines()) {
return ListUtils.map(newImports, rp -> rp.map(
i -> i.withPrefix(i.getPrefix().withWhitespace(i.getPrefix().getWhitespace()
Expand Down
28 changes: 14 additions & 14 deletions src/main/java/org/openrewrite/kotlin/Assertions.java
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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) {
Expand Down Expand Up @@ -164,22 +166,20 @@ private static void acceptSpec(Consumer<SourceSpec<K.CompilationUnit>> spec, Sou
}

public static ThrowingConsumer<K.CompilationUnit> isFullyParsed() {
return cu -> {
new KotlinIsoVisitor<Integer>() {
@Override
public J visitUnknown(J.Unknown unknown, Integer integer) {
throw new AssertionFailedError("Parsing error, J.Unknown detected");
}
return cu -> new KotlinIsoVisitor<Integer>() {
@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<SourceSpec<?>> spaceConscious() {
Expand Down
22 changes: 14 additions & 8 deletions src/main/java/org/openrewrite/kotlin/FindKotlinSources.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
};
}
}
4 changes: 1 addition & 3 deletions src/main/java/org/openrewrite/kotlin/KotlinParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -394,7 +393,6 @@ public CompiledSource parse(List<Parser.Input> sources, Disposable disposable, E
kotlinSources.add(new KotlinSource(source, file, cRLFLocations));
}

BaseDiagnosticsCollector diagnosticsReporter = DiagnosticReporterFactory.INSTANCE.createReporter(false);
Function1<? super GlobalSearchScope, PackagePartProvider> providerFunction1 = environment::createPackagePartProvider;
VfsBasedProjectEnvironment projectEnvironment = new VfsBasedProjectEnvironment(
environment.getProject(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
46 changes: 21 additions & 25 deletions src/main/java/org/openrewrite/kotlin/internal/KotlinPrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import java.util.Optional;
import java.util.function.UnaryOperator;

@SuppressWarnings("SwitchStatementWithTooFewBranches")
public class KotlinPrinter<P> extends KotlinVisitor<PrintOutputCapture<P>> {
private final KotlinJavaPrinter<P> delegate;

Expand Down Expand Up @@ -253,7 +254,7 @@ public J visitFunctionTypeParameter(K.FunctionType.Parameter parameter, PrintOut
@Override
public J visitKReturn(K.KReturn kReturn, PrintOutputCapture<P> 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);
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -671,7 +664,7 @@ private J.ClassDeclaration visitClassDeclaration0(J.ClassDeclaration classDecl,

if (classDecl.getImplements() != null) {
JContainer<TypeTree> 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<? extends JRightPadded<? extends J>> nodes = container.getPadding().getElements();
for (int i = 0; i < nodes.size(); i++) {
Expand Down Expand Up @@ -991,11 +984,6 @@ private void visitArgumentsContainer(JContainer<Expression> 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);
}

Expand All @@ -1011,13 +999,11 @@ public J visitNewClass(J.NewClass newClass, PrintOutputCapture<P> 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(":");
Expand Down Expand Up @@ -1306,12 +1292,22 @@ protected void afterSyntax(J j, PrintOutputCapture<P> 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> 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("?");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
/**
* PSI based parser
*/
@SuppressWarnings({"DataFlowIssue", "ConstantValue"})
public class KotlinTreeParserVisitor extends KtVisitor<J, ExecutionContext> {
private final KotlinSource kotlinSource;
private final PsiElementAssociations psiElementAssociations;
Expand Down Expand Up @@ -1643,9 +1644,7 @@ public J visitKtFile(KtFile file, ExecutionContext data) {

List<JRightPadded<Statement>> statements = new ArrayList<>(file.getDeclarations().size());
List<KtDeclaration> 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));
}
Expand Down Expand Up @@ -3514,27 +3513,16 @@ private Space infix(@Nullable PsiElement element, @Nullable Set<PsiElement> cons
}

private Space endFix(@Nullable PsiElement element) {
return endFix(element, null);
}

private Space endFix(@Nullable PsiElement element, @Nullable Set<PsiElement> 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));
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -3904,19 +3887,6 @@ private J.Modifier buildFinalModifier() {
);
}

@Nullable
private PsiElement findFirstNotSpaceChild(PsiElement parent) {
Iterator<PsiElement> 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) {
Expand Down
21 changes: 10 additions & 11 deletions src/main/java/org/openrewrite/kotlin/internal/PsiTreePrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "\\---";
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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));
}
}
}
Expand Down
Loading

0 comments on commit 4746bcd

Please sign in to comment.