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 79531b3
Show file tree
Hide file tree
Showing 11 changed files with 217 additions and 339 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 CompositeAnnotationProcessor(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,45 @@
* 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.List;
import java.util.Optional;
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 process(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 Optional<EventSubscription> reduce(final List<EventSubscription> results) {
return results.isEmpty()
? Optional.empty()
: Optional.of(() -> 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.process(instance, method, (A) annotation));
}
}
return reduce(Collections.unmodifiableList(results));
}

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

protected abstract Optional<O> reduce(final List<R> results);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* 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.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.
* The result is an {@link EventSubscription} tied to all created event listeners. If none, an empty result is returned.
*
* @param plugin the owning plugin
* @return a new event handler 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.
* The result is a {@link Cancellable} tied to all created tasks. If none, an empty result is returned.
*
* @param plugin the owning plugin
* @return a new task handler processor
*/
static PluginAnnotationProcessor<Cancellable> tasks(final MindustryPlugin plugin) {
return new TaskHandlerProcessor(plugin);
}

/**
* Composes multiple processors into one that returns their result in a list.
* <br>
* Note that if a composed processor is in the list of processors, it will be flattened. Such as:
* <br>
* {@code compose(p1, p2, compose(p3, p4), p5)} will become {@code compose(p1, p2, p3, p4, p5)}
*
* @param processors the processors
* @return the composed processor
*/
static PluginAnnotationProcessor<List<?>> compose(final PluginAnnotationProcessor<?>... processors) {
return compose(Arrays.asList(processors));
}

/**
* Composes multiple processors into one that returns their result in a list.
* <br>
* Note that if a composed processor is in the list of processors, it will be flattened. Such as:
* <br>
* {@code compose(p1, p2, compose(p3, p4), p5)} will become {@code compose(p1, p2, p3, p4, p5)}
*
* @param processors the processors
* @return the composed processor
*/
static PluginAnnotationProcessor<List<?>> compose(final Collection<PluginAnnotationProcessor<?>> processors) {
return new CompositeAnnotationProcessor(processors.stream()
.flatMap(processor -> processor instanceof CompositeAnnotationProcessor composite
? composite.processors().stream()
: Stream.of(processor))
.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,53 @@
* 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.List;
import java.util.Optional;
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 process(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 Optional<Cancellable> reduce(final List<Cancellable> results) {
return results.isEmpty() ? Optional.empty() : Optional.of(() -> results.forEach(Cancellable::cancel));
}

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

0 comments on commit 79531b3

Please sign in to comment.