Make Java classes final if possible

Also add private no-arg constructors for classes that aren't meant to be instantiated.
This commit is contained in:
translatenix
2024-04-27 20:31:57 -07:00
committed by Daniel Chao
parent ae69e4776f
commit e49a36e318
57 changed files with 89 additions and 70 deletions

View File

@@ -16,7 +16,7 @@
package org.pkl.core;
/** A logger that keeps messages locally and can return them. */
public class BufferedLogger implements Logger {
public final class BufferedLogger implements Logger {
private final StringBuilder builder = new StringBuilder();
private final Logger logger;

View File

@@ -21,6 +21,8 @@ import java.io.PrintWriter;
/** Predefined {@link Logger}s. */
@SuppressWarnings("unused")
public final class Loggers {
private Loggers() {}
/** Returns a logger that discards log messages. */
public static Logger noop() {
return new Logger() {

View File

@@ -27,7 +27,7 @@ import org.pkl.core.util.Nullable;
* <p>Create a new module source via {@link #create(URI, String)}, or one of the various helper
* factory methods.
*/
public class ModuleSource {
public final class ModuleSource {
public static ModuleSource create(URI uri, @Nullable String text) {
return new ModuleSource(uri, text);
}

View File

@@ -27,7 +27,7 @@ import java.util.Set;
* Information about the Pkl release that the current program runs on. This class is the Java
* equivalent of standard library module {@code pkl.release}.
*/
public class Release {
public final class Release {
private static final String SOURCE_CODE_HOMEPAGE = "https://github.com/apple/pkl/";
private static final String DOCUMENTATION_HOMEPAGE = "https://pkl-lang.org/main/";

View File

@@ -15,7 +15,7 @@
*/
package org.pkl.core;
public class RendererException extends RuntimeException {
public final class RendererException extends RuntimeException {
public RendererException(String message) {
super(message);
}

View File

@@ -20,7 +20,7 @@ package org.pkl.core;
*
* <p>{@link SecurityManagerException#getMessage()} is passed to users when errors arise.
*/
public class SecurityManagerException extends Exception {
public final class SecurityManagerException extends Exception {
public SecurityManagerException(String message) {
super(message);
}

View File

@@ -22,6 +22,8 @@ import org.pkl.core.runtime.VmExceptionBuilder;
import org.pkl.core.runtime.VmSet;
public final class VmModifier {
private VmModifier() {}
// user-facing modifiers
public static final int ABSTRACT = 0x1;

View File

@@ -46,7 +46,7 @@ import org.pkl.core.util.Pair;
* <li>read expressions
* </ul>
*/
public class ImportsAndReadsParser
public final class ImportsAndReadsParser
extends AbstractAstBuilder<@Nullable List<Pair<String, SourceSection>>> {
/** Parses a module, and collects all imports and reads. */
@@ -69,7 +69,7 @@ public class ImportsAndReadsParser
}
@Override
public @Nullable List<Pair<String, SourceSection>> visitModuleExtendsOrAmendsClause(
public List<Pair<String, SourceSection>> visitModuleExtendsOrAmendsClause(
ModuleExtendsOrAmendsClauseContext ctx) {
var importStr = doVisitSingleLineConstantStringPart(ctx.stringConstant().ts);
var sourceSection = createSourceSection(ctx.stringConstant());

View File

@@ -19,7 +19,7 @@ package org.pkl.core.http;
* Indicates that an error occurred while initializing an HTTP client. A common example is an error
* reading or parsing a certificate.
*/
public class HttpClientInitException extends RuntimeException {
public final class HttpClientInitException extends RuntimeException {
public HttpClientInitException(String message) {
super(message);
}

View File

@@ -29,7 +29,7 @@ import javax.annotation.concurrent.ThreadSafe;
* send.
*/
@ThreadSafe
class LazyHttpClient implements HttpClient {
final class LazyHttpClient implements HttpClient {
private final Supplier<HttpClient> supplier;
private final Object lock = new Object();

View File

@@ -25,7 +25,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FileResolver {
public final class FileResolver {
private FileResolver() {}
public static List<PathElement> listElements(URI baseUri) throws IOException {

View File

@@ -38,7 +38,7 @@ import org.pkl.core.util.LateInit;
* <p>NOTE: Do not initialize two resolvers for the same jar or zip file. Instead, share the same
* resolver for that jar or zip file.
*/
public class ModulePathResolver implements AutoCloseable {
public final class ModulePathResolver implements AutoCloseable {
private final Iterable<Path> modulePath;
private final Object lock = new Object();

View File

@@ -80,7 +80,7 @@ public class PathElement {
return "PathElement{" + "name='" + name + '\'' + ", isDirectory=" + isDirectory + '}';
}
public static class TreePathElement extends PathElement {
public static final class TreePathElement extends PathElement {
private final EconomicMap<String, TreePathElement> children = EconomicMaps.create();
public TreePathElement(String name, boolean isDirectory) {

View File

@@ -35,7 +35,7 @@ import org.pkl.core.runtime.VmExceptionBuilder;
import org.pkl.core.util.EconomicMaps;
import org.pkl.core.util.json.Json.JsonParseException;
public class ProjectDependenciesManager {
public final class ProjectDependenciesManager {
public static final String PKL_PROJECT_FILENAME = "PklProject";
public static final String PKL_PROJECT_DEPS_FILENAME = "PklProject.deps.json";

View File

@@ -70,7 +70,7 @@ import org.pkl.core.util.json.JsonWriter;
*/
@SuppressWarnings({"JavadocLinkAsPlainText", "unused"})
// incorrectly thinks link within sample metadata is a JavaDoc link
public class DependencyMetadata {
public final class DependencyMetadata {
public static DependencyMetadata parse(String input) throws JsonParseException {
var parsed = Json.parseObject(input);

View File

@@ -25,7 +25,7 @@ import org.pkl.core.util.ErrorMessages;
* The canonical URI of an asset within a package, i.e., a package URI with a fragment path. For
* example, {@code package://example.com/my/package@1.0.0#/my/module.pkl}
*/
public class PackageAssetUri {
public final class PackageAssetUri {
private final URI uri;
private final PackageUri packageUri;
private final Path assetPath;

View File

@@ -17,7 +17,7 @@ package org.pkl.core.packages;
import org.pkl.core.util.ErrorMessages;
public class PackageLoadError extends RuntimeException {
public final class PackageLoadError extends RuntimeException {
private final String messageName;
private final Object[] arguments;

View File

@@ -60,7 +60,9 @@ import org.pkl.core.util.Nullable;
import org.pkl.core.util.Pair;
import org.pkl.core.util.json.Json.JsonParseException;
class PackageResolvers {
final class PackageResolvers {
private PackageResolvers() {}
abstract static class AbstractPackageResolver implements PackageResolver {
@GuardedBy("lock")
private final EconomicMap<PackageUri, DependencyMetadata> cachedDependencyMetadata;
@@ -245,7 +247,7 @@ class PackageResolvers {
*
* <p>This gets used when the cache dir is not set.
*/
static class InMemoryPackageResolver extends AbstractPackageResolver {
static final class InMemoryPackageResolver extends AbstractPackageResolver {
@GuardedBy("lock")
private final EconomicMap<PackageUri, EconomicMap<String, ByteBuffer>> cachedEntries =
EconomicMaps.create();
@@ -406,7 +408,7 @@ class PackageResolvers {
* <p>Uses the built-in zip file system in {@link jdk.nio.zipfs} for reading files from the zip
* archive.
*/
static class DiskCachedPackageResolver extends AbstractPackageResolver {
static final class DiskCachedPackageResolver extends AbstractPackageResolver {
private final Path cacheDir;
private final Path tmpDir;

View File

@@ -23,7 +23,7 @@ import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.IoUtils;
import org.pkl.core.util.Nullable;
public class PackageUri {
public final class PackageUri {
private final URI uri;
private final Version version;
private final String pathWithoutVersion;

View File

@@ -20,7 +20,9 @@ import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.json.Json.FormatException;
import org.pkl.core.util.json.Json.JsonParseException;
public class PackageUtils {
public final class PackageUtils {
private PackageUtils() {}
public static PackageUri parsePackageUriWithoutChecksums(Object obj)
throws JsonParseException, URISyntaxException {
if (!(obj instanceof String string)) {

View File

@@ -20,7 +20,7 @@ import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.misc.IntervalSet;
import org.pkl.core.parser.antlr.PklParser;
class ErrorStrategy extends DefaultErrorStrategy {
final class ErrorStrategy extends DefaultErrorStrategy {
@Override
protected void reportNoViableAlternative(Parser parser, NoViableAltException e) {
var builder = new StringBuilder();

View File

@@ -67,7 +67,7 @@ public abstract class LexParseException extends RuntimeException {
return this;
}
public static class LexError extends LexParseException {
public static final class LexError extends LexParseException {
public LexError(String message, int line, int column, int length) {
super(message, line, column, length, Integer.MAX_VALUE);
}
@@ -79,7 +79,7 @@ public abstract class LexParseException extends RuntimeException {
}
}
public static class IncompleteInput extends ParseError {
public static final class IncompleteInput extends ParseError {
public IncompleteInput(String message, int line, int column, int length) {
super(message, line, column, length, Integer.MAX_VALUE - 1);
}

View File

@@ -23,7 +23,7 @@ import org.antlr.v4.runtime.*;
import org.pkl.core.parser.antlr.PklLexer;
import org.pkl.core.util.Nullable;
public class Lexer {
public final class Lexer {
public static final Set<Integer> KEYWORD_TYPES;
public static final Set<String> KEYWORD_NAMES;

View File

@@ -29,7 +29,7 @@ import org.pkl.core.parser.antlr.PklParser;
import org.pkl.core.parser.antlr.PklParser.*;
import org.pkl.core.util.Nullable;
public class Parser {
public final class Parser {
@TruffleBoundary
public PklParser createParser(
TokenStream stream, @Nullable List<LexParseException> errorCollector) {

View File

@@ -29,7 +29,7 @@ import org.pkl.core.util.ErrorMessages;
* package://example.com/foo/bar@0}. Does not include a URI's userinfo, query params or fragment
* segments.
*/
public class CanonicalPackageUri {
public final class CanonicalPackageUri {
private final URI baseUri;
private final int majorVersion;

View File

@@ -21,7 +21,7 @@ import org.pkl.core.packages.Dependency.RemoteDependency;
import org.pkl.core.packages.PackageUri;
import org.pkl.core.util.Nullable;
public class DeclaredDependencies {
public final class DeclaredDependencies {
private final Map<String, RemoteDependency> remoteDependencies;
private final Map<String, DeclaredDependencies> localDependencies;
private final URI projectFileUri;

View File

@@ -43,7 +43,7 @@ import org.pkl.core.util.Nullable;
*
* <p>Resolved dependencies have URI `projectpackage` to indicate that they should be project-local.
*/
public class ProjectDependenciesResolver {
public final class ProjectDependenciesResolver {
private final Project project;
private final PackageResolver packageResolver;
private final Writer logWriter;

View File

@@ -75,7 +75,7 @@ import org.pkl.core.util.json.JsonWriter;
* </pre>
* </code>
*/
public class ProjectDeps {
public final class ProjectDeps {
private static final Set<Integer> supportedSchemaVersions = Set.of(1);
private final EconomicMap<CanonicalPackageUri, Dependency> resolvedDependencies;

View File

@@ -78,7 +78,7 @@ import org.pkl.core.util.Pair;
* <li><em>thepackage@1.0.0.zip.sha256</em> - the SHA-256 checksum of the zip archive
* </ul>
*/
public class ProjectPackager {
public final class ProjectPackager {
/**
* Modification time value for all zip entries in a package, to ensure that archives are
* reproducible.

View File

@@ -40,7 +40,9 @@ import org.pkl.core.util.EconomicMaps;
*
* <p>File systems are only closed when the last usage of it closes.
*/
public class FileSystemManager {
public final class FileSystemManager {
private FileSystemManager() {}
private static final EconomicMap<URI, FileSystem> fileSystems = EconomicMaps.create();
private static final Map<FileSystem, Integer> counts = new IdentityHashMap<>();
@@ -98,7 +100,7 @@ public class FileSystemManager {
}
}
private static class Handle extends FileSystem {
private static final class Handle extends FileSystem {
final FileSystem delegate;

View File

@@ -22,7 +22,9 @@ import org.pkl.core.ValueFormatter;
import org.pkl.core.util.Nullable;
import org.pkl.core.util.StringSimilarity;
public class KeyLookupSuggestions {
public final class KeyLookupSuggestions {
private KeyLookupSuggestions() {}
private static final StringSimilarity STRING_SIMILARITY = new StringSimilarity();
// 0.77 is just about low enough to consider two three-character
// keys that differ in their first character similar

View File

@@ -24,7 +24,7 @@ import org.pkl.core.util.EconomicMaps;
import org.pkl.core.util.Nullable;
import org.pkl.core.util.StringSimilarity;
public class MemberLookupSuggestions {
public final class MemberLookupSuggestions {
private static final StringSimilarity STRING_SIMILARITY = new StringSimilarity();
// 0.77 is just about low enough to consider two three-character
// names that differ in their first character similar

View File

@@ -17,7 +17,7 @@ package org.pkl.core.runtime;
import static org.pkl.core.PClassInfo.pklProjectUri;
public class ProjectModule extends StdLibModule {
public final class ProjectModule extends StdLibModule {
private static final VmTyped instance = VmUtils.createEmptyModule();
static {

View File

@@ -24,7 +24,7 @@ import org.pkl.core.StackFrame;
import org.pkl.core.ast.MemberNode;
import org.pkl.core.util.Nullable;
class StackTraceGenerator {
final class StackTraceGenerator {
private final VmException exception;
private final List<StackFrame> frames = new ArrayList<>();

View File

@@ -21,7 +21,7 @@ import java.util.function.Function;
import org.pkl.core.StackFrame;
import org.pkl.core.util.Nullable;
public class StackTraceRenderer {
public final class StackTraceRenderer {
private final Function<StackFrame, StackFrame> frameTransformer;
public StackTraceRenderer(Function<StackFrame, StackFrame> frameTransformer) {

View File

@@ -32,7 +32,7 @@ import org.pkl.core.util.MutableBoolean;
import org.pkl.core.util.MutableReference;
/** Runs test results examples and facts. */
public class TestRunner {
public final class TestRunner {
private static final PklConverter converter = new PklConverter(VmMapping.empty());
private final boolean overwrite;
private final StackFrameTransformer stackFrameTransformer;

View File

@@ -47,7 +47,7 @@ import org.pkl.core.util.Nullable;
* preferable but isn't currently used. One problem with special formatting is that error
* output doesn't always go to a terminal and hence may be rendered verbatim.)
*/
public class VmExceptionBuilder {
public final class VmExceptionBuilder {
private @Nullable Object receiver;

View File

@@ -24,7 +24,7 @@ import org.pkl.core.util.ErrorMessages;
import org.pkl.core.util.Nullable;
import org.pkl.core.util.StringBuilderWriter;
public class VmExceptionRenderer {
public final class VmExceptionRenderer {
private final @Nullable StackTraceRenderer stackTraceRenderer;
/**

View File

@@ -19,7 +19,7 @@ import java.nio.file.Path;
import java.nio.file.spi.FileTypeDetector;
import org.pkl.core.util.Nullable;
public class VmFileDetector extends FileTypeDetector {
public final class VmFileDetector extends FileTypeDetector {
@Override
public @Nullable String probeContentType(Path path) {
var fileName = path.getFileName();

View File

@@ -17,7 +17,7 @@ package org.pkl.core.runtime;
import java.util.List;
public class VmStackOverflowException extends VmException {
public final class VmStackOverflowException extends VmException {
public VmStackOverflowException(StackOverflowError e) {
super("stackOverflow", e, true, new Object[0], List.of(), null, null, null, null);

View File

@@ -28,7 +28,7 @@ import org.pkl.core.util.MutableBoolean;
* <p>Currently prints fully qualified class name for outermost object (if rendered value is an
* object) and omits class names otherwise.
*/
public class VmValueRenderer {
public final class VmValueRenderer {
private final int lengthLimit;
private final String leadingOrTrailingNewline;
private final String interiorNewline;

View File

@@ -39,7 +39,7 @@ import org.pkl.executor.spi.v1.ExecutorSpiException;
import org.pkl.executor.spi.v1.ExecutorSpiOptions;
import org.pkl.executor.spi.v1.ExecutorSpiOptions2;
public class ExecutorSpiImpl implements ExecutorSpi {
public final class ExecutorSpiImpl implements ExecutorSpi {
private static final int MAX_HTTP_CLIENTS = 3;
// Don't create a new HTTP client for every executor request.

View File

@@ -17,7 +17,8 @@ package org.pkl.core.stdlib;
import org.pkl.core.runtime.Identifier;
public class PathConverterSupport {
final class PathConverterSupport {
private PathConverterSupport() {}
public static boolean pathMatches(Iterable<Object> pathSpec, Iterable<Object> path) {
var pathIterator = path.iterator();

View File

@@ -32,7 +32,7 @@ import org.pkl.core.util.json.JsonHandler;
import org.pkl.core.util.json.JsonParser;
import org.pkl.core.util.json.ParseException;
public class ParserNodes {
public final class ParserNodes {
private ParserNodes() {}
public abstract static class parse extends ExternalMethod1Node {

View File

@@ -34,7 +34,7 @@ import org.pkl.core.stdlib.PklConverter;
import org.pkl.core.stdlib.xml.RendererNodes.Renderer;
import org.pkl.core.util.EconomicMaps;
public class JUnitReport implements TestReport {
public final class JUnitReport implements TestReport {
@Override
public void report(TestResults results, Writer writer) throws IOException {

View File

@@ -23,7 +23,7 @@ import org.pkl.core.runtime.TestResults.Failure;
import org.pkl.core.runtime.TestResults.TestResult;
import org.pkl.core.util.StringUtils;
public class SimpleReport implements TestReport {
public final class SimpleReport implements TestReport {
@Override
public void report(TestResults results, Writer writer) throws IOException {

View File

@@ -19,7 +19,9 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.pkl.core.runtime.VmExceptionBuilder;
public class ByteArrayUtils {
public final class ByteArrayUtils {
private ByteArrayUtils() {}
public static String md5(byte[] input) {
return hash(input, "MD5");
}
@@ -38,7 +40,7 @@ public class ByteArrayUtils {
/**
* Implemented directly instead of using JRE's `new BigInteger.toString(16)` so we can AOT-compile
* this and not need a truffle boundary.
* this and do not need a Truffle boundary.
*/
public static String toHex(byte[] hash) {
// return new BigInteger(hash).toString(16);

View File

@@ -19,7 +19,7 @@ import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class CollectionUtils {
public final class CollectionUtils {
private static final float LOAD_FACTOR = 0.75f;
private CollectionUtils() {}

View File

@@ -20,7 +20,9 @@ import java.util.Locale;
import java.util.ResourceBundle;
import java.util.stream.*;
public class ErrorMessages {
public final class ErrorMessages {
private ErrorMessages() {}
public static String create(String messageName, Object... args) {
var locale = Locale.getDefault();
String errorMessage =

View File

@@ -33,14 +33,16 @@ import org.pkl.core.module.ModuleKey;
import org.pkl.core.module.PathElement;
import org.pkl.core.runtime.ReaderBase;
public class GlobResolver {
public static class InvalidGlobPatternException extends Exception {
public final class GlobResolver {
private GlobResolver() {}
public static final class InvalidGlobPatternException extends Exception {
public InvalidGlobPatternException(String message) {
super(message);
}
}
public static class ResolvedGlobElement {
public static final class ResolvedGlobElement {
private final String path;
private final URI uri;

View File

@@ -17,7 +17,7 @@ package org.pkl.core.util;
import java.io.Writer;
public class StringBuilderWriter extends Writer {
public final class StringBuilderWriter extends Writer {
private final StringBuilder builder;
public StringBuilderWriter(StringBuilder builder) {

View File

@@ -29,7 +29,7 @@ import javax.annotation.concurrent.Immutable;
* @author Thibault Debatty
*/
@Immutable
public class StringSimilarity {
public final class StringSimilarity {
private static final double DEFAULT_THRESHOLD = 0.7;
private static final int THREE = 3;
private static final double JW_COEF = 0.1;

View File

@@ -68,7 +68,7 @@ import org.pkl.core.util.Nullable;
* </table>
*/
@SuppressWarnings("unused")
public class Json {
public final class Json {
@FunctionalInterface
public interface Mapper<R> {
R apply(Object arg) throws Exception;

View File

@@ -127,11 +127,11 @@ import org.pkl.core.util.Nullable;
* @since 1.6
*/
@SuppressWarnings({"unused", "UnusedReturnValue"})
public class JsonWriter implements Closeable, Flushable {
public final class JsonWriter implements Closeable, Flushable {
/** An array with no elements requires no separators or newlines before it is closed. */
static final int EMPTY_ARRAY = 1;
/** A array with at least one value requires a comma and newline before the next element. */
/** An array with at least one value requires a comma and newline before the next element. */
static final int NONEMPTY_ARRAY = 2;
/** An object with no name/value pairs requires no separators or newlines before it is closed. */
@@ -200,7 +200,7 @@ public class JsonWriter implements Closeable, Flushable {
*
* @param indent a string containing only whitespace.
*/
public final void setIndent(String indent) {
public void setIndent(String indent) {
if (indent.isEmpty()) {
this.indent = null;
this.separator = ":";
@@ -221,7 +221,7 @@ public class JsonWriter implements Closeable, Flushable {
* <li>Numbers may be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}.
* </ul>
*/
public final void setLenient(boolean lenient) {
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
@@ -236,7 +236,7 @@ public class JsonWriter implements Closeable, Flushable {
* them to the stream. Without this setting, your XML/HTML encoder should replace these characters
* with the corresponding escape sequences.
*/
public final void setHtmlSafe(boolean htmlSafe) {
public void setHtmlSafe(boolean htmlSafe) {
this.htmlSafe = htmlSafe;
this.escaper = new JsonEscaper(htmlSafe);
}
@@ -244,7 +244,7 @@ public class JsonWriter implements Closeable, Flushable {
/**
* Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.
*/
public final boolean isHtmlSafe() {
public boolean isHtmlSafe() {
return htmlSafe;
}
@@ -252,7 +252,7 @@ public class JsonWriter implements Closeable, Flushable {
* Sets whether object members are serialized when their value is null. This has no impact on
* array elements. The default is true.
*/
public final void setSerializeNulls(boolean serializeNulls) {
public void setSerializeNulls(boolean serializeNulls) {
this.serializeNulls = serializeNulls;
}
@@ -260,7 +260,7 @@ public class JsonWriter implements Closeable, Flushable {
* Returns true if object members are serialized when their value is null. This has no impact on
* array elements. The default is true.
*/
public final boolean getSerializeNulls() {
public boolean getSerializeNulls() {
return serializeNulls;
}

View File

@@ -17,7 +17,7 @@ package org.pkl.core.util.properties;
import java.io.BufferedWriter;
public class PropertiesUtils {
public final class PropertiesUtils {
// Bitmap of characters that need escaping ('\t', '\n', '\f', '\r', ' ', '!', '#', ':', '=', '\\')
// in four 32-bit segments.

View File

@@ -18,7 +18,7 @@ package org.pkl.core.util.yaml;
import org.pkl.core.util.IoUtils;
@SuppressWarnings("DuplicatedCode")
public class Yaml11Emitter extends YamlEmitter {
public final class Yaml11Emitter extends YamlEmitter {
public Yaml11Emitter(StringBuilder builder, String indent) {
super(builder, indent);
}

View File

@@ -18,7 +18,7 @@ package org.pkl.core.util.yaml;
import org.pkl.core.util.IoUtils;
@SuppressWarnings("DuplicatedCode")
public class Yaml12Emitter extends YamlEmitter {
public final class Yaml12Emitter extends YamlEmitter {
public Yaml12Emitter(StringBuilder builder, String indent) {
super(builder, indent);
}