Skip to content

Commit

Permalink
feat: Greatly simplified the plugin annotation processing API
Browse files Browse the repository at this point in the history
  • Loading branch information
phinner committed May 4, 2024
1 parent 42e0a43 commit 527260e
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 341 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,13 @@
import java.util.List;
import java.util.Optional;

final class ListPluginAnnotationScanner implements PluginAnnotationScanner<List<?>> {

private final List<PluginAnnotationScanner<?>> scanners;

ListPluginAnnotationScanner(final List<PluginAnnotationScanner<?>> scanners) {
this.scanners = scanners;
}
record CompositePluginAnnotationProcessor(List<PluginAnnotationProcessor<?>> processors)
implements PluginAnnotationProcessor<List<?>> {

@Override
public Optional<List<?>> scan(final Object instance) {
return Optional.of(this.scanners.stream()
.map(scanner -> scanner.scan(instance))
public Optional<List<?>> process(final Object instance) {
return Optional.of(this.processors.stream()
.map(processor -> processor.process(instance))
.filter(Optional::isPresent)
.map(Optional::get)
.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation.method;
package com.xpdustry.distributor.api.annotation;

import com.xpdustry.distributor.api.event.EventBus;
import com.xpdustry.distributor.api.util.Priority;
Expand All @@ -26,7 +26,7 @@
import java.lang.annotation.Target;

/**
* Marks a method as an event handler, meaning it will be called by a {@link EventBus} when its corresponding event is
* Marks a method as an event handler, meaning it will be called by the {@link EventBus} when its corresponding event is
* posted.
* <br>
* The annotated method must have exactly one parameter, which is the event class.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,42 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation.method;
package com.xpdustry.distributor.api.annotation;

import com.xpdustry.distributor.api.DistributorProvider;
import com.xpdustry.distributor.api.event.EventSubscription;
import com.xpdustry.distributor.api.plugin.MindustryPlugin;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.List;
import java.util.function.Consumer;

final class EventHandlerProcessor implements MethodAnnotationScanner.Processor<EventHandler, EventSubscription> {
final class EventHandlerProcessor
extends MethodAnnotationProcessor<EventHandler, EventSubscription, EventSubscription> {

private final MindustryPlugin plugin;

EventHandlerProcessor(final MindustryPlugin plugin) {
super(EventHandler.class);
this.plugin = plugin;
}

@Override
public Optional<EventSubscription> process(final MethodAnnotationScanner.Context<EventHandler> context) {
if (context.getMethod().getParameterCount() != 1) {
throw new IllegalArgumentException(
"The event handler on " + context.getMethod() + " hasn't the right parameter count.");
} else if (!context.getMethod().canAccess(context.getInstance())) {
context.getMethod().setAccessible(true);
protected EventSubscription scan(final Object instance, final Method method, final EventHandler annotation) {
if (method.getParameterCount() != 1) {
throw new IllegalArgumentException("The event handler on " + method + " hasn't the right parameter count.");
}
if (!method.canAccess(instance)) {
method.setAccessible(true);
}
final var handler = new MethodEventHandler<>(context.getInstance(), context.getMethod());
return Optional.of(DistributorProvider.get()
final var handler = new MethodEventHandler<>(instance, method);
return DistributorProvider.get()
.getEventBus()
.subscribe(handler.getEventType(), context.getAnnotation().priority(), context.getPlugin(), handler));
.subscribe(handler.getEventType(), annotation.priority(), this.plugin, handler);
}

@Override
protected EventSubscription reduce(final List<EventSubscription> results) {
return () -> results.forEach(EventSubscription::unsubscribe);
}

private record MethodEventHandler<E>(Object target, Method method) implements Consumer<E> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Distributor, a feature-rich framework for Mindustry plugins.
*
* Copyright (C) 2024 Xpdustry
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

abstract class MethodAnnotationProcessor<A extends Annotation, R, O> implements PluginAnnotationProcessor<O> {

private final Class<A> annotationType;

protected MethodAnnotationProcessor(final Class<A> annotationType) {
this.annotationType = annotationType;
}

@SuppressWarnings({"unchecked"})
@Override
public final Optional<O> process(final Object instance) {
final List<R> results = new ArrayList<>();
for (final var method : instance.getClass().getDeclaredMethods()) {
for (final var annotation : method.getDeclaredAnnotations()) {
if (this.annotationType != annotation.annotationType()) continue;
results.add(this.scan(instance, method, (A) annotation));
}
}
return Optional.of(reduce(Collections.unmodifiableList(results)));
}

protected abstract R scan(final Object instance, final Method method, final A annotation);

protected abstract O reduce(final List<R> results);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Distributor, a feature-rich framework for Mindustry plugins.
*
* Copyright (C) 2024 Xpdustry
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation;

import com.xpdustry.distributor.api.event.EventSubscription;
import com.xpdustry.distributor.api.plugin.MindustryPlugin;
import com.xpdustry.distributor.api.scheduler.Cancellable;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
* A centralized mechanism for processing annotations of plugin objects.
*
* @param <R> the result type of the processor
*/
@FunctionalInterface
public interface PluginAnnotationProcessor<R> {

/**
* Processes the {@link EventHandler} method annotations of a given object to create event listeners.
* Returns a {@link EventSubscription} tied to all created event listeners for unsubscription.
*
* @param plugin the owning plugin
* @return the processor
*/
static PluginAnnotationProcessor<EventSubscription> events(final MindustryPlugin plugin) {
return new EventHandlerProcessor(plugin);
}

/**
* Processes the {@link TaskHandler} method annotations of a given object to create tasks.
* Returns a {@link Cancellable} tied to all created tasks for cancellation.
*
* @param plugin the owning plugin
* @return the processor
*/
static PluginAnnotationProcessor<Cancellable> tasks(final MindustryPlugin plugin) {
return new TaskHandlerProcessor(plugin);
}

/**
* Creates a processor with no result.
*
* @param consumer the consumer
* @return the scanner
*/
static PluginAnnotationProcessor<Void> consuming(final Consumer<Object> consumer) {
return instance -> {
consumer.accept(instance);
return Optional.empty();
};
}

/**
* Creates a processor that composes multiple processors.
* The result is a list of the results of the processors.
*
* @param scanners the processors
* @return the composed processor
*/
static PluginAnnotationProcessor<List<?>> compose(final PluginAnnotationProcessor<?>... scanners) {
return compose(Arrays.asList(scanners));
}

/**
* Creates a processor that composes multiple processors.
* The result is a list of the results of the processors.
*
* @param scanners the processors
* @return the composed processor
*/
static PluginAnnotationProcessor<List<?>> compose(final Collection<PluginAnnotationProcessor<?>> scanners) {
return new CompositePluginAnnotationProcessor(scanners.stream()
.flatMap(scanner -> scanner instanceof CompositePluginAnnotationProcessor composite
? composite.processors().stream()
: Stream.of(scanner))
.toList());
}

/**
* Processes the annotations of the given object.
*
* @param instance the object
* @return the result of the processing
*/
Optional<R> process(final Object instance);
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation.method;
package com.xpdustry.distributor.api.annotation;

import com.xpdustry.distributor.api.scheduler.Cancellable;
import com.xpdustry.distributor.api.scheduler.MindustryTimeUnit;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,44 +16,52 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.xpdustry.distributor.api.annotation.method;
package com.xpdustry.distributor.api.annotation;

import com.xpdustry.distributor.api.DistributorProvider;
import com.xpdustry.distributor.api.plugin.MindustryPlugin;
import com.xpdustry.distributor.api.scheduler.Cancellable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.List;
import java.util.function.Consumer;

final class TaskHandlerProcessor implements MethodAnnotationScanner.Processor<TaskHandler, Cancellable> {
final class TaskHandlerProcessor extends MethodAnnotationProcessor<TaskHandler, Cancellable, Cancellable> {

private final MindustryPlugin plugin;

TaskHandlerProcessor(final MindustryPlugin plugin) {
super(TaskHandler.class);
this.plugin = plugin;
}

@Override
public Optional<Cancellable> process(final MethodAnnotationScanner.Context<TaskHandler> context) {
if (context.getMethod().getParameterCount() > 1) {
throw new IllegalArgumentException(
"The event handler on " + context.getMethod() + " hasn't the right parameter count.");
} else if (!context.getMethod().canAccess(context.getInstance())) {
context.getMethod().setAccessible(true);
} else if (context.getMethod().getParameterCount() == 1
&& !Cancellable.class.equals(context.getMethod().getParameterTypes()[0])) {
throw new IllegalArgumentException(
"The event handler on " + context.getMethod() + " hasn't the right parameter type.");
protected Cancellable scan(final Object instance, final Method method, final TaskHandler annotation) {
if (method.getParameterCount() > 1) {
throw new IllegalArgumentException("The event handler on " + method + " hasn't the right parameter count.");
} else if (!method.canAccess(instance)) {
method.setAccessible(true);
} else if (method.getParameterCount() == 1 && !Cancellable.class.equals(method.getParameterTypes()[0])) {
throw new IllegalArgumentException("The event handler on " + method + " hasn't the right parameter type.");
}

final var builder = DistributorProvider.get()
.getPluginScheduler()
.schedule(context.getPlugin())
.async(context.getAnnotation().async());
if (context.getAnnotation().delay() > -1) {
builder.delay(
context.getAnnotation().delay(), context.getAnnotation().unit());
.schedule(this.plugin)
.async(annotation.async());
if (annotation.delay() > -1) {
builder.delay(annotation.delay(), annotation.unit());
}
if (context.getAnnotation().interval() > -1) {
builder.repeat(
context.getAnnotation().interval(), context.getAnnotation().unit());
if (annotation.interval() > -1) {
builder.repeat(annotation.interval(), annotation.unit());
}

return Optional.of(builder.execute(new MethodTaskHandler(context.getInstance(), context.getMethod())));
return builder.execute(new MethodTaskHandler(instance, method));
}

@Override
protected Cancellable reduce(final List<Cancellable> results) {
return () -> results.forEach(Cancellable::cancel);
}

private record MethodTaskHandler(Object object, Method method) implements Consumer<Cancellable> {
Expand Down
Loading

0 comments on commit 527260e

Please sign in to comment.