Allow default suggestion providers in @Parser

This commit is contained in:
Alexander Söderberg 2020-12-18 12:54:11 +01:00 committed by Alexander Söderberg
parent e5a35afb8a
commit 6cc3a21619
4 changed files with 55 additions and 7 deletions

View file

@ -31,7 +31,9 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Queue;
import java.util.function.BiFunction;
/**
* Represents a method annotated with {@link Parser}
@ -42,19 +44,23 @@ import java.util.Queue;
*/
public class MethodArgumentParser<C, T> implements ArgumentParser<C, T> {
private final BiFunction<CommandContext<C>, String, List<String>> suggestionProvider;
private final MethodHandle methodHandle;
/**
* Create a new parser
*
* @param instance Instance that owns the method
* @param method The annotated method
* @param suggestionProvider Suggestion provider
* @param instance Instance that owns the method
* @param method The annotated method
* @throws Exception If the method lookup fails
*/
public MethodArgumentParser(
final @NonNull BiFunction<CommandContext<C>, String, List<String>> suggestionProvider,
final @NonNull Object instance,
final @NonNull Method method
) throws Exception {
this.suggestionProvider = suggestionProvider;
this.methodHandle = MethodHandles.lookup().unreflect(method).bindTo(instance);
}
@ -73,4 +79,12 @@ public class MethodArgumentParser<C, T> implements ArgumentParser<C, T> {
}
}
@Override
public @NonNull List<@NonNull String> suggestions(
final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return this.suggestionProvider.apply(commandContext, input);
}
}

View file

@ -27,6 +27,7 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.BiFunction;
/**
* This annotation allows you to create annotated methods that behave like argument parsers.
@ -52,4 +53,18 @@ public @interface Parser {
*/
String name() default "";
/**
* Name of the suggestions provider to use. If the string is left empty, the default
* provider for the {@link cloud.commandframework.annotations.Argument} will be used. Otherwise,
* the {@link cloud.commandframework.arguments.parser.ParserRegistry} instance in the
* {@link cloud.commandframework.CommandManager} will be queried for a matching suggestion provider.
* <p>
* For this to work, the suggestion needs to be registered in the parser registry. To do this, use
* {@link cloud.commandframework.arguments.parser.ParserRegistry#registerSuggestionProvider(String, BiFunction)}.
* The registry instance can be retrieved using {@link cloud.commandframework.CommandManager#getParserRegistry()}.
*
* @return The name of the suggestion provider, or {@code ""}
*/
String suggestions() default "";
}