Skip to content

Commit

Permalink
Minor optimisations and cleanup, full code audit
Browse files Browse the repository at this point in the history
- Use `IdentityHashMap` for keys of type `Class`
- Use `addAll()` instead of a `for` loop `add()`
- Use `isEmpty()` instead of `length()`/`size()` comparisons
- Reduce eager configuration in build
- Other misc. changes
  • Loading branch information
PaintNinja committed May 9, 2024
1 parent 9b7e884 commit 2f10d83
Show file tree
Hide file tree
Showing 29 changed files with 59 additions and 59 deletions.
16 changes: 10 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ checkstyle {
}

// Source compiler configuration
tasks.withType(JavaCompile) {
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += ['-Xlint:all', '-Xlint:-path', '-proc:none']
options.deprecation = true
options.encoding = 'utf8'
Expand All @@ -342,13 +342,17 @@ def modularityInputs = objects.fileCollection()

project.sourceSets.each { set -> {
if (set.ext.has("languageVersion")) {
project.tasks[set.compileJavaTaskName].javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(set.ext.languageVersion)
project.tasks.named(set.compileJavaTaskName, JavaCompile) {
it.javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(set.ext.languageVersion)
}
}
}
if (set.ext.has("compatibility")) {
project.tasks[set.compileJavaTaskName].sourceCompatibility = set.ext.compatibility
project.tasks[set.compileJavaTaskName].targetCompatibility = set.ext.compatibility
project.tasks.named(set.compileJavaTaskName, JavaCompile) {
sourceCompatibility = set.ext.compatibility
targetCompatibility = set.ext.compatibility
}
}
def modularityExcluded = set.ext.has("modularityExcluded") && set.ext.modularityExcluded
if (!modularityExcluded) {
Expand All @@ -370,7 +374,7 @@ compileModularityJava {
}

if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
tasks.withType(Javadoc).configureEach {
// disable the crazy super-strict doclint tool in Java 8
options.addStringOption('Xdoclint:syntax', '-quiet')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
package org.spongepowered.tools.agent;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

import org.spongepowered.asm.logging.ILogger;
Expand All @@ -48,7 +49,7 @@ class MixinAgentClassLoader extends ClassLoader {
/**
* Mapping of mixin mixin classes to their fake classes
*/
private Map<Class<?>, byte[]> mixins = new HashMap<Class<?>, byte[]>();
private Map<Class<?>, byte[]> mixins = new IdentityHashMap<Class<?>, byte[]>();

/**
* Mapping that keep track of bytecode for classes that are targeted by
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public AnnotatedMixin(IMixinAnnotationProcessor ap, TypeElement type) {
this.annotation = this.handle.getAnnotation(Mixin.class);
this.classRef = TypeUtils.getInternalName(type);
this.primaryTarget = this.initTargets(ap);
this.remap = this.annotation.getBoolean("remap", true) && this.targets.size() > 0;
this.remap = this.annotation.getBoolean("remap", true) && !this.targets.isEmpty();

this.overwrites = new AnnotatedMixinElementHandlerOverwrite(ap, this);
this.shadows = new AnnotatedMixinElementHandlerShadow(ap, this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ public boolean isCaseSensitive() {
* Get whether this member has any aliases defined
*/
public boolean hasAliases() {
return this.aliases.size() > 0;
return !this.aliases.isEmpty();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public boolean isDefault() {
* Get whether this obfuscation type has data available
*/
public boolean isSupported() {
return this.getInputFileNames().size() > 0;
return !this.getInputFileNames().isEmpty();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
*/
public class MappingProviderTSrg extends MappingProvider {

private List<String> inputMappings = new ArrayList<String>();
private final List<String> inputMappings = new ArrayList<String>();

public MappingProviderTSrg(Messager messager, Filer filer) {
super(messager, filer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ protected static boolean compareElement(Element elem, String name, String type,
String elementType = TypeUtils.getJavaSignature(elem);
String rawElementType = TypeUtils.stripGenerics(elementType);
boolean compared = matchCase ? name.equals(elementName) : name.equalsIgnoreCase(elementName);
return compared && (type.length() == 0 || type.equals(elementType) || type.equals(rawElementType));
return compared && (type.isEmpty() || type.equals(elementType) || type.equals(rawElementType));
} catch (NullPointerException ex) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public void initProviders(IMixinAnnotationProcessor ap) {
serviceError.printStackTrace();
}

if (supportedTypes.size() > 0) {
if (!supportedTypes.isEmpty()) {
StringBuilder sb = new StringBuilder("Supported obfuscation types:");
for (Entry<String, Set<String>> supportedType : supportedTypes.entrySet()) {
sb.append(' ').append(supportedType.getKey()).append(" supports [").append(Joiner.on(',').join(supportedType.getValue())).append(']');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public String getClassRestrictions(String className) {
restrictions = "PACKAGE_CLASSLOADER_EXCLUSION";
}
if (this.isClassTransformerExcluded(className, null)) {
restrictions = (restrictions.length() > 0 ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION";
restrictions = (!restrictions.isEmpty() ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION";
}
return restrictions;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ public class MixinContainer {

static {
GlobalProperties.put(GlobalProperties.Keys.AGENTS, MixinContainer.agentClasses);
for (String agent : MixinService.getService().getPlatformAgents()) {
MixinContainer.agentClasses.add(agent);
}
MixinContainer.agentClasses.addAll(MixinService.getService().getPlatformAgents());
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public abstract class LoggerAdapterAbstract implements ILogger {
*/
public static class FormattedMessage {

private String message;
private final String message;

private Throwable t;

Expand All @@ -65,7 +65,7 @@ public FormattedMessage(String message, Object... params) {
if (delimPos < 0) {
break;
}
sb.append(message.substring(pos, delimPos)).append(params[param]);
sb.append(message, pos, delimPos).append(params[param]);
pos = delimPos + 2;
}
if (pos < message.length()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ protected DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner
public static DynamicSelectorDesc parse(String input, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context);
if (!descriptor.isResolved()) {
String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : "";
String extra = input.isEmpty() ? ". " + descriptor.getResolutionInfo() : "";
return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra));
}
return DynamicSelectorDesc.of(descriptor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ protected void parseSelectors() {
TargetSelector.parse(Annotations.<AnnotationNode>getValue(this.annotation, "target", false), this, selectors);

// Raise an error if we have no selectors
if (selectors.size() == 0) {
if (selectors.isEmpty()) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets",
this.annotationType, this.methodName));
}
Expand Down Expand Up @@ -406,7 +406,7 @@ protected void parseRequirements() {
* @return true if this InjectionInfo was successfully parsed
*/
public boolean isValid() {
return this.targets.size() > 0 && this.injectionPoints.size() > 0;
return !this.targets.isEmpty() && !this.injectionPoints.isEmpty();
}

/**
Expand Down Expand Up @@ -451,9 +451,7 @@ public void inject() {
* Perform cleanup and post-injection tasks
*/
public void postInject() {
for (MethodNode method : this.injectedMethods) {
this.classNode.methods.add(method);
}
this.classNode.methods.addAll(this.injectedMethods);

String description = this.getDescription();
String refMapStatus = this.mixin.getReferenceMapper().getStatus();
Expand Down Expand Up @@ -686,7 +684,7 @@ protected String getDynamicInfo() {
if (upstream != null) {
description = String.format("{%s} %s", upstream.getClassName(), description).trim();
}
return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : "";
return !description.isEmpty() ? String.format(" Method is @Dynamic(%s).", description) : "";
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ public InjectorGroupInfo add(InjectionInfo member) {
* @throws InjectionValidationException if validation fails
*/
public InjectorGroupInfo validate() throws InjectionValidationException {
if (this.members.size() == 0) {
if (this.members.isEmpty()) {
// I have no idea how we got here, but it's not an error :/
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -928,13 +928,13 @@ public static MemberInfo parse(final String input, final ISelectorContext contex
int bracePos = name.indexOf("{");
if (bracePos >= 0) {
try {
quantifier = Quantifier.parse(name.substring(bracePos, name.length()));
quantifier = Quantifier.parse(name.substring(bracePos));
name = name.substring(0, bracePos);
} catch (Exception ex) {
// Handled later in validate since matchCount will be 0
}
}
} else if (name.indexOf("{") >= 0) {
} else if (name.contains("{")) {
quantifier = Quantifier.NONE; // Probably incomplete quantifier
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ protected void applyInitialisers(MixinTargetContext mixin) {

// Find the initialiser instructions in the candidate ctor
Deque<AbstractInsnNode> initialiser = this.getInitialiser(mixin, ctor);
if (initialiser == null || initialiser.size() == 0) {
if (initialiser == null || initialiser.isEmpty()) {
return;
}

Expand Down Expand Up @@ -970,14 +970,14 @@ protected final void injectInitialiser(MixinTargetContext mixin, MethodNode ctor
}

for (AbstractInsnNode node : initialiser) {
if (node instanceof LabelNode) {
//if (node instanceof LabelNode) {
// Fabric: Merge cloned labels instead of skipping them.
// continue;
}
if (node instanceof JumpInsnNode) {
//}
//if (node instanceof JumpInsnNode) {
// Fabric: Jumps cause no issues if labels are cloned properly and should not be needlessly restricted.
// throw new InvalidMixinException(mixin, "Unsupported JUMP opcode in initialiser in " + mixin);
}
//}
AbstractInsnNode imACloneNow = node.clone(labels);
ctor.instructions.insert(insn, imACloneNow);
insn = imACloneNow;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -832,7 +832,7 @@ private void prepareMixins(String collectionName, List<String> mixinClasses, boo
}

if (Strings.isNullOrEmpty(this.mixinPackage)) {
if (mixinClasses.size() > 0) {
if (!mixinClasses.isEmpty()) {
this.logger.error("{} declares mixin classes in {} but does not specify a package, {} orphaned mixins will not be loaded: {}",
this, collectionName, mixinClasses.size(), mixinClasses);
}
Expand Down Expand Up @@ -867,7 +867,7 @@ private void prepareMixins(String collectionName, List<String> mixinClasses, boo
for (MixinInfo mixin : this.pendingMixins) {
try {
mixin.parseTargets();
if (mixin.getTargetClasses().size() > 0) {
if (!mixin.getTargetClasses().isEmpty()) {
for (String targetClass : mixin.getTargetClasses()) {
String targetClassName = targetClass.replace('/', '.');
this.mixinsFor(targetClassName).add(mixin);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1305,7 +1305,7 @@ private ClassNode loadMixinClass(String mixinClassName) throws ClassNotFoundExce
IClassTracker tracker = this.service.getClassTracker();
if (tracker != null) {
String restrictions = tracker.getClassRestrictions(mixinClassName);
if (restrictions.length() > 0) {
if (!restrictions.isEmpty()) {
this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ private static String getDynamicInfo(String targetType, AnnotationNode annotatio
if (upstream != null) {
description = String.format("{%s} %s", upstream.getClassName(), description).trim();
}
return description.length() > 0 ? String.format(" %s is @Dynamic(%s)", targetType, description) : "";
return !description.isEmpty() ? String.format(" %s is @Dynamic(%s)", targetType, description) : "";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,7 @@ private void updateBinding(MethodNode method, MemberRef methodRef, Traversal tra
* @param field Field node to transform
*/
void transformDescriptor(FieldNode field) {
if (!this.inheritsFromMixin && this.innerClasses.size() == 0) {
if (!this.inheritsFromMixin && this.innerClasses.isEmpty()) {
return;
}
field.desc = this.transformSingleDescriptor(field.desc, false);
Expand All @@ -911,7 +911,7 @@ void transformDescriptor(FieldNode field) {
* @param method Method node to transform
*/
void transformDescriptor(MethodNode method) {
if (!this.inheritsFromMixin && this.innerClasses.size() == 0) {
if (!this.inheritsFromMixin && this.innerClasses.isEmpty()) {
return;
}
method.desc = this.transformMethodDescriptor(method.desc);
Expand All @@ -924,7 +924,7 @@ void transformDescriptor(MethodNode method) {
* @param member Reference to the method or field
*/
void transformDescriptor(MemberRef member) {
if (!this.inheritsFromMixin && this.innerClasses.size() == 0) {
if (!this.inheritsFromMixin && this.innerClasses.isEmpty()) {
return;
}
if (member.isField()) {
Expand All @@ -940,7 +940,7 @@ void transformDescriptor(MemberRef member) {
* @param typeInsn Type instruction node to transform
*/
void transformDescriptor(TypeInsnNode typeInsn) {
if (!this.inheritsFromMixin && this.innerClasses.size() == 0) {
if (!this.inheritsFromMixin && this.innerClasses.isEmpty()) {
return;
}
typeInsn.desc = this.transformSingleDescriptor(typeInsn.desc, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

Expand All @@ -52,7 +52,7 @@ public final class Extensions implements IExtensionRegistry {
* generators using {@link #getExtension}
*/
private final Map<Class<? extends IExtension>, IExtension> extensionMap
= new HashMap<Class<? extends IExtension>, IExtension>();
= new IdentityHashMap<Class<? extends IExtension>, IExtension>();

/**
* Modules which generate synthetic classes required by mixins
Expand All @@ -69,7 +69,7 @@ public final class Extensions implements IExtensionRegistry {
* generators using {@link #getGenerator}
*/
private final Map<Class<? extends IClassGenerator>, IClassGenerator> generatorMap
= new HashMap<Class<? extends IClassGenerator>, IClassGenerator>();
= new IdentityHashMap<Class<? extends IClassGenerator>, IClassGenerator>();

private final ISyntheticClassRegistry syntheticClassRegistry;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -74,7 +75,7 @@ public abstract class MixinServiceAbstract implements IMixinService {
/**
* All internals offered to this service
*/
private final Map<Class<IMixinInternal>, IMixinInternal> internals = new HashMap<Class<IMixinInternal>, IMixinInternal>();
private final Map<Class<IMixinInternal>, IMixinInternal> internals = new IdentityHashMap<Class<IMixinInternal>, IMixinInternal>();

/**
* Service agent instances
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/spongepowered/asm/util/ClassSignature.java
Original file line number Diff line number Diff line change
Expand Up @@ -1264,13 +1264,13 @@ public SignatureVisitor getRemapper() {
*/
@Override
public String toString() {
while (this.rawInterfaces.size() > 0) {
while (!this.rawInterfaces.isEmpty()) {
this.addRawInterface(this.rawInterfaces.remove());
}

StringBuilder sb = new StringBuilder();

if (this.types.size() > 0) {
if (!this.types.isEmpty()) {
boolean valid = false;
StringBuilder types = new StringBuilder();
for (Entry<TypeVar, TokenHandle> type : this.types.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ private ConstraintParser() {
* @return parsed constraint
*/
public static Constraint parse(String expr) {
if (expr == null || expr.length() == 0) {
if (expr == null || expr.isEmpty()) {
return Constraint.NONE;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ private static int scanClassFeatures(ClassNode classNode) {

String nestHostClass = ClassNodeAdapter.getNestHostClass(classNode);
List<String> nestMembers = ClassNodeAdapter.getNestMembers(classNode);
if (nestHostClass != null || (nestMembers != null && nestMembers.size() > 0)) {
if (nestHostClass != null || (nestMembers != null && !nestMembers.isEmpty())) {
features |= LanguageFeatures.NESTING;
}

Expand Down
Loading

0 comments on commit 2f10d83

Please sign in to comment.