Fix IntelliJ warnings in Java code

Fix all IntelliJ warnings in Java production code except for
bogus spelling warnings and warnings about unused public methods.
Also fix some warnings emitted by Code->Inspect Code.

Changes made:
- use text block instead of string concatenation
- extract method to avoid code duplication
- use switch expression
- fix Javadoc syntax and spelling
- fix spelling in comment
- increase class visibility to match visibility of use site
- delete overriding method with same implementation
- use String.isEmpty() and StringBuilder.isEmpty()
- add @Serial annotation
- make field final
- remove unused field
- remove unused private method
- remove exceptions that aren't thrown from throws clause
- insert non-null assertion
- annotate overriding method with @Nonnull
- suppress warning
- delete unused class (WriteAuxiliarySlotNode)
- add final modifier
- remove unused error message
- repeat @Nullable modifier in overriding method
- remove never thrown exception from throws clause
- remove redundant suppression
This commit is contained in:
translatenix
2024-04-26 20:32:48 -07:00
committed by Daniel Chao
parent 5feaa2aaf7
commit ae69e4776f
51 changed files with 148 additions and 302 deletions

View File

@@ -20,7 +20,7 @@ import javax.lang.model.type.TypeMirror
* - Generated Truffle node classes for stdlib members.
* These classes are located in subpackages of `org.pkl.core.stdlib`
* and identified via their `@GeneratedBy` annotations.
* - `@PklName` annotations on hand-written node classes from which Truffle node classes are generated.
* - `@PklName` annotations on handwritten node classes from which Truffle node classes are generated.
*/
class MemberRegistryGenerator : AbstractProcessor() {
private val truffleNodeClassSuffix = "NodeGen"

View File

@@ -83,24 +83,15 @@ public enum DurationUnit {
/** Converts this unit to a {@link java.util.concurrent.TimeUnit}. */
public TimeUnit toTimeUnit() {
switch (this) {
case NANOS:
return TimeUnit.NANOSECONDS;
case MICROS:
return TimeUnit.MICROSECONDS;
case MILLIS:
return TimeUnit.MILLISECONDS;
case SECONDS:
return TimeUnit.SECONDS;
case MINUTES:
return TimeUnit.MINUTES;
case HOURS:
return TimeUnit.HOURS;
case DAYS:
return TimeUnit.DAYS;
default:
throw new AssertionError("Unknown duration unit: " + this);
}
return switch (this) {
case NANOS -> TimeUnit.NANOSECONDS;
case MICROS -> TimeUnit.MICROSECONDS;
case MILLIS -> TimeUnit.MILLISECONDS;
case SECONDS -> TimeUnit.SECONDS;
case MINUTES -> TimeUnit.MINUTES;
case HOURS -> TimeUnit.HOURS;
case DAYS -> TimeUnit.DAYS;
};
}
@Override

View File

@@ -109,8 +109,7 @@ public abstract class PType implements Serializable {
}
public static final class Constrained extends PType {
private static final long serialVersionUID = 0L;
@Serial private static final long serialVersionUID = 0L;
private final PType baseType;
private final List<String> constraints;

View File

@@ -45,7 +45,7 @@ public final class StackFrameTransformers {
return frame;
};
public static StackFrameTransformer replacePackageUriWithSourceCodeUrl =
public static final StackFrameTransformer replacePackageUriWithSourceCodeUrl =
frame -> {
var uri = URI.create(frame.getModuleUri());
if (!uri.getScheme().equalsIgnoreCase("package")) {

View File

@@ -16,18 +16,8 @@
package org.pkl.core;
import java.io.IOException;
import org.pkl.core.util.ArrayCharEscaper;
public final class ValueFormatter {
private static final ArrayCharEscaper charEscaper =
ArrayCharEscaper.builder()
.withEscape('\n', "\\n")
.withEscape('\r', "\\r")
.withEscape('\t', "\\t")
.withEscape('"', "\\\"")
.withEscape('\\', "\\\\")
.build();
private static final ValueFormatter BASIC = new ValueFormatter(false, false);
private static final ValueFormatter WITH_CUSTOM_DELIMITERS = new ValueFormatter(false, true);

View File

@@ -60,8 +60,9 @@ public final class ValueRenderers {
* Creates a renderer for {@link java.util.Properties} file format. If {@code omitNullProperties}
* is {@code true}, object properties and map entries whose value is {@code null} will not be
* rendered. If {@code restrictCharset} is {@code true} characters outside the printable US-ASCII
* charset range will be rendered as Unicode escapes (see
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.3).
* charset range will be rendered as <a
* href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.3">Unicode
* escapes</a>.
*/
public static ValueRenderer properties(
Writer writer, boolean omitNullProperties, boolean restrictCharset) {

View File

@@ -21,7 +21,7 @@ import org.pkl.core.util.LateInit;
import org.pkl.core.util.Nullable;
/**
* A semantic version (https://semver.org/spec/v2.0.0.html).
* A <a href="https://semver.org/spec/v2.0.0.html">semantic version</a>.
*
* <p>This class guarantees that valid semantic version numbers are handled correctly, but does
* <em>not</em> guarantee that invalid semantic version numbers are rejected.

View File

@@ -1924,26 +1924,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
var functionName = toIdentifier(ctx.Identifier());
var argCtx = ctx.argumentList();
var receiver = visitExpr(ctx.expr());
var currentScope = symbolTable.getCurrentScope();
var constLevel = currentScope.getConstLevel();
var needsConst = false;
if (receiver instanceof OuterNode) {
var outerScope = getParentLexicalScope();
if (outerScope != null) {
needsConst =
switch (constLevel) {
case MODULE -> outerScope.isModuleScope();
case ALL -> outerScope.getConstLevel() != ConstLevel.ALL;
case NONE -> false;
};
}
} else if (receiver instanceof GetModuleNode) {
needsConst = constLevel != ConstLevel.NONE;
} else if (receiver instanceof ThisNode) {
var constDepth = currentScope.getConstDepth();
needsConst = constLevel == ConstLevel.ALL && constDepth == -1;
}
var needsConst = needsConst(receiver);
if (ctx.t.getType() == PklLexer.QDOT) {
//noinspection ConstantConditions
@@ -2008,24 +1989,7 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
}
}
var constLevel = symbolTable.getCurrentScope().getConstLevel();
var needsConst = false;
if (receiver instanceof OuterNode) {
var outerScope = getParentLexicalScope();
if (outerScope != null) {
needsConst =
switch (constLevel) {
case MODULE -> outerScope.isModuleScope();
case ALL -> outerScope.getConstLevel() != ConstLevel.ALL;
case NONE -> false;
};
}
} else if (receiver instanceof GetModuleNode) {
needsConst = constLevel != ConstLevel.NONE;
} else if (receiver instanceof ThisNode) {
var constDepth = symbolTable.getCurrentScope().getConstDepth();
needsConst = constLevel == ConstLevel.ALL && constDepth == -1;
}
var needsConst = needsConst(receiver);
if (ctx.t.getType() == PklLexer.QDOT) {
return new NullPropagatingOperationNode(
sourceSection,
@@ -2127,6 +2091,29 @@ public final class AstBuilder extends AbstractAstBuilder<Object> {
return ctx.es.stream().map(this::visitExpr).toArray(ExpressionNode[]::new);
}
private boolean needsConst(ExpressionNode receiver) {
var scope = symbolTable.getCurrentScope();
var constLevel = scope.getConstLevel();
var needsConst = false;
if (receiver instanceof OuterNode) {
var outerScope = getParentLexicalScope();
if (outerScope != null) {
needsConst =
switch (constLevel) {
case MODULE -> outerScope.isModuleScope();
case ALL -> outerScope.getConstLevel() != ConstLevel.ALL;
case NONE -> false;
};
}
} else if (receiver instanceof GetModuleNode) {
needsConst = constLevel != ConstLevel.NONE;
} else if (receiver instanceof ThisNode) {
var constDepth = scope.getConstDepth();
needsConst = constLevel == ConstLevel.ALL && constDepth == -1;
}
return needsConst;
}
private Identifier toIdentifier(TerminalNode node) {
return Identifier.get(node.getText());
}

View File

@@ -223,10 +223,6 @@ public final class SymbolTable {
return scope;
}
private boolean isConst() {
return constLevel.isConst();
}
/**
* Returns the lexical depth from the current scope to the top-most scope that is const. Depth
* is 0-indexed, and -1 means that the scope is not a const scope.

View File

@@ -65,9 +65,9 @@ public abstract class EqualNode extends ExpressionNode {
}
/**
* This method effectively covers `VmValue left, VmValue right` but is implemented in a more
* efficient way. See:
* https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces
* This method effectively covers `VmValue left, VmValue right` but is implemented in a <a
* href="https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces">more
* efficient way</a>.
*/
@Specialization(
guards = {"left.getClass() == leftJavaClass", "right.getClass() == leftJavaClass"},

View File

@@ -65,9 +65,9 @@ public abstract class NotEqualNode extends ExpressionNode {
}
/**
* This method effectively covers `VmValue left, VmValue right` but is implemented in a more
* efficient way. See:
* https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces
* This method effectively covers `VmValue left, VmValue right` but is implemented in a <a
* href="https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces">more
* efficient way</a>.
*/
@Specialization(
guards = {"left.getClass() == leftJavaClass", "right.getClass() == leftJavaClass"},

View File

@@ -78,7 +78,7 @@ public abstract class GeneratorMemberNode extends PklNode {
* `ObjectData.forBindings`. - 3 `FrameSlot`s for `i`, `key`, and `value`
*/
@ValueType
static final class ObjectData {
public static final class ObjectData {
// member count is exact iff every for/when body has exactly one member
ObjectData(int minMemberCount, int length) {
this.members = EconomicMaps.create(minMemberCount);

View File

@@ -107,7 +107,7 @@ public abstract class PropertiesLiteralNode extends SpecializedObjectLiteralNode
// Ultimately, this lambda or a lambda returned from it will call one of the other
// specializations,
// which will perform the "isValidXYZ" guard check.
// That said, to flag non-sensical amendments early, this specialization could have a guard to
// That said, to flag nonsensical amendments early, this specialization could have a guard to
// check
// that this amendment is at least one of a valid listing, mapping, or object amendment (modulo
// parameters).

View File

@@ -67,6 +67,7 @@ public abstract class SpecializedObjectLiteralNode extends ObjectLiteralNode {
// only runs once per VmClass (which often means once per PropertiesLiteralNode)
// unless an XYZUncached specialization is active
@SuppressWarnings("ExtractMethodRecommender")
@TruffleBoundary
@Idempotent
protected boolean checkIsValidTypedAmendment(Object parent) {

View File

@@ -49,10 +49,6 @@ public final class ImportNode extends AbstractImportNode {
assert importUri.isAbsolute();
}
public URI getImportUri() {
return importUri;
}
public Object executeGeneric(VirtualFrame frame) {
if (importedModule == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();

View File

@@ -23,7 +23,6 @@ import org.pkl.core.ast.ExpressionNode;
import org.pkl.core.runtime.VmUtils;
public class ReadEnclosingAuxiliarySlotNode extends ExpressionNode {
private final int slot;
private final int levelsUp;

View File

@@ -22,7 +22,6 @@ import com.oracle.truffle.api.source.SourceSection;
import org.pkl.core.ast.ExpressionNode;
public abstract class ReadFrameSlotNode extends ExpressionNode {
private final int slot;
protected ReadFrameSlotNode(SourceSection sourceSection, int slot) {

View File

@@ -1,31 +0,0 @@
/**
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
*
* 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.pkl.core.ast.frame;
import com.oracle.truffle.api.frame.VirtualFrame;
import org.pkl.core.ast.PklNode;
public class WriteAuxiliarySlotNode extends PklNode {
private final int slot;
public WriteAuxiliarySlotNode(int slot) {
this.slot = slot;
}
public void evalGeneric(VirtualFrame frame, Object value) {
frame.setAuxiliarySlot(slot, value);
}
}

View File

@@ -50,8 +50,9 @@ public abstract class IsInstanceOfNode extends PklNode {
}
/**
* This method effectively covers `VmValue value` but is implemented in a more efficient way. See:
* https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces
* This method effectively covers `VmValue value` but is implemented in a <a
* href="https://www.graalvm.org/22.0/graalvm-as-a-platform/language-implementation-framework/TruffleLibraries/#strategy-2-java-interfaces">more
* efficient way</a>.
*/
@Specialization(guards = "value.getClass() == valueJavaClass", limit = "99")
protected boolean evalVmValue(

View File

@@ -61,8 +61,9 @@ public final class ObjectMember extends Member {
/**
* Tells if this member is a property.
*
* <p>Not named `isProperty()` to work around https://bugs.openjdk.java.net/browse/JDK-8185424
* (which is apparently triggered by `-Xdoclint:none`).
* <p>Not named `isProperty()` to work around <a
* href="https://bugs.openjdk.java.net/browse/JDK-8185424">JDK-8185424</a> (which is apparently
* triggered by `-Xdoclint:none`).
*/
public boolean isProp() {
return name != null;

View File

@@ -44,6 +44,7 @@ import org.pkl.core.ast.member.UntypedObjectMemberNode;
import org.pkl.core.runtime.*;
import org.pkl.core.util.EconomicMaps;
import org.pkl.core.util.LateInit;
import org.pkl.core.util.Nonnull;
import org.pkl.core.util.Nullable;
public abstract class TypeNode extends PklNode {
@@ -1683,7 +1684,7 @@ public abstract class TypeNode extends PklNode {
}
@Override
public VmTypeAlias getVmTypeAlias() {
public @Nonnull VmTypeAlias getVmTypeAlias() {
return typeAlias;
}

View File

@@ -151,13 +151,12 @@ public final class ModuleKeys {
}
@Override
public String loadSource() throws IOException {
public String loadSource() {
return text;
}
@Override
public ResolvedModuleKey resolve(SecurityManager securityManager)
throws IOException, SecurityManagerException {
public ResolvedModuleKey resolve(SecurityManager securityManager) {
return this;
}
@@ -272,11 +271,6 @@ public final class ModuleKeys {
return this;
}
@Override
public boolean isCached() {
return true;
}
@Override
public ModuleKey getOriginal() {
return this;
@@ -469,11 +463,6 @@ public final class ModuleKeys {
return true;
}
@Override
public boolean isLocal() {
return false;
}
@Override
public boolean isGlobbable() {
return false;

View File

@@ -25,7 +25,7 @@ import org.pkl.core.util.EconomicMaps;
import org.pkl.core.util.Nullable;
public class PathElement {
public static Comparator<PathElement> comparator =
public static final Comparator<PathElement> comparator =
(o1, o2) -> {
if (o1.isDirectory && !o2.isDirectory) {
return 1;

View File

@@ -50,10 +50,11 @@ public class ProjectDependenciesManager {
private Map<String, Dependency> myDependencies = null;
@GuardedBy("lock")
private EconomicMap<PackageUri, Map<String, Dependency>> localPackageDependencies = null;
private final EconomicMap<PackageUri, Map<String, Dependency>> localPackageDependencies =
EconomicMaps.create();
@GuardedBy("lock")
private EconomicMap<PackageUri, Map<String, Dependency>> packageDependencies =
private final EconomicMap<PackageUri, Map<String, Dependency>> packageDependencies =
EconomicMaps.create();
private final Object lock = new Object();
@@ -74,7 +75,6 @@ public class ProjectDependenciesManager {
}
var projectDeps = getProjectDeps();
myDependencies = doBuildResolvedDependenciesForProject(declaredDependencies, projectDeps);
localPackageDependencies = EconomicMaps.create();
for (var localPkg : declaredDependencies.getLocalDependencies().values()) {
ensureLocalProjectDependencyInitialized(localPkg, projectDeps);
}
@@ -83,7 +83,6 @@ public class ProjectDependenciesManager {
private void ensureLocalProjectDependencyInitialized(
DeclaredDependencies localProjectDependencies, ProjectDeps projectDeps) {
assert localPackageDependencies != null;
// turn `package:` scheme into `projectpackage`: scheme
var uri = PackageUri.create("project" + localProjectDependencies.getMyPackageUri());
if (localPackageDependencies.containsKey(uri)) {

View File

@@ -339,7 +339,7 @@ class PackageResolvers {
}
@Override
public List<PathElement> doListElements(PackageAssetUri uri, Checksums checksums)
public List<PathElement> doListElements(PackageAssetUri uri, @Nullable Checksums checksums)
throws IOException, SecurityManagerException {
var packageUri = uri.getPackageUri();
ensurePackageDownloaded(packageUri, checksums);
@@ -351,7 +351,7 @@ class PackageResolvers {
}
@Override
public boolean doHasElement(PackageAssetUri uri, Checksums checksums)
public boolean doHasElement(PackageAssetUri uri, @Nullable Checksums checksums)
throws IOException, SecurityManagerException {
var packageUri = uri.getPackageUri();
ensurePackageDownloaded(packageUri, checksums);

View File

@@ -86,7 +86,7 @@ public class ProjectDeps {
return parse(input);
}
public static ProjectDeps parse(String input) throws JsonParseException, URISyntaxException {
public static ProjectDeps parse(String input) throws JsonParseException {
var parsed = Json.parseObject(input);
var schemaVersion = parsed.getInt("schemaVersion");
if (!supportedSchemaVersions.contains(schemaVersion)) {

View File

@@ -64,13 +64,8 @@ public final class Identifier implements Comparable<Identifier> {
public static final Identifier CONVERTERS = get("converters");
public static final Identifier USE_MAPPING = get("useMapping");
// members of pkl.base#IntSeq, pkl.base#RegexMatch
public static final Identifier START = get("start");
public static final Identifier END = get("end");
// members of pkl.base#RegexMatch
public static final Identifier VALUE = get("value");
public static final Identifier GROUPS = get("groups");
// members of pkl.base#Module
public static final Identifier OUTPUT = get("output");
@@ -111,10 +106,6 @@ public final class Identifier implements Comparable<Identifier> {
public static final Identifier PB = get("pb");
public static final Identifier PIB = get("pib");
// members of pkl.base#Pair
public static final Identifier FIRST = get("first");
public static final Identifier SECOND = get("second");
// members of pkl.base#Function(1-5)
public static final Identifier APPLY = get("apply");
@@ -147,8 +138,6 @@ public final class Identifier implements Comparable<Identifier> {
// members of pkl.yaml
public static final Identifier MAX_COLLECTION_ALIASES = get("maxCollectionAliases");
public static final Identifier DEPENDENCIES = get("dependencies");
// common in lambdas etc
public static final Identifier IT = get("it");

View File

@@ -15,7 +15,6 @@
*/
package org.pkl.core.runtime;
import com.oracle.truffle.api.CompilerDirectives;
import java.net.URI;
public final class MathModule extends StdLibModule {
@@ -30,10 +29,4 @@ public final class MathModule extends StdLibModule {
public static VmTyped getModule() {
return instance;
}
@CompilerDirectives.TruffleBoundary
private static VmClass loadClass(String className) {
var theModule = getModule();
return (VmClass) VmUtils.readMember(theModule, Identifier.get(className));
}
}

View File

@@ -88,7 +88,7 @@ public final class VmClass extends VmValue {
private final Object allHiddenPropertyNamesLock = new Object();
// Helps to to overcome recursive initialization issues
// Helps to overcome recursive initialization issues
// between classes and annotations in pkl.base.
@CompilationFinal private volatile boolean isInitialized;
@@ -497,7 +497,6 @@ public final class VmClass extends VmValue {
public EconomicMap<Object, ObjectMember> getDynamicToTypedMembers() {
synchronized (dynamicToTypedMembersLock) {
if (__dynamicToTypedMembers == null) {
//noinspection ConstantConditions
__dynamicToTypedMembers =
createDelegatingMembers(
(member) ->
@@ -515,7 +514,6 @@ public final class VmClass extends VmValue {
public EconomicMap<Object, ObjectMember> getMapToTypedMembers() {
synchronized (mapToTypedMembersLock) {
if (__mapToTypedMembers == null) {
//noinspection ConstantConditions
__mapToTypedMembers =
createDelegatingMembers(
(member) ->

View File

@@ -56,6 +56,7 @@ public abstract class VmCollection extends VmValue implements Iterable<Object> {
}
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public abstract boolean isLengthOne();
public final void checkLengthOne() {

View File

@@ -21,7 +21,6 @@ import com.oracle.truffle.api.TruffleLanguage;
import com.oracle.truffle.api.TruffleLanguage.ContextPolicy;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.source.Source;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.ast.builder.AstBuilder;
import org.pkl.core.ast.expression.unary.ImportNode;
import org.pkl.core.module.ModuleKey;
@@ -74,8 +73,7 @@ public final class VmLanguage extends TruffleLanguage<VmContext> {
}
@TruffleBoundary
public VmTyped loadModule(ModuleKey moduleKey, ImportNode importNode)
throws SecurityManagerException {
public VmTyped loadModule(ModuleKey moduleKey, ImportNode importNode) {
var context = VmContext.get(null);
return context

View File

@@ -98,7 +98,9 @@ public final class VmMap extends VmValue implements Iterable<Map.Entry<Object, O
@TruffleBoundary
public Map.Entry<Object, Object> next() {
var key = keyIterator.next();
return Map.entry(key, map.get(key));
var value = map.get(key);
assert value != null;
return Map.entry(key, value);
}
@Override
@@ -187,7 +189,9 @@ public final class VmMap extends VmValue implements Iterable<Map.Entry<Object, O
public VmList values() {
var builder = VmList.EMPTY.builder();
for (var key : keyOrder) {
builder.add(map.get(key));
var value = map.get(key);
assert value != null;
builder.add(value);
}
return builder.build();
}
@@ -196,7 +200,9 @@ public final class VmMap extends VmValue implements Iterable<Map.Entry<Object, O
public VmList entries() {
var builder = VmList.EMPTY.builder();
for (var key : keyOrder) {
builder.add(new VmPair(key, map.get(key)));
var value = map.get(key);
assert value != null;
builder.add(new VmPair(key, value));
}
return builder.build();
}
@@ -225,6 +231,7 @@ public final class VmMap extends VmValue implements Iterable<Map.Entry<Object, O
var result = CollectionUtils.newLinkedHashMap(keyOrder.size());
for (var key : keyOrder) {
var value = map.get(key);
assert value != null;
result.put(VmValue.export(key), VmValue.export(value));
}
return result;

View File

@@ -72,7 +72,7 @@ public abstract class AbstractRenderer implements VmValueVisitor {
@LateInit private Object topLevelValue;
/** The current indent. Modified by {@link #increaseIndent()} and {@link #decreaseIndent()}. */
protected StringBuilder currIndent = new StringBuilder();
protected final StringBuilder currIndent = new StringBuilder();
/** The (closest) {@link SourceSection} of the value being visited, for better error messages. */
protected @Nullable SourceSection currSourceSection = null;

View File

@@ -21,8 +21,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Associates a stdlib node class with an Pkl member name or a stdlib package with a Pkl module
* name. Only required if the Java class/package can't have the same name as its corresponding Pkl
* Associates a stdlib node class with a Pkl member name or a stdlib package with a Pkl module name.
* Only required if the Java class/package can't have the same name as its corresponding Pkl
* member/module.
*/
@Target({ElementType.PACKAGE, ElementType.TYPE})

View File

@@ -89,7 +89,6 @@ public final class VmObjectFactory<E> {
var section = VmUtils.unavailableSourceSection();
var identifier = Identifier.get(name);
var member = new ObjectMember(section, section, VmModifier.NONE, identifier, name);
//noinspection ConstantConditions
var node =
isPropertyTypeChecked
? TypeCheckedPropertyNodeGen.create(null, new FrameDescriptor(), member, bodyNode)

View File

@@ -293,6 +293,7 @@ public final class RendererNodes {
} else if (deferredKey instanceof String string) {
writeXmlElement(string, null, value, true, true);
} else {
assert deferredKey != null;
cannotRenderNonStringKey(deferredKey);
}
}
@@ -458,7 +459,7 @@ public final class RendererNodes {
}
private void startNewLine() {
if (builder.length() == 0) return;
if (builder.isEmpty()) return;
lineNumber += 1;
builder.append(LINE_BREAK).append(currIndent);

View File

@@ -527,58 +527,25 @@ public final class IoUtils {
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean isDecimalDigit(char ch) {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
return switch (ch) {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> true;
default -> false;
};
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean isDecimalDigitOrUnderscore(char ch) {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '_':
return true;
default:
return false;
}
return switch (ch) {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_' -> true;
default -> false;
};
}
public static boolean isNonZeroDecimalDigit(char ch) {
switch (ch) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
return switch (ch) {
case '1', '2', '3', '4', '5', '6', '7', '8', '9' -> true;
default -> false;
};
}
public static boolean isOctalDigit(char ch) {

View File

@@ -24,13 +24,14 @@ import javax.annotation.meta.TypeQualifierDefault;
/**
* Indicates that method return types and method parameters in the annotated package are {@link
* org.pkl.core.util.Nonnull} unless explicitly annotated with {@link org.pkl.core.util.Nullable}.
* Nonnull} unless explicitly annotated with {@link Nullable}.
*
* <p>This annotation is a generalization of {@link javax.annotation.ParametersAreNonnullByDefault}.
* All Pkl packages containing Java code should carry this annotation.
*
* <p>Ideally, this default would apply to every {@link ElementType#TYPE_USE}, but I haven't been
* able to make this work reasonably in IntelliJ (https://youtrack.jetbrains.com/issue/IDEA-278618).
* able to make this work reasonably in <a
* href="https://youtrack.jetbrains.com/issue/IDEA-278618">IntelliJ</a>.
*/
@Documented
@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_PARAMETER})

View File

@@ -25,11 +25,13 @@ public final class StringUtils {
// whose key property is that it maps 25 characters into the 32-slot table without collision.
// Basically this is an opportunistic fast implementation as opposed to "good code". For most
// other use-cases, the reduction in readability isn't worth it.
@SuppressWarnings("UnnecessaryUnicodeEscape")
private static final String TABLE =
"\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000"
+ "\u2029\u000B\u3000\u2008\u2003\u205F\u3000\u1680"
+ "\u0009\u0020\u2006\u2001\u202F\u00A0\u000C\u2009"
+ "\u3000\u2004\u3000\u3000\u2028\n\u2007\u3000";
private static final int MULTIPLIER = 1682554634;
private static final int SHIFT = Integer.numberOfLeadingZeros(TABLE.length() - 1);

View File

@@ -397,7 +397,7 @@ public final class JsonParser {
var start = captureStart;
var end = index - 1;
captureStart = -1;
if (captureBuffer.length() > 0) {
if (!captureBuffer.isEmpty()) {
captureBuffer.append(buffer, start, end - start);
var captured = captureBuffer.toString();
captureBuffer.setLength(0);

View File

@@ -201,7 +201,7 @@ public class JsonWriter implements Closeable, Flushable {
* @param indent a string containing only whitespace.
*/
public final void setIndent(String indent) {
if (indent.length() == 0) {
if (indent.isEmpty()) {
this.indent = null;
this.separator = ":";
} else {

View File

@@ -17,10 +17,8 @@ package org.pkl.core.util.xml;
import java.util.Arrays;
/**
* Originally taken from:
* https://github.com/apache/xerces2-j/blob/8ce366ce9a20e7ffcb1dd37d0c4b5663d65b1f7d/src/org/apache/xerces/util/XMLChar.java
*/
// Originally taken from:
// https://github.com/apache/xerces2-j/blob/8ce366ce9a20e7ffcb1dd37d0c4b5663d65b1f7d/src/org/apache/xerces/util/XMLChar.java
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
final class Xml10Validator extends XmlValidator {
private static final byte[] CHARS = new byte[1 << 16];

View File

@@ -17,10 +17,8 @@ package org.pkl.core.util.xml;
import java.util.Arrays;
/**
* Originally taken from:
* https://github.com/apache/xerces2-j/blob/8ce366ce9a20e7ffcb1dd37d0c4b5663d65b1f7d/src/org/apache/xerces/util/XML11Char.java
*/
// Originally taken from:
// https://github.com/apache/xerces2-j/blob/8ce366ce9a20e7ffcb1dd37d0c4b5663d65b1f7d/src/org/apache/xerces/util/XML11Char.java
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
final class Xml11Validator extends XmlValidator {
private static final byte[] CHARS = new byte[1 << 16];

View File

@@ -43,6 +43,7 @@ public final class YamlEscaper extends AbstractCharEscaper {
@Override
protected @Nullable String findReplacement(char ch) {
//noinspection UnnecessaryUnicodeEscape
return ch <= '\u0022'
? REPLACEMENTS[ch]
: ch == '\u2028' ? "\\L" : ch == '\u2029' ? "\\P" : null;

View File

@@ -31,12 +31,6 @@ A for-generator cannot generate object properties (only entries and elements).
forGeneratorCannotGenerateMethods=\
A for-generator cannot generate object methods (only entries and elements).
legacyForGeneratorCannotHaveTwoVars=\
A legacy for-generator cannot have two for-variables.\n\
\n\
The correct syntax for a for-generator with two for-variables is:\n\
for (key, value in iterable) { ... }
cannotIterateOverThisValue=\
Cannot iterate over value of type `{0}`.
@@ -92,13 +86,6 @@ Instead, instantiate a concrete subclass.
cannotInstantiateType=\
Cannot instantiate type `{0}`.
cannotAmendValueOfExternalClass=\
Cannot amend value of external class `{0}`.\n\
\n\
Values of external classes cannot be amended.\n\
Instead, create a new value using the class'' literal syntax or constructor method.\n\
For example, `123` creates a value of class `Int`, and `Pair(1, 2)` creates a value of class `Pair`.
cannotAmendPropertyDefinition=\
A property definition cannot be amended.\n\
\n\
@@ -135,6 +122,7 @@ Cannot amend fixed property `{0}`.
cannotAssignConstProperty=\
Cannot assign to const property `{0}`.
# suppress inspection "UnusedProperty"
cannotAmendConstProperty=\
Cannot amend const property `{0}`.
@@ -479,9 +467,6 @@ Undefined value.
undefinedPropertyValue=\
Tried to read property `{0}` but its value is undefined.
unreachableCode=\
This code should not have been reached.
cannotFindModule=\
Cannot find module `{0}`.
@@ -542,9 +527,6 @@ Cannot convert Float `{0}` to Int because it is too large.
cannotConvertNonFiniteFloat=\
Cannot convert non-finite Float `{0}` to Int.
cannotConvertMapWithNonStringKeyToTyped=\
Cannot convert map with non-string key to typed object.
intValueTooLarge=\
Int value `{0}` is too large (only Int32 supported here).
@@ -560,15 +542,9 @@ Cannot combine glob imports with triple-dot module URIs.
cannotGlobUri=\
Cannot expand glob pattern `{0}` because scheme `{1}` is not globbable.
expectedAClass=\
Expected a class, but got a value of type `{0}`.
expectedAnnotationClass=\
Expected an annotation class.
expectedAClassButGotNull=\
Expected a class, but got `null`.
expectedNonNullValue=\
Expected a non-null value, but got `null`.
@@ -665,10 +641,6 @@ For example: `package://example.com/my/project@1.0.0#/path/to/file.pkl`.
invalidResourceUri=\
Resource URI `{0}` has invalid syntax.
# used as {1} in invalidModuleUri and invalidResourceUri
invalidUriFormat=\
must match pattern `{0}`
invalidGlobPattern=\
Invalid glob pattern `{0}`.