diff --git a/CLAUDE.md b/CLAUDE.md index 0d748c5371..a84d53ee6f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -93,7 +93,6 @@ OpenRewrite is an automated refactoring ecosystem for source code that eliminate - **`rewrite-java-test`**: Java-specific testing utilities and infrastructure - **`rewrite-java-lombok`**: Lombok-specific Java support - **`rewrite-benchmarks`**: JMH performance benchmarks -- **`tools/language-parser-builder`**: Template tool for generating new language parsers ## Architecture Decision Records (ADRs) diff --git a/IDE.properties.tmp b/IDE.properties.tmp index 907d735897..569427acbc 100644 --- a/IDE.properties.tmp +++ b/IDE.properties.tmp @@ -44,7 +44,3 @@ rewrite-yaml rewrite-benchmarks rewrite-bom - -# Tools that are used less frequently to, for example, build new language parsers. - -#tools diff --git a/settings.gradle.kts b/settings.gradle.kts index ed5bb25bd5..7b3e720885 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -50,10 +50,6 @@ val includedProjects = file("IDE.properties").let { } }.toSet() -if (!file("IDE.properties").exists() || includedProjects.contains("tools")) { - includeBuild("tools") -} - include(*allProjects.toTypedArray()) gradle.allprojects { diff --git a/tools/language-parser-builder/README.md b/tools/language-parser-builder/README.md deleted file mode 100644 index efedafc95d..0000000000 --- a/tools/language-parser-builder/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Language Parser Builder - -This project is a tool to generate an OpenRewrite lossless semantic tree (LST) model for a language. The LST model is the form that is suitable for search, transformation, and even serialization. - -This project is a sort of template meant to be modified while generating an LST model and then reverted back to its current state once the new language binding is complete. - -### To use - -Replace all occurrences of `Toml` with the language you intend to build a parser for. Rename the packages ending in `toml`, file names containing `Toml`, and references in the code referring to `Toml`. - -Update the `Assertions` class with the correct `@Language` annotation for your language (if there is one, otherwise remove them altogether), and update the method names to your language name. - -The class `src/model/Toml` is meant to help you write a simplified version of the LST model. `GenerateModel` takes this simplified form and writes out the full LST model and fills out basic visitor navigation and printing methods. The generated methods in `TomlPrinter` (which will of course be renamed to the language you are implementing) are meant as a starting point. There will be further printing modification necessary, but the generator takes care of a lot of the repetitive work. - -You can proceed incrementally, adding model objects and running the generator, implementing their print methods, etc. Or you can write out the entire model and generate once. The generator will not overwrite any existing methods, so iterative generation does not clobber your work. - -### Completing the language parser - -A partial series of steps needed to complete the language: - -* Create a new directory `rewrite-LANGUAGE` -* Add your new language to the list of `allProjects` in `settings.gradle.kts` -* Add your new language to `IDE.properties.tmp`. diff --git a/tools/language-parser-builder/build.gradle.kts b/tools/language-parser-builder/build.gradle.kts deleted file mode 100644 index 938488e495..0000000000 --- a/tools/language-parser-builder/build.gradle.kts +++ /dev/null @@ -1,38 +0,0 @@ -plugins { - id("org.openrewrite.build.language-library") version("latest.release") -} - -sourceSets { - create("model") { - compileClasspath += sourceSets.main.get().output - runtimeClasspath += sourceSets.main.get().output - } -} -val modelImplementation: Configuration by configurations.getting { - extendsFrom(configurations.implementation.get()) -} -val modelAnnotationProcessor: Configuration by configurations.getting -val modelCompileOnly: Configuration by configurations.getting - -configurations["modelRuntimeOnly"].extendsFrom(configurations.runtimeOnly.get()) - -dependencies { - compileOnly("org.projectlombok:lombok:latest.release") - compileOnly("org.openrewrite:rewrite-test") - implementation("org.openrewrite:rewrite-java-21") - - implementation(platform("org.openrewrite.recipe:rewrite-recipe-bom:latest.release")) - modelAnnotationProcessor("org.projectlombok:lombok:latest.release") - modelCompileOnly("org.projectlombok:lombok:latest.release") - modelImplementation("ch.qos.logback:logback-classic:latest.release") -} - -tasks.register("runGenerator") { - mainClass = "generate.GenerateModel" - classpath = sourceSets.getByName("model").runtimeClasspath - workingDir = file("../..") -} - -license { - header = file("../../gradle/licenseHeader.txt") -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/Assertions.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/Assertions.java deleted file mode 100644 index f22ecb25b8..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/Assertions.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml; - -public class Assertions { - private Assertions() { - } - -// public static SourceSpecs toml(@Language("toml") @Nullable String before) { -// return Assertions.toml(before, s -> { -// }); -// } -// -// public static SourceSpecs toml(@Language("toml") @Nullable String before, Consumer> spec) { -// SourceSpec doc = new SourceSpec<>(Toml.Document.class, null, TomlParser.builder(), before, null); -// spec.accept(xml); -// return xml; -// } -// -// public static SourceSpecs toml(@Language("toml") @Nullable String before, @Language("toml") @Nullable String after) { -// return toml(before, after, s -> { -// }); -// } -// -// public static SourceSpecs toml(@Language("toml") @Nullable String before, @Language("toml") @Nullable String after, -// Consumer> spec) { -// SourceSpec doc = new SourceSpec<>(Toml.Document.class, null, TomlParser.builder(), before, s -> after); -// spec.accept(doc); -// return doc; -// } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlIsoVisitor.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlIsoVisitor.java deleted file mode 100644 index ffd297d513..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlIsoVisitor.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml; - -public class TomlIsoVisitor

extends TomlVisitor

