Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: dependencies
packages:
- "@typespec/http-client-java"
---

Use JavaParser for unused-import removal, eliminating Google Java Format and its runtime dependencies along with the generator's `--add-exports` JVM options.
3 changes: 3 additions & 0 deletions packages/http-client-java/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ As a Node.js package, the entry of the library is written in TypeScript, under `
As a Java code generator, part of the implementation is written in Java, under `generator` folder.
Java code is packaged into a JAR file, and included in the Node.js package. The JAR file is called at runtime by TypeScript code.

Generated Java is analyzed with JavaParser to remove unused imports and order the remaining imports, then formatted with Eclipse JDT using `generator\eclipse-format-azure-sdk-for-java.xml`.
Import cleanup does not require resolving the generated SDK's dependencies.

## Build and Pack

["Setup.ps1" script](https://github.com/microsoft/typespec/blob/main/packages/http-client-java/Setup.ps1) builds TypeScript code and Java code, and packs them into "typespec-http-client-java-[version].tgz".
Expand Down
7 changes: 0 additions & 7 deletions packages/http-client-java/emitter/src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,6 @@ export async function $onEmit(context: EmitContext<EmitterOptions>) {
`-XX:StartFlightRecording=settings="${perfProfile}",filename="${options["output-dir"]}/typespecPerf.jfr",maxsize=1gb`,
);
}
// These module modifications are needed by google-java-format
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED");
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED");
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED");
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED");
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED");
javaArgs.push("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED");
javaArgs.push("-jar");
javaArgs.push(jarFileName);
javaArgs.push(codeModelFileName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,6 @@
<artifactId>javaparser-core</artifactId>
<version>3.27.0</version>
</dependency>
<!-- 1.24.0 is the last version that supports Java 11 -->
<dependency>
<groupId>com.google.googlejavaformat</groupId>
<artifactId>google-java-format</artifactId>
<version>1.24.0</version>
</dependency>
<!-- 3.27.0 aligns with the version used when Spotless uses Eclipse 4.21 / 4.21.0. -->
<!-- In the future when this is upgraded it might slightly change code formatting. -->
<dependency>
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
package com.microsoft.typespec.http.client.generator.core.postprocessor;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.microsoft.typespec.http.client.generator.core.MockUnitJavagen;
import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings;
import com.microsoft.typespec.http.client.generator.core.postprocessor.implementation.CodeFormatterUtil;
import io.clientcore.core.serialization.json.JsonReader;
import io.clientcore.core.utils.IOExceptionCheckedFunction;
import java.io.IOException;
Expand Down Expand Up @@ -65,6 +67,22 @@ public void emptyBatchDoesNotResolveAReadme() {
assertTrue(host.output.isEmpty());
}

@Test
public void invalidJavaIsReportedAcrossTheBatchBeforeWritingFiles() {
Host host = new Host();
Map<String, String> files = new LinkedHashMap<>();
files.put("Valid.java", "class Valid {}");
files.put("First.java", "class First { void broken(;) {} }");
files.put("Second.java", "class Second { void broken(;) {} }");

IllegalStateException exception = assertThrows(IllegalStateException.class,
() -> CodeFormatterUtil.formatCode(files, host, LoggerFactory.getLogger(PostprocessorBatchTests.class)));

assertTrue(exception.getMessage().contains("First.java"));
assertTrue(exception.getMessage().contains("Second.java"));
assertTrue(host.output.isEmpty());
}

private static final class Host extends MockUnitJavagen {
private String readme;
private int configurationReads;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,23 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.StaticJavaParser;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

public class CodeFormatterUtilTests {
Expand Down Expand Up @@ -119,6 +125,151 @@ public void importsAndCommentsArePreserved() {
assertEquals(formatted, CodeFormatterUtil.formatCode(Map.of("Example.java", formatted)).get(0));
}

@ParameterizedTest(name = "{0}")
@MethodSource("importUsageCases")
public void removesOnlyUnusedImports(String description, String source, List<String> expectedImports) {
String formatted = CodeFormatterUtil.formatCode(Map.of("Example.java", source)).get(0);

assertEquals(expectedImports,
formatted.lines().filter(line -> line.startsWith("import ")).collect(Collectors.toList()));
assertEquals(formatted, CodeFormatterUtil.formatCode(Map.of("Example.java", formatted)).get(0));
}

private static Stream<Arguments> importUsageCases() {
return Stream.of(
Arguments.of("strings, comments, and declaration names are not references",
String.join("\n", "package test;", "import java.util.ArrayList;", "import java.util.Locale;",
"import java.util.Set;", "import java.util.function.Supplier;", "class Example {",
" // Set and Supplier are mentioned only in comments.", " String text = \"ArrayList\";",
" int Set;", " void Locale() {}", "}"),
List.of()),
Arguments.of("unresolved types, annotations, nested types, and static members are references",
String.join("\n", "package test;", "import com.example.Marker;", "import com.example.Model;",
"import com.example.Outer.Inner;", "import static com.example.Outer.StaticInner;",
"import static com.example.Values.VALUE;", "import static com.example.Values.create;",
"@Marker class Example {", " Model value = create();", " Inner[] nested;",
" StaticInner other;", " Object constant = VALUE;", "}"),
List.of("import static com.example.Outer.StaticInner;", "import static com.example.Values.VALUE;",
"import static com.example.Values.create;", "import com.example.Marker;",
"import com.example.Model;", "import com.example.Outer.Inner;")),
Arguments.of("qualified references do not use an imported selector",
String.join("\n", "package test;", "import java.util.List;",
"import static java.util.Collections.emptyList;", "import static java.lang.Integer.MAX_VALUE;",
"class Example {", " java.util.List<String> values = java.util.Collections.emptyList();",
" int maximum = Integer.MAX_VALUE;", "}"),
List.of()),
Arguments.of("method references and qualified annotations do not use imported selectors",
String.join("\n", "package test;", "import com.example.Factory;", "import com.example.Marker;",
"import java.util.function.Supplier;", "import static com.example.Factory.create;",
"@com.example.Marker class Example {", " Supplier<Factory> factory = Factory::create;", "}"),
List.of("import com.example.Factory;", "import java.util.function.Supplier;")),
Arguments.of("wildcard imports are retained conservatively",
String.join("\n", "package test;", "import java.util.*;", "import static java.util.Collections.*;",
"class Example {}"),
List.of("import static java.util.Collections.*;", "import java.util.*;")),
Arguments.of("java.lang and same-package imports are redundant",
String.join("\n", "package test;", "import java.lang.String;", "import java.lang.*;",
"import test.Model;", "import test.*;", "import static java.lang.Math.max;", "class Example {",
" String text;", " Model model;", " int value = max(1, 2);", "}"),
List.of("import static java.lang.Math.max;")),
Arguments.of("Javadoc links, values, see tags, and exceptions retain their imports",
String.join("\n", "package test;", "import com.example.Owner;", "import com.example.Argument;",
"import com.example.Problem;", "import com.example.Useful;", "/**",
" * {@link Owner#method(Argument) label}.", " * {@linkplain Useful Other}.",
" * {@value Owner#VALUE}.", " * @see Owner#method(Argument argument)", " */", "class Example {",
" /** @throws Problem when the call fails */", " void call() {}", "}"),
List.of("import com.example.Argument;", "import com.example.Owner;", "import com.example.Problem;",
"import com.example.Useful;")),
Arguments.of("Javadoc parameter types include arrays and varargs but not qualified selectors",
String.join("\n", "package test;", "import com.example.Owner;", "import com.example.Parameter;",
"import com.example.ArrayElement;", "import java.util.List;", "/**",
" * {@link Owner#call(Parameter[], java.util.List, ArrayElement...) label}.", " */",
"class Example {}"),
List.of("import com.example.ArrayElement;", "import com.example.Owner;",
"import com.example.Parameter;")),
Arguments.of("Javadoc parameter names are not type references",
String.join("\n", "package test;", "import com.example.Owner;", "import com.example.Parameter;",
"import com.example.ArrayElement;", "import com.example.Unused;", "/**",
" * {@link Owner#call(Parameter Unused, ArrayElement... elements) label}.", " */",
"class Example {}"),
List.of("import com.example.ArrayElement;", "import com.example.Owner;",
"import com.example.Parameter;")),
Arguments.of("Javadoc prose, code, literal, HTML, and quoted see text are not references",
String.join("\n", "package test;", "import java.util.List;", "import java.util.Set;",
"import java.time.Instant;", "/**", " * List, {@code Instant}, and {@literal Set}.",
" * @see \"List\"", " * @see <a href=\"https://example.com/Instant\">Set</a>", " */",
"class Example {}"),
List.of()),
Arguments.of("orphan Javadoc does not retain imports",
String.join("\n", "package test;", "import java.time.Instant;", "class Example {",
" /** {@link Instant} */", "}"),
List.of()),
Arguments.of("an empty Javadoc link does not prevent import removal",
String.join("\n", "package test;", "import java.util.Set;", "/** {@link} */", "class Example {}"),
List.of()));
}

@Test
public void removingAnInlineImportPreservesTheFollowingDeclaration() {
String formatted
= CodeFormatterUtil.formatCode(Map.of("Example.java", "import java.util.Set; public class Example {}"))
.get(0);

assertFalse(formatted.contains("import "));
assertTrue(formatted.contains("public class Example"));
}

@Test
public void removingAnImportPreservesItsTrailingComment() {
String source
= String.join("\r\n", "// File header.", "package test;", "import java.util.Set; // Keep this explanation.",
"/** Class documentation. */", "public class Example {}", "");

String formatted = CodeFormatterUtil.formatCode(Map.of("Example.java", source)).get(0);

assertFalse(formatted.contains("import "));
assertTrue(formatted.contains("// File header."));
assertTrue(formatted.contains("// Keep this explanation."));
assertTrue(formatted.contains("/** Class documentation. */"));
assertTrue(formatted.contains("public class Example"));
}

@Test
public void preservesModuleServiceImports() {
String source
= String.join("\n", "import com.example.Service;", "import com.example.Provider;", "import java.util.Set;",
"module example {", " uses Service;", " provides Service with Provider;", "}", "");

String formatted = CodeFormatterUtil.formatCode(Map.of("module-info.java", source)).get(0);

assertTrue(formatted.contains("import com.example.Service;"));
assertTrue(formatted.contains("import com.example.Provider;"));
assertFalse(formatted.contains("import java.util.Set;"));
assertTrue(formatted.contains("uses Service;"));
assertTrue(formatted.contains("provides Service with Provider;"));
}

@Test
public void respectsTabWidthAndRetainsJavadocReferencesWithoutCommentAttribution() {
ParserConfiguration original = StaticJavaParser.getParserConfiguration();
ParserConfiguration configured = new ParserConfiguration().setTabSize(4).setAttributeComments(false);
StaticJavaParser.setConfiguration(configured);
try {
String source = String.join("\r\n", "package test;", "\timport java.util.Set;",
"\timport java.time.Instant;", "/** {@link Instant} */", "class Example {}", "");

String formatted = CodeFormatterUtil.formatCode(Map.of("Example.java", source)).get(0);

assertTrue(formatted.contains("import java.time.Instant;"));
assertFalse(formatted.contains("import java.util.Set;"));
assertTrue(formatted.contains("class Example"));
assertSame(configured, StaticJavaParser.getParserConfiguration());
assertFalse(configured.isAttributeComments());
} finally {
StaticJavaParser.setConfiguration(original);
}
}

@Test
public void errorsAreAggregatedAcrossFiles() {
Map<String, String> files = new LinkedHashMap<>();
Expand Down
8 changes: 0 additions & 8 deletions packages/http-client-java/generator/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,6 @@
</systemPropertyVariables>
<forkCount>1</forkCount>
<testFailureIgnore>false</testFailureIgnore>
<argLine>
--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED
--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>

Expand Down
Loading