Skip to content

Commit

Permalink
Get tools compiling
Browse files Browse the repository at this point in the history
  • Loading branch information
sambsnyd committed Feb 28, 2024
1 parent b8d2559 commit e7622c8
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.openrewrite.ExecutionContext;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Result;
import org.openrewrite.internal.InMemoryLargeSourceSet;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.tree.J;
Expand All @@ -32,6 +33,7 @@
import java.util.List;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

@RequiredArgsConstructor
public class GenerateModel {
Expand All @@ -57,6 +59,8 @@ public static void main(String[] args) {
null,
ctx
)
.map(J.CompilationUnit.class::cast)
.toList()
.get(0)
.getClasses()
.get(0)
Expand All @@ -81,28 +85,26 @@ public void generate() {
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlRightPadded.java")
);

results.addAll(new WriteModel(modelClasses).run(List.of(jp().parse(
ListUtils.concat(TomlTreePath, deps), null, ctx).get(0)), ctx).getResults());
results.addAll(new WriteVisitorMethods(modelClasses).run(jp().parse(
List.of(
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlVisitor.java"),
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlIsoVisitor.java")
),
null,
ctx
), ctx).getResults());
results.addAll(new WritePrinter(modelClasses).run(jp().parse(
List.of(
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/TomlPrinter.java")
),
null,
ctx
), ctx).getResults());
results.addAll(new WriteModel(modelClasses)
.run(new InMemoryLargeSourceSet(jp().parse(
ListUtils.concat(TomlTreePath, deps), null, ctx)
.collect(toList())), ctx).getChangeset().getAllResults());
results.addAll(new WriteVisitorMethods(modelClasses)
.run(new InMemoryLargeSourceSet(jp().parse(List.of(
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlVisitor.java"),
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlIsoVisitor.java")
), null, ctx)
.collect(toList())), ctx).getChangeset().getAllResults());
results.addAll(new WritePrinter(modelClasses)
.run(new InMemoryLargeSourceSet(jp().parse(List.of(
Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlContainer.java")), null, ctx)
.collect(toList())), ctx).getChangeset().getAllResults());

writeResults(results);

// TODO Unable to add accessors in the first phase due to some bug in JavaTemplate.
writeResults(new WritePaddingAccessors().run(jp().parse(List.of(TomlTreePath), null, ctx), ctx).getResults());
writeResults(new WritePaddingAccessors()
.run(new InMemoryLargeSourceSet(jp().parse(List.of(TomlTreePath), null, ctx).collect(toList())), ctx).getChangeset().getAllResults());
}

private void writeResults(List<Result> results) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.Comparator;
import java.util.List;
import java.util.StringJoiner;
import java.util.function.Supplier;

@RequiredArgsConstructor
public class WriteModel extends Recipe {
Expand All @@ -46,18 +45,18 @@ public String getDescription() {
return "Expand the model into an AST with Lombok annotations, Padding classes, etc.";
}

Supplier<JavaParser> parser = () -> JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()).build();
JavaParser.Builder<? extends JavaParser, ?> parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath());

JavaVisitor<ExecutionContext> writeModelClass = new JavaIsoVisitor<ExecutionContext>() {
final JavaTemplate valueModel = JavaTemplate.builder(this::getCursor,
final JavaTemplate valueModel = JavaTemplate.builder(
"""
@Value
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@With
"""
).javaParser(parser).build();

final JavaTemplate paddedModel = JavaTemplate.builder(this::getCursor,
final JavaTemplate paddedModel = JavaTemplate.builder(
"""
@ToString
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
Expand All @@ -67,13 +66,13 @@ public String getDescription() {
"""
).javaParser(parser).build();

final JavaTemplate idField = JavaTemplate.builder(this::getCursor, "@EqualsAndHashCode.Include UUID id;").javaParser(parser).build();
final JavaTemplate prefixField = JavaTemplate.builder(this::getCursor, "Space prefix;").javaParser(parser).build();
final JavaTemplate markersField = JavaTemplate.builder(this::getCursor, "Markers markers;").javaParser(parser).build();
final JavaTemplate paddingField = JavaTemplate.builder(this::getCursor, "@Nullable @NonFinal transient WeakReference<Padding> padding;").javaParser(parser).build();
final JavaTemplate implementsTree = JavaTemplate.builder(this::getCursor, "Toml").javaParser(parser).build();
final JavaTemplate idField = JavaTemplate.builder("@EqualsAndHashCode.Include UUID id;").javaParser(parser).build();
final JavaTemplate prefixField = JavaTemplate.builder("Space prefix;").javaParser(parser).build();
final JavaTemplate markersField = JavaTemplate.builder("Markers markers;").javaParser(parser).build();
final JavaTemplate paddingField = JavaTemplate.builder("@Nullable @NonFinal transient WeakReference<Padding> padding;").javaParser(parser).build();
final JavaTemplate implementsTree = JavaTemplate.builder("Toml").javaParser(parser).build();

final JavaTemplate getPadding = JavaTemplate.builder(this::getCursor,
final JavaTemplate getPadding = JavaTemplate.builder(
"""
public Padding getPadding() {
Padding p;
Expand All @@ -92,7 +91,7 @@ public Padding getPadding() {
"""
).build();

final JavaTemplate paddingClass = JavaTemplate.builder(this::getCursor,
final JavaTemplate paddingClass = JavaTemplate.builder(
"""
@RequiredArgsConstructor
public static class Padding {
Expand All @@ -101,7 +100,7 @@ public static class Padding {
"""
).build();

final JavaTemplate acceptMethod = JavaTemplate.builder(this::getCursor,
final JavaTemplate acceptMethod = JavaTemplate.builder(
"""
@Override public <P> Toml acceptToml(TomlVisitor<P> v, P p) {
return v.visit#{}(this, p);
Expand All @@ -112,7 +111,7 @@ public static class Padding {
/**
* The accessors in the model class that skips the padding and return the contained element.
*/
final JavaTemplate unwrappedPaddedGetterWither = JavaTemplate.builder(this::getCursor,
final JavaTemplate unwrappedPaddedGetterWither = JavaTemplate.builder(
"""
public #{} get#{}() {
return #{}.getElement();
Expand All @@ -125,7 +124,7 @@ public static class Padding {
"""
).javaParser(parser).build();

final JavaTemplate nullableUnwrappedPaddedGetterWither = JavaTemplate.builder(this::getCursor,
final JavaTemplate nullableUnwrappedPaddedGetterWither = JavaTemplate.builder(
"""
@Nullable
public #{} get#{}() {
Expand All @@ -144,7 +143,7 @@ public static class Padding {
/**
* The accessors in the model class that skips the padding and return the contained elements.
*/
final JavaTemplate unwrappedContainerGetterWither = JavaTemplate.builder(this::getCursor,
final JavaTemplate unwrappedContainerGetterWither = JavaTemplate.builder(
"""
public List<#{}> get#{}() {
return #{}.getElements();
Expand All @@ -157,27 +156,28 @@ public static class Padding {
"""
).javaParser(parser).build();

final JavaTemplate withGetterAnnotations = JavaTemplate.builder(this::getCursor, "@With @Getter")
final JavaTemplate withGetterAnnotations = JavaTemplate.builder("@With @Getter")
.javaParser(parser).build();

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration c = classDecl;
if (FindAnnotations.find(c, "@generate.Skip").size() > 0) {
if (!FindAnnotations.find(c, "@generate.Skip").isEmpty()) {
//noinspection ConstantConditions
return null;
}

boolean padded = c.getBody().getStatements().stream().anyMatch(this::isPadded);

if(c.getImplements() == null) {
c = c.withTemplate(implementsTree, c.getCoordinates().addImplementsClause());
if (c.getImplements() == null) {
c = implementsTree.apply(getCursor(), c.getCoordinates().addImplementsClause());
}

c = c.withTemplate(markersField, c.getBody().getCoordinates().firstStatement());
c = c.withTemplate(prefixField, c.getBody().getCoordinates().firstStatement());
c = c.withTemplate(idField, c.getBody().getCoordinates().firstStatement());
c = c.withTemplate(acceptMethod, c.getBody().getCoordinates().lastStatement(), classDecl.getSimpleName());

c = markersField.apply(getCursor(), c.getBody().getCoordinates().firstStatement());
c = prefixField.apply(getCursor(), c.getBody().getCoordinates().firstStatement());
c = idField.apply(getCursor(), c.getBody().getCoordinates().firstStatement());
c = acceptMethod.apply(getCursor(), c.getBody().getCoordinates().lastStatement(), classDecl.getSimpleName());

for (Statement statement : c.getBody().getStatements()) {
if (statement instanceof J.VariableDeclarations varDec) {
Expand All @@ -196,32 +196,32 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
case "TomlContainer" -> writeContainerGetterWithers(c, varDec, elementType);
case "TomlLeftPadded" -> writePaddedGetterWithers(c, varDec, elementType, "Left");
case "TomlRightPadded" -> writePaddedGetterWithers(c, varDec, elementType, "Right");
default -> c.withTemplate(withGetterAnnotations, varDec.getCoordinates()
default -> withGetterAnnotations.apply(getCursor(), varDec.getCoordinates()
.addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
};
} else if (padded) {
c = c.withTemplate(withGetterAnnotations, varDec.getCoordinates()
c = withGetterAnnotations.apply(getCursor(), varDec.getCoordinates()
.addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
}
}
}
}

if (padded) {
c = c.withTemplate(paddedModel, c.getCoordinates().replaceAnnotations());
c = c.withTemplate(paddingField, c.getBody().getCoordinates().firstStatement());
c = c.withTemplate(getPadding, c.getBody().getCoordinates().lastStatement());
c = c.withTemplate(paddingClass, c.getBody().getCoordinates().lastStatement(), c.getSimpleName());
c = paddedModel.apply(getCursor(), c.getCoordinates().replaceAnnotations());
c = paddingField.apply(getCursor(), c.getBody().getCoordinates().firstStatement());
c = getPadding.apply(getCursor(), c.getBody().getCoordinates().lastStatement());
c = paddingClass.apply(getCursor(), c.getBody().getCoordinates().lastStatement(), c.getSimpleName());
} else {
c = c.withTemplate(valueModel, c.getCoordinates().replaceAnnotations());
c = valueModel.apply(getCursor(), c.getCoordinates().replaceAnnotations());
}

List<Statement> statements = c.getBody().getStatements();
c = c.withBody(c.getBody().withStatements(ListUtils.map(statements, (i, statement) -> {
if (statement instanceof J.VariableDeclarations && i > 0) {
Statement previous = statements.get(i - 1);
if (!((J.VariableDeclarations) statement).getAllAnnotations().isEmpty() ||
(previous instanceof J.VariableDeclarations) && !((J.VariableDeclarations) previous).getAllAnnotations().isEmpty()) {
if (!((J.VariableDeclarations) statement).getLeadingAnnotations().isEmpty() ||
(previous instanceof J.VariableDeclarations) && !((J.VariableDeclarations) previous).getLeadingAnnotations().isEmpty()) {
return statement.withPrefix(Space.format("\n\n"));
}
}
Expand All @@ -237,7 +237,7 @@ private J.ClassDeclaration writeContainerGetterWithers(J.ClassDeclaration c, J.V
String elementTypeName = elementType.getClassName();
String modelTypeName = c.getSimpleName();

c = c.withTemplate(unwrappedContainerGetterWither, c.getBody().getCoordinates().lastStatement(),
c = unwrappedContainerGetterWither.apply(getCursor(), c.getBody().getCoordinates().lastStatement(),
elementTypeName, capitalizedName,
name,
modelTypeName, capitalizedName, elementTypeName, name,
Expand All @@ -263,12 +263,12 @@ private J.ClassDeclaration writePaddedGetterWithers(J.ClassDeclaration c, J.Vari
.get(0).getSimpleName());
}
}
c = c.withTemplate(nullableUnwrappedPaddedGetterWither, c.getBody().getCoordinates().lastStatement(),
c = nullableUnwrappedPaddedGetterWither.apply(getCursor(), c.getBody().getCoordinates().lastStatement(),
elementTypeName, capitalizedName, name, name, modelTypeName, capitalizedName,
elementTypeName, name, name, name, modelTypeName, newModelArguments.toString(),
capitalizedName, leftOrRight, name, name);
} else {
c = c.withTemplate(unwrappedPaddedGetterWither, c.getBody().getCoordinates().lastStatement(),
c = unwrappedPaddedGetterWither.apply(getCursor(), c.getBody().getCoordinates().lastStatement(),
elementTypeName, capitalizedName, name,
modelTypeName, capitalizedName, elementTypeName, name,
capitalizedName, leftOrRight, name, name);
Expand All @@ -288,7 +288,7 @@ boolean isPadded(Statement statement) {
};

@Override
protected JavaVisitor<ExecutionContext> getVisitor() {
public JavaVisitor<ExecutionContext> getVisitor() {
return new JavaIsoVisitor<>() {
@Override
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import org.openrewrite.java.tree.TypeUtils;

import java.util.StringJoiner;
import java.util.function.Supplier;

/**
* TODO Unable to add accessors in the first phase due to some bug in JavaTemplate.
Expand All @@ -42,7 +41,12 @@ public String getDisplayName() {
return "Write accessors for padded parts of the model";
}

Supplier<JavaParser> parser = () -> JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()).build();
@Override
public String getDescription() {
return "Write accessors for padded parts of the model.";
}

JavaParser.Builder<? extends JavaParser, ?> parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath());

@RequiredArgsConstructor
class WritePaddingAccessorsVisitor extends JavaIsoVisitor<ExecutionContext> {
Expand All @@ -51,7 +55,7 @@ class WritePaddingAccessorsVisitor extends JavaIsoVisitor<ExecutionContext> {
/**
* The accessors in the Padding class that return the padding wrapped element.
*/
final JavaTemplate paddedGetterWither = JavaTemplate.builder(this::getCursor,
final JavaTemplate paddedGetterWither = JavaTemplate.builder(
"""
#{}
public Toml#{}<#{}> get#{}() {
Expand Down Expand Up @@ -113,24 +117,18 @@ private J.ClassDeclaration writePaddedGetterWithers(J.ClassDeclaration c, J.Vari
}
}

c = c.withTemplate(paddedGetterWither, c.getBody().getCoordinates().lastStatement(),
c = paddedGetterWither.apply(getCursor(), c.getBody().getCoordinates().lastStatement(),
nullable ? "@Nullable " : "", leftOrRight, elementTypeName, capitalizedName,
name, modelTypeName, capitalizedName,
nullable ? "@Nullable " : "", leftOrRight,
elementTypeName, name, name, name, modelTypeName, newModelArguments);

return c;
}

boolean isPadded(Statement statement) {
JavaType.FullyQualified type = TypeUtils.asFullyQualified(((J.VariableDeclarations) statement).getType());
assert type != null;
return type.getClassName().contains("Padded") || type.getClassName().equals("TomlContainer");
}
}

@Override
protected JavaVisitor<ExecutionContext> getVisitor() {
public JavaVisitor<ExecutionContext> getVisitor() {
return new JavaIsoVisitor<>() {
@Override
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
Expand Down
Loading

0 comments on commit e7622c8

Please sign in to comment.