{ - -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlParser.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlParser.java deleted file mode 100755 index 6e815eace0..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml; - -//public class TomlParser implements Parser { -// @Override -// public List parseInputs(Iterable sourceFiles, @Nullable Path relativeTo, ExecutionContext ctx) { -// ParsingEventListener parsingListener = ParsingExecutionContextView.view(ctx).getParsingListener(); -// return acceptedInputs(sourceFiles).stream() -// .map(sourceFile -> { -// Timer.Builder timer = Timer.builder("rewrite.parse") -// .description("The time spent parsing an XML file") -// .tag("file.type", "XML"); -// Timer.Sample sample = Timer.start(); -// Path path = sourceFile.getRelativePath(relativeTo); -// try { -// EncodingDetectingInputStream is = sourceFile.getSource(ctx); -// String sourceStr = is.readFully(); -// -// // FIXME implement me! -// Toml.Document document = null; -// -// sample.stop(MetricsHelper.successTags(timer).register(Metrics.globalRegistry)); -// parsingListener.parsed(sourceFile, document); -// return document; -// } catch (Throwable t) { -// sample.stop(MetricsHelper.errorTags(timer, t).register(Metrics.globalRegistry)); -// ParsingExecutionContextView.view(ctx).parseFailure(sourceFile, relativeTo, this, t); -// ctx.getOnError().accept(new IllegalStateException(path + " " + t.getMessage(), t)); -// return null; -// } -// }) -// .filter(Objects::nonNull) -// .collect(toList()); -// } -// -// @Override -// public List parse(@Language("xml") String... sources) { -// return parse(new InMemoryExecutionContext(), sources); -// } -// -// @Override -// public boolean accept(Path path) { -// String p = path.toString(); -// return p.endsWith(".xml") || -// p.endsWith(".wsdl") || -// p.endsWith(".xhtml") || -// p.endsWith(".xsd") || -// p.endsWith(".xsl") || -// p.endsWith(".xslt") || -// p.endsWith(".tld"); -// } -// -// @Override -// public Path sourcePathFromSourceText(Path prefix, String sourceCode) { -// return prefix.resolve("file.xml"); -// } -// -// public static Builder builder() { -// return new Builder(); -// } -// -// public static class Builder extends Parser.Builder { -// -// public Builder() { -// super(Toml.Document.class); -// } -// -// @Override -// public TomlParser build() { -// return new TomlParser(); -// } -// -// @Override -// public String getDslName() { -// return "toml"; -// } -// } -//} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlVisitor.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlVisitor.java deleted file mode 100644 index 2ae7a5b922..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/TomlVisitor.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml; - -import org.openrewrite.Cursor; -import org.openrewrite.TreeVisitor; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.java.tree.J; -import org.openrewrite.marker.Markers; -import org.openrewrite.toml.tree.*; - -import java.util.List; - -public class TomlVisitor

extends TreeVisitor { - - public Space visitSpace(Space space, P p) { - return space; - } - - public TomlRightPadded visitRightPadded(@Nullable TomlRightPadded right, P p) { - if (right == null) { - //noinspection ConstantConditions - return null; - } - - setCursor(new Cursor(getCursor(), right)); - - T t = right.getElement(); - if (t instanceof J) { - //noinspection unchecked - t = visitAndCast((J) right.getElement(), p); - } - - setCursor(getCursor().getParent()); - if (t == null) { - //noinspection ConstantConditions - return null; - } - - Space after = visitSpace(right.getAfter(), p); - Markers markers = visitMarkers(right.getMarkers(), p); - return (after == right.getAfter() && t == right.getElement() && markers == right.getMarkers()) ? - right : new TomlRightPadded<>(t, after, markers); - } - - public TomlLeftPadded visitLeftPadded(@Nullable TomlLeftPadded left, P p) { - if (left == null) { - //noinspection ConstantConditions - return null; - } - - setCursor(new Cursor(getCursor(), left)); - - Space before = visitSpace(left.getBefore(), p); - T t = left.getElement(); - - if (t instanceof J) { - //noinspection unchecked - t = visitAndCast((J) left.getElement(), p); - } - - setCursor(getCursor().getParent()); - if (t == null) { - // If nothing changed leave AST node the same - if (left.getElement() == null && before == left.getBefore()) { - return left; - } - //noinspection ConstantConditions - return null; - } - - return (before == left.getBefore() && t == left.getElement()) ? left : new TomlLeftPadded<>(before, t, left.getMarkers()); - } - - public TomlContainer visitContainer(@Nullable TomlContainer container, P p) { - if (container == null) { - //noinspection ConstantConditions - return null; - } - setCursor(new Cursor(getCursor(), container)); - - Space before = visitSpace(container.getBefore(), p); - List> ts = ListUtils.map(container.getPadding().getElements(), t -> visitRightPadded(t, p)); - - setCursor(getCursor().getParent()); - - return ts == container.getPadding().getElements() && before == container.getBefore() ? - container : - TomlContainer.build(before, ts, container.getMarkers()); - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/TomlPrinter.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/TomlPrinter.java deleted file mode 100644 index 1f1fa14b70..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/TomlPrinter.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.internal; - -import org.openrewrite.Cursor; -import org.openrewrite.PrintOutputCapture; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.marker.Marker; -import org.openrewrite.marker.Markers; -import org.openrewrite.toml.TomlVisitor; -import org.openrewrite.toml.tree.*; - -import java.util.List; -import java.util.function.UnaryOperator; - -public class TomlPrinter

extends TomlVisitor> { - private static final UnaryOperator MARKER_WRAPPER = - out -> "/*~~" + out + (out.isEmpty() ? "" : "~~") + ">*/"; - - protected void beforeSyntax(Toml t, PrintOutputCapture

p) { - beforeSyntax(t.getPrefix(), t.getMarkers(), p); - } - - protected void beforeSyntax(Space prefix, Markers markers, PrintOutputCapture

p) { - for (Marker marker : markers.getMarkers()) { - p.append(p.getMarkerPrinter().beforePrefix(marker, new Cursor(getCursor(), marker), MARKER_WRAPPER)); - } - visitSpace(prefix, p); - visitMarkers(markers, p); - for (Marker marker : markers.getMarkers()) { - p.append(p.getMarkerPrinter().beforeSyntax(marker, new Cursor(getCursor(), marker), MARKER_WRAPPER)); - } - } - - protected void afterSyntax(Toml t, PrintOutputCapture

p) { - afterSyntax(t.getMarkers(), p); - } - - protected void afterSyntax(Markers markers, PrintOutputCapture

p) { - for (Marker marker : markers.getMarkers()) { - p.append(p.getMarkerPrinter().afterSyntax(marker, new Cursor(getCursor(), marker), MARKER_WRAPPER)); - } - } - - protected void visitRightPadded(List> nodes, String suffixBetween, PrintOutputCapture

p) { - for (int i = 0; i < nodes.size(); i++) { - TomlRightPadded node = nodes.get(i); - visit(node.getElement(), p); - visitSpace(node.getAfter(), p); - visitMarkers(node.getMarkers(), p); - if (i < nodes.size() - 1) { - p.append(suffixBetween); - } - } - } - - protected void visitContainer(String before, @Nullable TomlContainer container, - String suffixBetween, @Nullable String after, PrintOutputCapture

p) { - if (container == null) { - return; - } - beforeSyntax(container.getBefore(), container.getMarkers(), p); - p.append(before); - visitRightPadded(container.getPadding().getElements(), suffixBetween, p); - afterSyntax(container.getMarkers(), p); - p.append(after == null ? "" : after); - } - - @Override - public Space visitSpace(Space space, PrintOutputCapture

p) { - p.append(space.getWhitespace()); - return space; - } - - protected void visitLeftPadded(@Nullable String prefix, @Nullable TomlLeftPadded leftPadded, PrintOutputCapture

p) { - if (leftPadded != null) { - beforeSyntax(leftPadded.getBefore(), leftPadded.getMarkers(), p); - if (prefix != null) { - p.append(prefix); - } - visit(leftPadded.getElement(), p); - afterSyntax(leftPadded.getMarkers(), p); - } - } - - protected void visitRightPadded(@Nullable TomlRightPadded rightPadded, @Nullable String suffix, PrintOutputCapture

p) { - if (rightPadded != null) { - beforeSyntax(Space.EMPTY, rightPadded.getMarkers(), p); - visit(rightPadded.getElement(), p); - afterSyntax(rightPadded.getMarkers(), p); - visitSpace(rightPadded.getAfter(), p); - if (suffix != null) { - p.append(suffix); - } - } - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/package-info.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/package-info.java deleted file mode 100644 index 9edd15a9b9..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/internal/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@NonNullApi -@NonNullFields -package org.openrewrite.toml.internal; - -import org.openrewrite.internal.lang.NonNullApi; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/package-info.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/package-info.java deleted file mode 100644 index 66c2c169ce..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@NonNullApi -@NonNullFields -package org.openrewrite.toml; - -import org.openrewrite.internal.lang.NonNullApi; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Expression.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Expression.java deleted file mode 100644 index 4c1d17ad6c..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Expression.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -public interface Expression extends Toml { -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Key.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Key.java deleted file mode 100644 index 9ff6f869cd..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Key.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -public interface Key extends Toml { -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Space.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Space.java deleted file mode 100644 index ab22d03b80..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Space.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; -import lombok.EqualsAndHashCode; -import org.openrewrite.internal.lang.Nullable; - -import java.util.Collections; -import java.util.Map; -import java.util.WeakHashMap; - -/** - * Toml white space. - */ -@EqualsAndHashCode -@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@ref") -public class Space { - public static final Space EMPTY = new Space(""); - - @Nullable - private final String whitespace; - - /* - * Most occurrences of spaces will have no comments or markers and will be repeated frequently throughout a source file. - * e.g.: a single space between keywords, or the common indentation of every line in a block. - * So use flyweights to avoid storing many instances of functionally identical spaces - */ - private static final Map flyweights = Collections.synchronizedMap(new WeakHashMap<>()); - - private Space(@Nullable String whitespace) { - this.whitespace = whitespace == null || whitespace.isEmpty() ? null : whitespace; - } - - @JsonCreator - public static Space build(@Nullable String whitespace) { - if (whitespace == null || whitespace.isEmpty()) { - return Space.EMPTY; - } else if (whitespace.length() <= 100) { - //noinspection StringOperationCanBeSimplified - return flyweights.computeIfAbsent(whitespace, k -> new Space(new String(whitespace))); - } - return new Space(whitespace); - } - - public String getIndent() { - return getWhitespaceIndent(whitespace); - } - - private String getWhitespaceIndent(@Nullable String whitespace) { - if (whitespace == null) { - return ""; - } - int lastNewline = whitespace.lastIndexOf('\n'); - if (lastNewline >= 0) { - return whitespace.substring(lastNewline + 1); - } else if (lastNewline == whitespace.length() - 1) { - return ""; - } - return whitespace; - } - - public String getWhitespace() { - return whitespace == null ? "" : whitespace; - } - - - public Space withWhitespace(String whitespace) { - if (whitespace.isEmpty()) { - return Space.EMPTY; - } - - if (this.whitespace == null || whitespace.equals(this.whitespace)) { - return this; - } - return build(whitespace); - } - - public boolean isEmpty() { - return this == EMPTY; - } - - public static Space format(String formatting) { - return Space.build(formatting); - } - - private static final String[] spaces = { - "·₁", "·₂", "·₃", "·₄", "·₅", "·₆", "·₇", "·₈", "·₉", "·₊" - }; - - private static final String[] tabs = { - "-₁", "-₂", "-₃", "-₄", "-₅", "-₆", "-₇", "-₈", "-₉", "-₊" - }; - - @Override - public String toString() { - StringBuilder printedWs = new StringBuilder(); - int lastNewline = 0; - if (whitespace != null) { - char[] charArray = whitespace.toCharArray(); - for (int i = 0; i < charArray.length; i++) { - char c = charArray[i]; - if (c == '\n') { - printedWs.append("\\n"); - lastNewline = i + 1; - } else if (c == '\r') { - printedWs.append("\\r"); - lastNewline = i + 1; - } else if (c == ' ') { - printedWs.append(spaces[(i - lastNewline) % 10]); - } else if (c == '\t') { - printedWs.append(tabs[(i - lastNewline) % 10]); - } - } - } - - return "Space(whitespace='" + printedWs + "')"; - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TValue.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TValue.java deleted file mode 100644 index 0fec053d0e..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TValue.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -public interface TValue extends Toml { -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Toml.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Toml.java deleted file mode 100644 index 52b761b291..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Toml.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -import org.openrewrite.Tree; -import org.openrewrite.TreeVisitor; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.toml.TomlVisitor; - -public interface Toml extends Tree { - - @SuppressWarnings("unchecked") - @Override - default R accept(TreeVisitor v, P p) { - return (R) acceptToml(v.adapt(TomlVisitor.class), p); - } - - @Override - default

boolean isAcceptable(TreeVisitor v, P p) { - return v.isAdaptableTo(TomlVisitor.class); - } - - @Nullable - default

Toml acceptToml(TomlVisitor

v, P p) { - return v.defaultValue(this, p); - } - - default Space getPrefix() { - return Space.EMPTY; - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlContainer.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlContainer.java deleted file mode 100644 index 823eb45056..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlContainer.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -import com.fasterxml.jackson.annotation.JsonCreator; -import lombok.RequiredArgsConstructor; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.marker.Markers; - -import java.util.List; -import java.util.function.UnaryOperator; - -import static java.util.Collections.emptyList; - -/** - * AST elements that contain lists of trees with some delimiter like function call arguments. - * - * @param The type of the inner list of elements. - */ -public class TomlContainer { - private transient Padding padding; - - private static final TomlContainer EMPTY = new TomlContainer<>(Space.EMPTY, emptyList(), Markers.EMPTY); - - private final Space before; - - private final List> elements; - private final Markers markers; - - private TomlContainer(Space before, List> elements, Markers markers) { - this.before = before; - this.elements = elements; - this.markers = markers; - } - - public static TomlContainer build(List> elements) { - return build(Space.EMPTY, elements, Markers.EMPTY); - } - - @JsonCreator - public static TomlContainer build(Space before, List> elements, Markers markers) { - if (before.isEmpty() && elements.isEmpty()) { - return empty(); - } - return new TomlContainer<>(before, elements, markers); - } - - @SuppressWarnings("unchecked") - public static TomlContainer empty() { - return (TomlContainer) EMPTY; - } - - public TomlContainer withBefore(Space before) { - return this.before == before ? this : build(before, elements, markers); - } - - public TomlContainer withElements(List> elements) { - return this.elements == elements ? this : build(before, elements, markers); - } - - public TomlContainer withMarkers(Markers markers) { - return this.markers == markers ? this : build(before, elements, markers); - } - - public Markers getMarkers() { - return markers; - } - - public List getElements() { - return TomlRightPadded.getElements(elements); - } - - public Space getBefore() { - return before; - } - - public TomlContainer map(UnaryOperator map) { - return getPadding().withElements(ListUtils.map(elements, t -> t.map(map))); - } - - public Space getLastSpace() { - return elements.isEmpty() ? Space.EMPTY : elements.get(elements.size() - 1).getAfter(); - } - - public TomlContainer withLastSpace(Space after) { - return withElements(ListUtils.mapLast(elements, elem -> elem.withAfter(after))); - } - - public Padding getPadding() { - if (padding == null) { - this.padding = new Padding<>(this); - } - return padding; - } - - @RequiredArgsConstructor - public static class Padding { - private final TomlContainer c; - - public List> getElements() { - return c.elements; - } - - public TomlContainer withElements(List> elements) { - return c.elements == elements ? c : build(c.before, c.elements, c.markers); - } - } - - @Nullable - public static

TomlContainer

withElementsNullable(@Nullable TomlContainer

before, @Nullable List

elements) { - if (before == null) { - if (elements == null || elements.isEmpty()) { - return null; - } - return TomlContainer.build(Space.EMPTY, TomlRightPadded.withElements(emptyList(), elements), Markers.EMPTY); - } - if (elements == null || elements.isEmpty()) { - return null; - } - return before.getPadding().withElements(TomlRightPadded.withElements(before.elements, elements)); - } - - public static

TomlContainer

withElements(TomlContainer

before, @Nullable List

elements) { - if (elements == null) { - return before.getPadding().withElements(emptyList()); - } - return before.getPadding().withElements(TomlRightPadded.withElements(before.elements, elements)); - } - - @Override - public String toString() { - return "TomlContainer(before=" + before + ", elementCount=" + elements.size() + ')'; - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlLeftPadded.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlLeftPadded.java deleted file mode 100644 index 896d7682d8..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlLeftPadded.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -import lombok.EqualsAndHashCode; -import lombok.Value; -import lombok.With; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.marker.Markers; - -import java.util.function.UnaryOperator; - -@Value -@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) -@With -public class TomlLeftPadded { - Space before; - T element; - Markers markers; - - public TomlLeftPadded map(UnaryOperator map) { - return withElement(map.apply(element)); - } - - @Nullable - public static TomlLeftPadded withElement(@Nullable TomlLeftPadded before, @Nullable T elements) { - if (before == null) { - if (elements == null) { - return null; - } - return new TomlLeftPadded<>(Space.EMPTY, elements, Markers.EMPTY); - } - if (elements == null) { - return null; - } - return before.withElement(elements); - } - - @Override - public String toString() { - return "ProtoLeftPadded(before=" + before + ", element=" + element.getClass().getSimpleName() + ')'; - } - - public static TomlLeftPadded build(T element) { - return new TomlLeftPadded<>(Space.EMPTY, element, Markers.EMPTY); - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlRightPadded.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlRightPadded.java deleted file mode 100644 index fc45aefd51..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlRightPadded.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.openrewrite.toml.tree; - -import lombok.AccessLevel; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.With; -import lombok.experimental.FieldDefaults; -import org.openrewrite.internal.lang.Nullable; -import org.openrewrite.marker.Markers; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Function; -import java.util.function.UnaryOperator; -import java.util.stream.Collectors; - -/** - * A Toml element that could have trailing space. - * - * @param - */ -@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) -@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) -@Data -public class TomlRightPadded { - @With - T element; - - @With - Space after; - - @With - Markers markers; - - public TomlRightPadded map(UnaryOperator map) { - return withElement(map.apply(element)); - } - - public static List getElements(List> ls) { - List list = new ArrayList<>(); - for (TomlRightPadded l : ls) { - T elem = l.getElement(); - list.add(elem); - } - return list; - } - - public static

List> withElements(List> before, List

elements) { - // a cheaper check for the most common case when there are no changes - if (elements.size() == before.size()) { - boolean hasChanges = false; - for (int i = 0; i < before.size(); i++) { - if (before.get(i).getElement() != elements.get(i)) { - hasChanges = true; - break; - } - } - if (!hasChanges) { - return before; - } - } - - List> after = new ArrayList<>(elements.size()); - Map> beforeById = before.stream().collect(Collectors - .toMap(j -> j.getElement().getId(), Function.identity())); - - for (P t : elements) { - if (beforeById.get(t.getId()) != null) { - TomlRightPadded

found = beforeById.get(t.getId()); - after.add(found.withElement(t)); - } else { - after.add(new TomlRightPadded<>(t, Space.EMPTY, Markers.EMPTY)); - } - } - - return after; - } - - public static TomlRightPadded build(T element) { - return new TomlRightPadded<>(element, Space.EMPTY, Markers.EMPTY); - } - - @Nullable - public static TomlRightPadded withElement(@Nullable TomlRightPadded before, @Nullable T elements) { - if (before == null) { - if (elements == null) { - return null; - } - return new TomlRightPadded<>(elements, Space.EMPTY, Markers.EMPTY); - } - if (elements == null) { - return null; - } - return before.withElement(elements); - } - - @Override - public String toString() { - return "TomlRightPadded(element=" + element.getClass().getSimpleName() + ", after=" + after + ')'; - } -} diff --git a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/package-info.java b/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/package-info.java deleted file mode 100644 index 365bb30cd0..0000000000 --- a/tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2020 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@NonNullApi -@NonNullFields -package org.openrewrite.toml.tree; - -import org.openrewrite.internal.lang.NonNullApi; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/tools/language-parser-builder/src/model/java/generate/GenerateModel.java b/tools/language-parser-builder/src/model/java/generate/GenerateModel.java deleted file mode 100644 index 0ead10722b..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/GenerateModel.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -import lombok.RequiredArgsConstructor; -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; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; - -import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.toList; - -@RequiredArgsConstructor -public class GenerateModel { - static final ExecutionContext ctx = new InMemoryExecutionContext(Throwable::printStackTrace); - - static JavaParser jp() { - return JavaParser.fromJavaVersion() - .classpath(JavaParser.runtimeClasspath()) - .logCompilationWarningsAndErrors(true) - .build(); - } - - final List modelClasses; - - public static void main(String[] args) { - new GenerateModel(jp() - .parse( - List.of( - Paths.get("tools/language-parser-builder/src/model/java/model/Toml.java"), - Paths.get("tools/language-parser-builder/src/model/java/model/Key.java"), - Paths.get("tools/language-parser-builder/src/model/java/model/TValue.java") - ), - null, - ctx - ) - .map(J.CompilationUnit.class::cast) - .toList() - .get(0) - .getClasses() - .get(0) - .getBody() - .getStatements() - .stream() - .filter(J.ClassDeclaration.class::isInstance) - .map(J.ClassDeclaration.class::cast) - .toList()).generate(); - } - - public void generate() { - List results = new ArrayList<>(); - - Path TomlTreePath = Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/Toml.java"); - - List deps = 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"), - Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlContainer.java"), - Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlLeftPadded.java"), - Paths.get("tools/language-parser-builder/src/main/java/org/openrewrite/toml/tree/TomlRightPadded.java") - ); - - 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/internal/TomlPrinter.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(new InMemoryLargeSourceSet(jp().parse(List.of(TomlTreePath), null, ctx).collect(toList())), ctx).getChangeset().getAllResults()); - } - - private void writeResults(List results) { - for (Result result : results) { - try { - Files.writeString(requireNonNull(result.getAfter()).getSourcePath(), - result.getAfter().printAll()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - } -} diff --git a/tools/language-parser-builder/src/model/java/generate/Skip.java b/tools/language-parser-builder/src/model/java/generate/Skip.java deleted file mode 100644 index 64adfade63..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/Skip.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -public @interface Skip { -} diff --git a/tools/language-parser-builder/src/model/java/generate/WriteModel.java b/tools/language-parser-builder/src/model/java/generate/WriteModel.java deleted file mode 100644 index 623705ce01..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/WriteModel.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -import lombok.RequiredArgsConstructor; -import org.openrewrite.Cursor; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaParser; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.JavaVisitor; -import org.openrewrite.java.search.FindAnnotations; -import org.openrewrite.java.tree.*; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.StringJoiner; - -@RequiredArgsConstructor -public class WriteModel extends Recipe { - final List modelClasses; - - @Override - public String getDisplayName() { - return "Write the AST model"; - } - - @Override - public String getDescription() { - return "Expand the model into an AST with Lombok annotations, Padding classes, etc."; - } - - JavaParser.Builder parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()); - - JavaVisitor writeModelClass = new JavaIsoVisitor() { - final JavaTemplate valueModel = JavaTemplate.builder( - """ - @Value - @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) - @With - """ - ).javaParser(parser).build(); - - final JavaTemplate paddedModel = JavaTemplate.builder( - """ - @ToString - @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) - @EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) - @RequiredArgsConstructor - @AllArgsConstructor(access = AccessLevel.PRIVATE) - """ - ).javaParser(parser).build(); - - final JavaTemplate idField = JavaTemplate.builder("@EqualsAndHashCode.Include UUID id;").imports("java.util.UUID").javaParser(parser).build(); - final JavaTemplate prefixField = JavaTemplate.builder("Space prefix;").javaParser(parser).build(); - final JavaTemplate markersField = JavaTemplate.builder("Markers markers;").imports("org.openrewrite.marker.Markers").javaParser(parser).build(); - final JavaTemplate paddingField = JavaTemplate.builder("@Nullable @NonFinal transient WeakReference padding;").javaParser(parser).build(); - final JavaTemplate implementsTree = JavaTemplate.builder("Toml").javaParser(parser).build(); - - final JavaTemplate getPadding = JavaTemplate.builder( - """ - public Padding getPadding() { - Padding p; - if (this.padding == null) { - p = new Padding(this); - this.padding = new WeakReference<>(p); - } else { - p = this.padding.get(); - if (p == null || p.t != this) { - p = new Padding(this); - this.padding = new WeakReference<>(p); - } - } - return p; - } - """ - ).build(); - - final JavaTemplate paddingClass = JavaTemplate.builder( - """ - @RequiredArgsConstructor - public static class Padding { - private final #{} t; - } - """ - ).build(); - - final JavaTemplate acceptMethod = JavaTemplate.builder( - """ - @Override public

Toml acceptToml(TomlVisitor

v, P p) { - return v.visit#{}(this, p); - } - """ - ).javaParser(parser).build(); - - /** - * The accessors in the model class that skips the padding and return the contained element. - */ - final JavaTemplate unwrappedPaddedGetterWither = JavaTemplate.builder( - """ - public #{} get#{}() { - return #{}.getElement(); - } - - public #{} with#{}(#{} #{}) { - //noinspection ConstantConditions - return getPadding().with#{}(Toml#{}Padded.withElement(this.#{}, #{})); - } - """ - ).javaParser(parser).build(); - - final JavaTemplate nullableUnwrappedPaddedGetterWither = JavaTemplate.builder( - """ - @Nullable - public #{} get#{}() { - return #{} == null ? null : #{}.getElement(); - } - - public #{} with#{}(@Nullable #{} #{}) { - if (#{} == null) { - return this.#{} == null ? this : new #{}(#{}); - } - return getPadding().with#{}(Toml#{}Padded.withElement(this.#{}, #{})); - } - """ - ).javaParser(parser).build(); - - /** - * The accessors in the model class that skips the padding and return the contained elements. - */ - final JavaTemplate unwrappedContainerGetterWither = JavaTemplate.builder( - """ - public List<#{}> get#{}() { - return #{}.getElements(); - } - - public #{} with#{}(List<#{}> #{}) { - return getPadding().with#{}(this.#{}.getPadding().withElements(TomlRightPadded.withElements( - this.#{}.getPadding().getElements(), #{})); - } - """ - ).javaParser(parser).build(); - - 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").isEmpty()) { - //noinspection ConstantConditions - return null; - } - - boolean padded = c.getBody().getStatements().stream().anyMatch(this::isPadded); - - if (c.getImplements() == null) { - c = implementsTree.apply(updateCursor(c), c.getCoordinates().addImplementsClause()); - } - - - c = markersField.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement()); - c = prefixField.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement()); - c = idField.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement()); - c = acceptMethod.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), classDecl.getSimpleName()); - - for (Statement statement : c.getBody().getStatements()) { - if (statement instanceof J.VariableDeclarations varDec) { - JavaType.FullyQualified fqn = TypeUtils.asFullyQualified(varDec.getType()); - - JavaType.FullyQualified elementType = null; - if (varDec.getTypeExpression() instanceof J.ParameterizedType typeExpression) { - if (typeExpression.getTypeParameters() != null) { - elementType = TypeUtils.asFullyQualified(typeExpression.getTypeParameters().get(0).getType()); - } - } - - if (fqn != null) { - if (elementType != null) { - c = switch (fqn.getClassName()) { - case "TomlContainer" -> writeContainerGetterWithers(c, varDec, elementType); - case "TomlLeftPadded" -> writePaddedGetterWithers(c, varDec, elementType, "Left"); - case "TomlRightPadded" -> writePaddedGetterWithers(c, varDec, elementType, "Right"); - default -> writeModelGetterWithers(c, varDec); - }; - } else if (padded) { - c = writeModelGetterWithers(c, varDec); - } - } else if (padded) { - c = writeModelGetterWithers(c, varDec); - } - } - } - - if (padded) { - c = paddedModel.apply(updateCursor(c), c.getCoordinates().replaceAnnotations()); - c = paddingField.apply(updateCursor(c), c.getBody().getCoordinates().firstStatement()); - c = getPadding.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement()); - c = paddingClass.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), c.getSimpleName()); - } else { - c = valueModel.apply(updateCursor(c), c.getCoordinates().replaceAnnotations()); - } - - List 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).getLeadingAnnotations().isEmpty() || - (previous instanceof J.VariableDeclarations) && !((J.VariableDeclarations) previous).getLeadingAnnotations().isEmpty()) { - return statement.withPrefix(Space.format("\n\n")); - } - } - return statement; - }))); - - return c; - } - - private J.ClassDeclaration writeModelGetterWithers(J.ClassDeclaration c, J.VariableDeclarations varDec) { - return c.withBody(c.getBody().withStatements(ListUtils.map(c.getBody().getStatements(), statement -> { - if (statement == varDec) { - Cursor cursor = new Cursor(new Cursor(updateCursor(c), c.getBody()), varDec); - statement = withGetterAnnotations.apply(cursor, varDec.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName))); - } - return statement; - }))); - } - - private J.ClassDeclaration writeContainerGetterWithers(J.ClassDeclaration c, J.VariableDeclarations varDec, JavaType.FullyQualified elementType) { - String name = varDec.getVariables().get(0).getSimpleName(); - String capitalizedName = name.substring(0, 1).toUpperCase() + name.substring(1); - String elementTypeName = elementType.getClassName(); - String modelTypeName = c.getSimpleName(); - - J.Block body = unwrappedContainerGetterWither.apply(new Cursor(updateCursor(c), c.getBody()), c.getBody().getCoordinates().lastStatement(), - elementTypeName, capitalizedName, - name, - modelTypeName, capitalizedName, elementTypeName, name, - capitalizedName, name, - name, name); - - return c.withBody(body); - } - - private J.ClassDeclaration writePaddedGetterWithers(J.ClassDeclaration c, J.VariableDeclarations varDec, JavaType.FullyQualified elementType, - String leftOrRight) { - boolean nullable = !FindAnnotations.find(varDec, "@org.openrewrite.internal.lang.Nullable").isEmpty(); - String name = varDec.getVariables().get(0).getSimpleName(); - String capitalizedName = name.substring(0, 1).toUpperCase() + name.substring(1); - String elementTypeName = elementType.getClassName(); - String modelTypeName = c.getSimpleName(); - - J.Block body = c.getBody(); - if (nullable) { - StringJoiner newModelArguments = new StringJoiner(", "); - for (Statement statement : body.getStatements()) { - if (statement instanceof J.VariableDeclarations) { - newModelArguments.add(statement == varDec ? "null" : ((J.VariableDeclarations) statement).getVariables() - .get(0).getSimpleName()); - } - } - body = nullableUnwrappedPaddedGetterWither.apply(new Cursor(getCursor(), body), body.getCoordinates().lastStatement(), - elementTypeName, capitalizedName, name, name, modelTypeName, capitalizedName, - elementTypeName, name, name, name, modelTypeName, newModelArguments.toString(), - capitalizedName, leftOrRight, name, name); - } else { - body = unwrappedPaddedGetterWither.apply(new Cursor(getCursor(), body), body.getCoordinates().lastStatement(), - elementTypeName, capitalizedName, name, - modelTypeName, capitalizedName, elementTypeName, name, - capitalizedName, leftOrRight, name, name); - } - - return c.withBody(body); - } - - boolean isPadded(Statement statement) { - if (!(statement instanceof J.VariableDeclarations)) { - return false; - } - JavaType.FullyQualified type = TypeUtils.asFullyQualified(((J.VariableDeclarations) statement).getType()); - assert type != null; - return type.getClassName().contains("Padded") || type.getClassName().equals("TomlContainer"); - } - }; - - @Override - public JavaVisitor getVisitor() { - return new JavaIsoVisitor<>() { - @Override - public J.Block visitBlock(J.Block block, ExecutionContext ctx) { - Object parent = getCursor().getParentOrThrow().getValue(); - if (!(parent instanceof J.ClassDeclaration) || !((J.ClassDeclaration) parent).getSimpleName().equals("Toml")) { - return block; - } - - J.Block b = block.withStatements(ListUtils.map(block.getStatements(), s -> s instanceof J.ClassDeclaration && - !(((J.ClassDeclaration) s).getSimpleName().equals("CompilationUnit")) ? null : s)); - List statements = new ArrayList<>(b.getStatements()); - statements.addAll(ListUtils.map(modelClasses, - mc -> (J.ClassDeclaration) writeModelClass.visitNonNull(mc, ctx, getCursor().getParentOrThrow()))); - b = b.withStatements(statements); - - return b; - } - }; - } -} diff --git a/tools/language-parser-builder/src/model/java/generate/WritePaddingAccessors.java b/tools/language-parser-builder/src/model/java/generate/WritePaddingAccessors.java deleted file mode 100644 index 3eb3ff742d..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/WritePaddingAccessors.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -import lombok.RequiredArgsConstructor; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaParser; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.JavaVisitor; -import org.openrewrite.java.search.FindAnnotations; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.Statement; -import org.openrewrite.java.tree.TypeUtils; - -import java.util.StringJoiner; - -/** - * TODO Unable to add accessors in the first phase due to some bug in JavaTemplate. - */ -@RequiredArgsConstructor -public class WritePaddingAccessors extends Recipe { - @Override - public String getDisplayName() { - return "Write accessors for padded parts of the model"; - } - - @Override - public String getDescription() { - return "Write accessors for padded parts of the model."; - } - - JavaParser.Builder parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()); - - @RequiredArgsConstructor - class WritePaddingAccessorsVisitor extends JavaIsoVisitor { - final J.ClassDeclaration modelClassDeclaration; - - /** - * The accessors in the Padding class that return the padding wrapped element. - */ - final JavaTemplate paddedGetterWither = JavaTemplate.builder( - """ - #{} - public Toml#{}<#{}> get#{}() { - return t.#{}; - } - - public #{} with#{}(#{}Toml#{}<#{}> #{}) { - return t.#{} == #{} ? t : new #{}(#{}); - } - """ - ).javaParser(parser).build(); - - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - J.ClassDeclaration c = classDecl; - - if (c.getSimpleName().equals("Padding")) { - for (Statement statement : modelClassDeclaration.getBody().getStatements()) { - if (statement instanceof J.VariableDeclarations varDec) { - JavaType.FullyQualified fqn = TypeUtils.asFullyQualified(varDec.getType()); - - JavaType.FullyQualified elementType = null; - if (varDec.getTypeExpression() instanceof J.ParameterizedType typeExpression) { - if (typeExpression.getTypeParameters() != null) { - elementType = TypeUtils.asFullyQualified(typeExpression.getTypeParameters().get(0).getType()); - } - } - - if (fqn != null && elementType != null) { - c = switch (fqn.getClassName()) { - case "TomlContainer" -> writePaddedGetterWithers(c, varDec, elementType, "Container"); - case "TomlLeftPadded" -> writePaddedGetterWithers(c, varDec, elementType, "LeftPadded"); - case "TomlRightPadded" -> writePaddedGetterWithers(c, varDec, elementType, "RightPadded"); - default -> c; - }; - } - } - } - - return c; - } - - return super.visitClassDeclaration(classDecl, ctx); - } - - private J.ClassDeclaration writePaddedGetterWithers(J.ClassDeclaration c, J.VariableDeclarations varDec, JavaType.FullyQualified elementType, - String leftOrRight) { - boolean nullable = !FindAnnotations.find(varDec, "@org.openrewrite.internal.lang.Nullable").isEmpty(); - String name = varDec.getVariables().get(0).getSimpleName(); - String capitalizedName = name.substring(0, 1).toUpperCase() + name.substring(1); - String elementTypeName = elementType.getClassName(); - String modelTypeName = modelClassDeclaration.getSimpleName(); - - StringJoiner newModelArguments = new StringJoiner(", "); - for (Statement paddingStatement : modelClassDeclaration.getBody().getStatements()) { - if (paddingStatement instanceof J.VariableDeclarations) { - newModelArguments.add(paddingStatement == varDec ? name : "t." + ((J.VariableDeclarations) paddingStatement).getVariables() - .get(0).getSimpleName()); - } - } - - c = paddedGetterWither.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), - nullable ? "@Nullable " : "", leftOrRight, elementTypeName, capitalizedName, - name, modelTypeName, capitalizedName, - nullable ? "@Nullable " : "", leftOrRight, - elementTypeName, name, name, name, modelTypeName, newModelArguments); - - return c; - } - } - - @Override - public JavaVisitor getVisitor() { - return new JavaIsoVisitor<>() { - @Override - public J.Block visitBlock(J.Block block, ExecutionContext ctx) { - Object parent = getCursor().getParentOrThrow().getValue(); - if (!(parent instanceof J.ClassDeclaration) || !((J.ClassDeclaration) parent).getSimpleName().equals("Toml")) { - return block; - } - - J.Block b = block; - - b = b.withStatements(ListUtils.map(b.getStatements(), - mc -> mc instanceof J.ClassDeclaration ? - (Statement) new WritePaddingAccessorsVisitor((J.ClassDeclaration) mc) - .visitNonNull(mc, ctx, getCursor().getParentOrThrow()) : - mc) - ); - - return b; - } - }; - } -} diff --git a/tools/language-parser-builder/src/model/java/generate/WritePrinter.java b/tools/language-parser-builder/src/model/java/generate/WritePrinter.java deleted file mode 100644 index ee152fc22b..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/WritePrinter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -import lombok.RequiredArgsConstructor; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaParser; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.JavaVisitor; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.Statement; -import org.openrewrite.java.tree.TypeUtils; - -import java.util.List; -import java.util.StringJoiner; - -import static java.util.Objects.requireNonNull; - -@RequiredArgsConstructor -public class WritePrinter extends Recipe { - final List modelClasses; - - @Override - public String getDisplayName() { - return "Write the boilerplate for `TomlPrinter`"; - } - - @Override - public String getDescription() { - return "Every print method starts with `visitSpace` then `visitMarkers`. " + - "Every model element is visited. An engineer must fill in the places " + - "where keywords are grammatically required."; - } - - JavaParser.Builder parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()); - - @Override - public JavaVisitor getVisitor() { - return new JavaIsoVisitor<>() { - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - J.ClassDeclaration c = classDecl; - - for (J.ClassDeclaration modelClass : missingVisitorMethods(c)) { - String modelTypeName = modelClass.getSimpleName(); - String paramName = modelTypeName.substring(0, 1).toLowerCase() + modelTypeName.substring(1); - - StringJoiner fields = new StringJoiner("\n "); - for (Statement statement : modelClass.getBody().getStatements()) { - if (statement instanceof J.VariableDeclarations varDec) { - J.VariableDeclarations.NamedVariable namedVariable = varDec.getVariables().get(0); - String name = namedVariable.getSimpleName(); - String capitalizedName = name.substring(0, 1).toUpperCase() + name.substring(1); - - JavaType.FullyQualified elemType = requireNonNull(TypeUtils.asFullyQualified(varDec.getType())); - switch (elemType.getClassName()) { - case "TomlLeftPadded": - fields.add("visitLeftPadded(\"\"," + paramName + ".getPadding().get" + capitalizedName + "(), p);"); - break; - case "TomlRightPadded": - fields.add("visitRightPadded(" + paramName + ".getPadding().get" + capitalizedName + "(), \"\", p);"); - break; - case "TomlContainer": - fields.add("visitContainer(\"\", " + paramName + ".getPadding().get" + capitalizedName + "(), \"\", \"\", p);"); - break; - case "List": - String loopVar = paramName.substring(0, 1); - if (loopVar.equals("p")) { - loopVar = "pp"; - } - String typeParam = ((J.Identifier) requireNonNull(((J.ParameterizedType) varDec.getTypeExpression()).getTypeParameters()).get(0)).getSimpleName(); - fields.add("for(Toml." + typeParam + " " + loopVar + " : " + paramName + ".get" + capitalizedName + "()) {\n" + - " // TODO print each element\n" + - "}"); - break; - case "String": - fields.add("p.append(" + paramName + ".get" + capitalizedName + "());"); - break; - case "Integer": - fields.add("p.append(" + paramName + ".get" + capitalizedName + "().toString());"); - break; - default: - if (elemType.getClassName().startsWith("Toml")) { - fields.add("visit(" + paramName + ".get" + capitalizedName + "(), p);"); - } - } - } - } - - StringBuilder template = new StringBuilder(); - - JavaTemplate visitMethod = JavaTemplate.builder( - "public Toml visit#{}(Toml.#{} #{}, PrintOutputCapture

p) {" + - " visitSpace(#{}.getPrefix(), p);" + - " visitMarkers(#{}.getMarkers(), p);" + - " #{}" + - " return #{};" + - "}" - ) - .javaParser(parser) -// .doAfterVariableSubstitution(System.out::println) - .doBeforeParseTemplate(template::append) - .build(); - - try { - c = visitMethod.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), - modelTypeName, modelTypeName, paramName, - paramName, - paramName, - fields, - paramName); - } catch (Throwable t) { - System.out.println(template); - throw t; - } - } - - return c; - } - - private List missingVisitorMethods(J.ClassDeclaration visitorClass) { - return ListUtils.map(modelClasses, modelClass -> { - for (Statement statement : visitorClass.getBody().getStatements()) { - if (statement instanceof J.MethodDeclaration m) { - if (m.getSimpleName().endsWith(modelClass.getSimpleName())) { - return null; - } - } - } - return modelClass; - }); - } - }; - } -} diff --git a/tools/language-parser-builder/src/model/java/generate/WriteVisitorMethods.java b/tools/language-parser-builder/src/model/java/generate/WriteVisitorMethods.java deleted file mode 100644 index a0e7363ef9..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/WriteVisitorMethods.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package generate; - -import lombok.RequiredArgsConstructor; -import org.openrewrite.ExecutionContext; -import org.openrewrite.Recipe; -import org.openrewrite.internal.ListUtils; -import org.openrewrite.java.JavaIsoVisitor; -import org.openrewrite.java.JavaParser; -import org.openrewrite.java.JavaTemplate; -import org.openrewrite.java.JavaVisitor; -import org.openrewrite.java.search.FindAnnotations; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.Statement; -import org.openrewrite.java.tree.TypeUtils; - -import java.util.List; -import java.util.StringJoiner; - -import static java.util.Objects.requireNonNull; - -@RequiredArgsConstructor -public class WriteVisitorMethods extends Recipe { - final List modelClasses; - - @Override - public String getDisplayName() { - return "Write TOML boilerplate"; - } - - @Override - public String getDescription() { - return "Write the boilerplate for `TomlVisitor` and `TomlIsoVisitor`."; - } - - @Override - public JavaVisitor getVisitor() { - return new JavaVisitor<>() { - @Override - public J visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - return switch (classDecl.getSimpleName()) { - case "TomlVisitor" -> - writeVisitorMethods.visitNonNull(classDecl, ctx, getCursor().getParentOrThrow()); - case "TomlIsoVisitor" -> - writeIsoVisitorMethods.visitNonNull(classDecl, ctx, getCursor().getParentOrThrow()); - default -> classDecl; - }; - - } - }; - } - - JavaParser.Builder parser = JavaParser.fromJavaVersion().classpath(JavaParser.runtimeClasspath()); - - private final JavaVisitor writeVisitorMethods = new JavaIsoVisitor<>() { - - final JavaTemplate visitMethod = JavaTemplate.builder( - """ - public Toml visit#{}(Toml.#{} #{}, P p) { - Toml.#{} #{} = #{}; - #{} = #{}.withPrefix(visitSpace(#{}.getPrefix(), p)); - #{} = #{}.withMarkers(visitMarkers(#{}.getMarkers(), p)); - #{} - return #{}; - } - """ - ).javaParser(parser).build(); - - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - J.ClassDeclaration c = classDecl; - - for (J.ClassDeclaration modelClass : missingVisitorMethods(c)) { - String modelTypeName = modelClass.getSimpleName(); - String paramName = modelTypeName.substring(0, 1).toLowerCase() + modelTypeName.substring(1); - String varName = paramName.substring(0, 1); - if (varName.equals("p")) { - varName = "pp"; - } - - StringJoiner fields = new StringJoiner("\n "); - for (Statement statement : modelClass.getBody().getStatements()) { - if (statement instanceof J.VariableDeclarations varDec) { - boolean nullable = !FindAnnotations.find(varDec, "@org.openrewrite.internal.lang.Nullable").isEmpty(); - String name = varDec.getVariables().get(0).getSimpleName(); - String capitalizedName = name.substring(0, 1).toUpperCase() + name.substring(1); - - JavaType.FullyQualified elemType = requireNonNull(TypeUtils.asFullyQualified(varDec.getType())); - switch (elemType.getClassName()) { - case "TomlLeftPadded": - if (nullable) { - fields.add("if(" + varName + ".getPadding().get" + capitalizedName + "() != null) {"); - } - fields.add(varName + " = " + varName + ".getPadding().with" + capitalizedName + "(visitLeftPadded(" + - varName + ".getPadding().get" + capitalizedName + "(), p));"); - if (nullable) { - fields.add("}"); - } - break; - case "TomlRightPadded": - if (nullable) { - fields.add("if(" + varName + ".getPadding().get" + capitalizedName + "() != null) {"); - } - fields.add(varName + " = " + varName + ".getPadding().with" + capitalizedName + "(visitRightPadded(" + - varName + ".getPadding().get" + capitalizedName + "(), p));"); - if (nullable) { - fields.add("}"); - } - break; - case "TomlContainer": - fields.add(varName + " = " + varName + ".getPadding().with" + capitalizedName + "(visitContainer(" + varName + ".getPadding().get" + capitalizedName + "(), p));"); - break; - case "List": - J.ParameterizedType parameterizedType = requireNonNull((J.ParameterizedType) varDec.getTypeExpression()); - String elemListType = requireNonNull(TypeUtils.asFullyQualified(requireNonNull(parameterizedType.getTypeParameters()).get(0).getType())) - .getClassName(); - fields.add(varName + " = " + varName + ".with" + capitalizedName + "(ListUtils.map(" + - varName + ".get" + capitalizedName + "(), t -> (" + elemListType + - ") visit(t, p)));"); - break; - default: - if (elemType.getClassName().startsWith("Toml")) { - fields.add(varName + " = " + varName + ".with" + capitalizedName + "((" + - elemType.getClassName() + ") visit(" + varName + ".get" + capitalizedName + "(), p));"); - } - } - } - } - c = visitMethod.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), - modelTypeName, modelTypeName, paramName, - modelTypeName, varName, paramName, - varName, varName, varName, - varName, varName, varName, - fields, - varName); - } - - return c; - } - }; - - private final JavaVisitor writeIsoVisitorMethods = new JavaIsoVisitor<>() { - final JavaTemplate isoVisitMethod = JavaTemplate.builder( - """ - @Override - public Toml.#{} visit#{}(Toml.#{} #{}, P p) { - return (Toml.#{}) super.visit#{}(#{}, p); - } - """ - ).javaParser(parser).build(); - - @Override - public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { - J.ClassDeclaration c = classDecl; - - for (J.ClassDeclaration modelClass : missingVisitorMethods(c)) { - String modelTypeName = modelClass.getSimpleName(); - String paramName = modelTypeName.substring(0, 1).toLowerCase() + modelTypeName.substring(1); - c = isoVisitMethod.apply(updateCursor(c), c.getBody().getCoordinates().lastStatement(), - modelTypeName, modelTypeName, modelTypeName, paramName, - modelTypeName, modelTypeName, paramName); - } - - return c; - } - }; - - private List missingVisitorMethods(J.ClassDeclaration visitorClass) { - return ListUtils.map(modelClasses, modelClass -> { - for (Statement statement : visitorClass.getBody().getStatements()) { - if (statement instanceof J.MethodDeclaration m) { - if (m.getSimpleName().endsWith(modelClass.getSimpleName())) { - return null; - } - } - } - return modelClass; - }); - } -} diff --git a/tools/language-parser-builder/src/model/java/generate/package-info.java b/tools/language-parser-builder/src/model/java/generate/package-info.java deleted file mode 100644 index e052a3f31a..0000000000 --- a/tools/language-parser-builder/src/model/java/generate/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@NonNullApi -package generate; - -import org.openrewrite.internal.lang.NonNullApi; diff --git a/tools/language-parser-builder/src/model/java/model/Expression.java b/tools/language-parser-builder/src/model/java/model/Expression.java deleted file mode 100644 index 09b1c007b6..0000000000 --- a/tools/language-parser-builder/src/model/java/model/Expression.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package model; - -public interface Expression { -} diff --git a/tools/language-parser-builder/src/model/java/model/Key.java b/tools/language-parser-builder/src/model/java/model/Key.java deleted file mode 100644 index f9df9410d7..0000000000 --- a/tools/language-parser-builder/src/model/java/model/Key.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package model; - -public interface Key { -} diff --git a/tools/language-parser-builder/src/model/java/model/TValue.java b/tools/language-parser-builder/src/model/java/model/TValue.java deleted file mode 100644 index f2b0a321ea..0000000000 --- a/tools/language-parser-builder/src/model/java/model/TValue.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package model; - -public interface TValue { -} diff --git a/tools/language-parser-builder/src/model/java/model/Toml.java b/tools/language-parser-builder/src/model/java/model/Toml.java deleted file mode 100644 index 16d999e7f9..0000000000 --- a/tools/language-parser-builder/src/model/java/model/Toml.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * https://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package model; - -import org.openrewrite.toml.tree.TomlContainer; -import org.openrewrite.toml.tree.TomlLeftPadded; - -import java.nio.charset.Charset; -import java.nio.file.Path; - -public interface Toml { - - class Document { - Path sourcePath; - Charset charset; - TomlContainer expressions; - } - - class KeyValue implements Expression { - Key key; - TomlLeftPadded value; - } - - class BareKey implements Key { - String value; - } - - class DottedKey implements Key { - TomlContainer keys; - } - - class LiteralString implements Key, TValue { - String value; - String valueSource; - } - - class Array { - TomlContainer values; - } -} diff --git a/tools/settings.gradle.kts b/tools/settings.gradle.kts deleted file mode 100644 index 5d6869110b..0000000000 --- a/tools/settings.gradle.kts +++ /dev/null @@ -1,8 +0,0 @@ -pluginManagement { - repositories { - mavenLocal() - gradlePluginPortal() - } -} - -include("language-parser-builder")