The fact that this still works is a miracle

This commit is contained in:
Draycia committed 2021-12-06 22:18:05 -08:00
1 parent 86daf99602
commit da9808de7b
8 files changed
+287 -43

No files matched your search

@@ -44,7 +44,7 @@ public record SourcedAudience(Audience sender, Audience recipient) implements Fo
@Override @Override
public @NotNull Audience audience() { public @NotNull Audience audience() {
return Audience.audience(this.sender, this.recipient); return this.recipient;
} }
} }
@@ -35,6 +35,7 @@ import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.CarbonMessageService; import net.draycia.carbon.common.messages.CarbonMessageService;
import net.draycia.carbon.common.messages.CarbonMessageSource; import net.draycia.carbon.common.messages.CarbonMessageSource;
import net.draycia.carbon.common.messages.ReceiverResolver; import net.draycia.carbon.common.messages.ReceiverResolver;
import net.draycia.carbon.common.messages.StandardPlaceholderResolverStrategyButDifferent;
import net.draycia.carbon.common.messages.placeholders.ComponentPlaceholderResolver; import net.draycia.carbon.common.messages.placeholders.ComponentPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.KeyPlaceholderResolver; import net.draycia.carbon.common.messages.placeholders.KeyPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.StringPlaceholderResolver; import net.draycia.carbon.common.messages.placeholders.StringPlaceholderResolver;
@@ -46,8 +47,6 @@ import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.Moonshine; import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.exception.scan.UnscannableMethodException; import net.kyori.moonshine.exception.scan.UnscannableMethodException;
import net.kyori.moonshine.strategy.StandardPlaceholderResolverStrategy;
import net.kyori.moonshine.strategy.supertype.StandardSupertypeThenInterfaceSupertypeStrategy;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -84,7 +83,7 @@ public final class CarbonCommonModule extends AbstractModule {
.sourced(carbonMessageSource) .sourced(carbonMessageSource)
.rendered(carbonMessageRenderer) .rendered(carbonMessageRenderer)
.sent(carbonMessageSender) .sent(carbonMessageSender)
.resolvingWithStrategy(new StandardPlaceholderResolverStrategy<>(new StandardSupertypeThenInterfaceSupertypeStrategy(false))) .resolvingWithStrategy(new StandardPlaceholderResolverStrategyButDifferent<>())
.weightedPlaceholderResolver(Component.class, componentPlaceholderResolver, 0) .weightedPlaceholderResolver(Component.class, componentPlaceholderResolver, 0)
.weightedPlaceholderResolver(UUID.class, uuidPlaceholderResolver, 0) .weightedPlaceholderResolver(UUID.class, uuidPlaceholderResolver, 0)
.weightedPlaceholderResolver(String.class, stringPlaceholderResolver, 0) .weightedPlaceholderResolver(String.class, stringPlaceholderResolver, 0)
@@ -71,7 +71,7 @@ public class MuteInfoCommand {
if (!target.muted()) { if (!target.muted()) {
if (sender.equals(target)) { if (sender.equals(target)) {
messageService.muteInfoSelfMuted(sender); messageService.muteInfoSelfNotMuted(sender);
} else { } else {
messageService.muteInfoNotMuted(sender, CarbonPlayer.renderName(target)); messageService.muteInfoNotMuted(sender, CarbonPlayer.renderName(target));
} }
@@ -79,7 +79,7 @@ public class MuteInfoCommand {
return; return;
} else { } else {
if (sender.equals(target)) { if (sender.equals(target)) {
messageService.muteInfoSelfNotMuted(sender); messageService.muteInfoSelfMuted(sender);
} else { } else {
messageService.muteInfoMuted(sender, CarbonPlayer.renderName(target), target.muted()); messageService.muteInfoMuted(sender, CarbonPlayer.renderName(target), target.muted());
} }
@@ -41,14 +41,14 @@ public interface CarbonMessageService {
@ChatType(MessageType.CHAT) @ChatType(MessageType.CHAT)
RenderedMessage basicChatFormat( RenderedMessage basicChatFormat(
final Audience audience, final Audience audience,
final @Placeholder UUID uuid, final UUID uuid,
final @Placeholder("display_name") Component displayName, @Placeholder("display_name") final Component displayName,
final @Placeholder String username, final String username,
final @Placeholder Component message final Component message
); );
@Message("channel.change") @Message("channel.change")
void changedChannels(final Audience audience, final @Placeholder String channel); void changedChannels(final Audience audience, final String channel);
/* /*
* ============================================================= * =============================================================
@@ -63,16 +63,16 @@ public interface CarbonMessageService {
void muteInfoSelfNotMuted(final Audience audience); void muteInfoSelfNotMuted(final Audience audience);
@Message("mute.info.not_muted") @Message("mute.info.not_muted")
void muteInfoNotMuted(final Audience audience, final @Placeholder Component target); void muteInfoNotMuted(final Audience audience, final Component target);
@Message("mute.info.muted") @Message("mute.info.muted")
void muteInfoMuted(final Audience audience, final @Placeholder Component target, final @Placeholder boolean muted); void muteInfoMuted(final Audience audience, final Component target, final boolean muted);
@Message("mute.unmute.alert.target") @Message("mute.unmute.alert.target")
void unmuteAlertRecipient(final Audience audience); void unmuteAlertRecipient(final Audience audience);
@Message("mute.unmute.alert.players") @Message("mute.unmute.alert.players")
void unmuteAlertPlayers(final Audience audience, final @Placeholder Component target); void unmuteAlertPlayers(final Audience audience, final Component target);
@Message("mute.exempt") @Message("mute.exempt")
void muteExempt(final Audience audience); void muteExempt(final Audience audience);
@@ -81,7 +81,7 @@ public interface CarbonMessageService {
void muteAlertRecipient(final Audience audience); void muteAlertRecipient(final Audience audience);
@Message("mute.alert.players") @Message("mute.alert.players")
void muteAlertPlayers(final Audience audience, final @Placeholder Component target); void muteAlertPlayers(final Audience audience, final Component target);
@Message("mute.cannot_speak") @Message("mute.cannot_speak")
void muteCannotSpeak(final Audience audience); void muteCannotSpeak(final Audience audience);
@@ -99,37 +99,37 @@ public interface CarbonMessageService {
@ChatType(MessageType.CHAT) @ChatType(MessageType.CHAT)
void whisperSender( void whisperSender(
final SourcedAudience audience, final SourcedAudience audience,
final @Placeholder("sender_display_name") Component senderDisplayName, @Placeholder("sender_display_name") final Component senderDisplayName,
final @Placeholder("recipient_display_name") Component recipientDisplayName, @Placeholder("recipient_display_name") final Component recipientDisplayName,
final @Placeholder String message final String message
); );
@Message("whisper.from") @Message("whisper.from")
@ChatType(MessageType.CHAT) @ChatType(MessageType.CHAT)
void whisperRecipient( void whisperRecipient(
final SourcedAudience audience, final SourcedAudience audience,
final @Placeholder("sender_display_name") Component senderDisplayName, @Placeholder("sender_display_name") final Component senderDisplayName,
final @Placeholder("recipient_display_name") Component recipientDisplayName, @Placeholder("recipient_display_name") final Component recipientDisplayName,
final @Placeholder String message final String message
); );
@Message("reply.target.missing") @Message("reply.target.missing")
void replyTargetNotSet(final Audience audience, final @Placeholder("sender_display_name") Component senderDisplayName); void replyTargetNotSet(final Audience audience, @Placeholder("sender_display_name") final Component senderDisplayName);
@Message("reply.target.self") @Message("reply.target.self")
void whisperSelfError(final Audience audience, final @Placeholder("sender_display_name") Component senderDisplayName); void whisperSelfError(final Audience audience, @Placeholder("sender_display_name") final Component senderDisplayName);
@Message("whisper.continue.target_missing") @Message("whisper.continue.target_missing")
void whisperTargetNotSet( void whisperTargetNotSet(
final Audience audience, final Audience audience,
final @Placeholder("sender_display_name") Component senderDisplayName @Placeholder("sender_display_name") final Component senderDisplayName
); );
@Message("whisper.ignoring_target") @Message("whisper.ignoring_target")
void whisperIgnoringTarget(final Audience audience, final @Placeholder Component target); void whisperIgnoringTarget(final Audience audience, final Component target);
@Message("whisper.ignored_by_target") @Message("whisper.ignored_by_target")
void whisperTargetIgnoring(final Audience audience, final @Placeholder Component target); void whisperTargetIgnoring(final Audience audience, final Component target);
/* /*
* ============================================================= * =============================================================
@@ -138,28 +138,28 @@ public interface CarbonMessageService {
*/ */
@Message("nickname.set") @Message("nickname.set")
void nicknameSet(final Audience audience, final @Placeholder Component nickname); void nicknameSet(final Audience audience, final Component nickname);
@Message("nickname.set.others") @Message("nickname.set.others")
void nicknameSetOthers(final Audience audience, final @Placeholder String target, final @Placeholder Component nickname); void nicknameSetOthers(final Audience audience, final String target, final Component nickname);
@Message("nickname.show.others") @Message("nickname.show.others")
void nicknameShowOthers(final Audience audience, final @Placeholder String target, final @Placeholder Component nickname); void nicknameShowOthers(final Audience audience, final String target, final Component nickname);
@Message("nickname.show.others.unset") @Message("nickname.show.others.unset")
void nicknameShowOthersUnset(final Audience audience, final @Placeholder String target); void nicknameShowOthersUnset(final Audience audience, final String target);
@Message("nickname.show") @Message("nickname.show")
void nicknameShow(final Audience audience, final @Placeholder String target, final @Placeholder Component nickname); void nicknameShow(final Audience audience, final String target, final Component nickname);
@Message("nickname.show.unset") @Message("nickname.show.unset")
void nicknameShowUnset(final Audience audience, final @Placeholder String target); void nicknameShowUnset(final Audience audience, final String target);
@Message("nickname.reset") @Message("nickname.reset")
void nicknameReset(final Audience audience); void nicknameReset(final Audience audience);
@Message("nickname.reset.others") @Message("nickname.reset.others")
void nicknameResetOthers(final Audience audience, final @Placeholder String target); void nicknameResetOthers(final Audience audience, final String target);
@Message("nickname.set.self.error") @Message("nickname.set.self.error")
void nicknameCannotSetOwn(final Audience audience); void nicknameCannotSetOwn(final Audience audience);
@@ -174,13 +174,13 @@ public interface CarbonMessageService {
*/ */
@Message("ignore.exempt") @Message("ignore.exempt")
void ignoreExempt(final Audience audience, final @Placeholder Component target); void ignoreExempt(final Audience audience, final Component target);
@Message("ignore.now_ignoring") @Message("ignore.now_ignoring")
void nowIgnoring(final Audience audience, final @Placeholder Component target); void nowIgnoring(final Audience audience, final Component target);
@Message("ignore.no_longer_ignoring") @Message("ignore.no_longer_ignoring")
void noLongerIgnoring(final Audience audience, final @Placeholder Component target); void noLongerIgnoring(final Audience audience, final Component target);
@Message("ignore.invalid_target") @Message("ignore.invalid_target")
void ignoreTargetInvalid(final Audience audience); void ignoreTargetInvalid(final Audience audience);
@@ -209,17 +209,17 @@ public interface CarbonMessageService {
@Message("error.command.command_execution") @Message("error.command.command_execution")
void errorCommandCommandExecution( void errorCommandCommandExecution(
final Audience audience, final Audience audience,
final @Placeholder("throwable_message") Component throwableMessage, @Placeholder("throwable_message") final Component throwableMessage,
final @Placeholder String stacktrace final String stacktrace
); );
@Message("error.command.argument_parsing") @Message("error.command.argument_parsing")
void errorCommandArgumentParsing(final Audience audience, final @Placeholder("throwable_message") Component throwableMessage); void errorCommandArgumentParsing(final Audience audience, @Placeholder("throwable_message") final Component throwableMessage);
@Message("error.command.invalid_sender") @Message("error.command.invalid_sender")
void errorCommandInvalidSender(final Audience audience, final @Placeholder String sender_type); void errorCommandInvalidSender(final Audience audience, final String sender_type);
@Message("error.command.invalid_syntax") @Message("error.command.invalid_syntax")
void errorCommandInvalidSyntax(final Audience audience, final @Placeholder Component syntax); void errorCommandInvalidSyntax(final Audience audience, final Component syntax);
} }
@@ -0,0 +1,55 @@
/*
* moonshine - A localisation library for Java.
* Copyright (C) Mariell Hoversholm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.messages;
import java.util.Iterator;
public final class PrefixedDelegateIterator<T> implements Iterator<T> {
private final T prefix;
private final Iterator<T> delegate;
private boolean seenPrefix = false;
public PrefixedDelegateIterator(final T prefix, final Iterator<T> delegate) {
this.prefix = prefix;
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return !this.seenPrefix || this.delegate.hasNext();
}
@Override
public T next() {
if (!this.seenPrefix) {
this.seenPrefix = true;
return this.prefix;
}
return this.delegate.next();
}
@Override
public void remove() {
if (!this.seenPrefix) {
throw new IllegalStateException("must see prefix before removing from iterator");
}
this.delegate.remove();
}
}
@@ -62,13 +62,17 @@ public final class ReceiverResolver implements IReceiverLocatorResolver<Audience
private static final class Resolver implements IReceiverLocator<Audience> { private static final class Resolver implements IReceiverLocator<Audience> {
@Override @Override
public Audience locate(final Method method, final Object proxy, final @Nullable Object[] parameters) { public Audience locate(final Method method, final Object proxy, final @Nullable Object[] parameters) {
for (final Object parameter : parameters) { if (parameters.length == 0) {
return Audience.empty();
}
final @Nullable Object parameter = parameters[0];
if (parameter instanceof SourcedAudience sourcedAudience) { if (parameter instanceof SourcedAudience sourcedAudience) {
return sourcedAudience.recipient(); return sourcedAudience.recipient();
} else if (parameter instanceof Audience audience) { } else if (parameter instanceof Audience audience) {
return audience; return audience;
} }
}
return Audience.empty(); return Audience.empty();
} }
@@ -0,0 +1,34 @@
/*
* moonshine - A localisation library for Java.
* Copyright (C) Mariell Hoversholm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.messages;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker for a message recipient for detection with {@link ReceiverResolver}.
*/
@Documented
@Target({ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Recipient {
}
@@ -0,0 +1,152 @@
/*
* moonshine - A localisation library for Java.
* Copyright (C) Mariell Hoversholm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.messages;
import static java.util.Collections.emptyNavigableSet;
import io.leangen.geantyref.GenericTypeReflector;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.annotation.Placeholder;
import net.kyori.moonshine.annotation.meta.ThreadSafe;
import net.kyori.moonshine.exception.PlaceholderResolvingException;
import net.kyori.moonshine.exception.UnfinishedPlaceholderException;
import net.kyori.moonshine.model.MoonshineMethod;
import net.kyori.moonshine.placeholder.ContinuanceValue;
import net.kyori.moonshine.placeholder.IPlaceholderResolver;
import net.kyori.moonshine.strategy.IPlaceholderResolverStrategy;
import net.kyori.moonshine.strategy.supertype.ISupertypeStrategy;
import net.kyori.moonshine.strategy.supertype.StandardSupertypeThenInterfaceSupertypeStrategy;
import org.checkerframework.checker.nullness.qual.Nullable;
@ThreadSafe
public final class StandardPlaceholderResolverStrategyButDifferent<R, I, F> implements
IPlaceholderResolverStrategy<R, I, F> {
private final ISupertypeStrategy supertypeStrategy = new StandardSupertypeThenInterfaceSupertypeStrategy(false);
@Override
public Map<String, ? extends F> resolvePlaceholders(final Moonshine<R, I, ?, F> moonshine,
final R receiver, final I intermediateText,
final MoonshineMethod<? extends R> moonshineMethod,
final @Nullable Object[] parameters)
throws PlaceholderResolvingException {
if (parameters.length == 0) {
return Collections.emptyMap();
}
final Map<String, F> finalisedPlaceholders = new LinkedHashMap<>(parameters.length);
final Map<String, ContinuanceValue<?>> resolvingPlaceholders = new LinkedHashMap<>(16);
final Parameter[] methodParameters = moonshineMethod.reflectMethod().getParameters();
final Type[] exactParameterTypes = GenericTypeReflector.getParameterTypes(
moonshineMethod.reflectMethod(), moonshine.proxiedType());
// Don't resolve recipients
for (int idx = 1; idx < parameters.length; ++idx) {
final Parameter parameter = methodParameters[idx];
final @Nullable Object value = parameters[idx];
if (value == null) {
// Nothing to resolve with.
continue;
}
final Type parameterType = GenericTypeReflector.getExactSubType(
exactParameterTypes[idx], value.getClass());
final @Nullable Placeholder placeholder = parameter.getAnnotation(Placeholder.class);
final String placeholderName = (placeholder != null && !placeholder.value().isEmpty())
? placeholder.value()
: parameter.getName();
resolvingPlaceholders
.put(placeholderName, ContinuanceValue.continuanceValue(value, parameterType));
}
this.resolvePlaceholder(moonshine, receiver, finalisedPlaceholders,
resolvingPlaceholders, moonshineMethod, parameters);
return finalisedPlaceholders;
}
/**
* Resolve a single placeholder.
*
* @param moonshine the moonshine instance
* @param finalisedPlaceholders the finalised placeholders
* @param resolvingPlaceholders the placeholders to resolve
* @param moonshineMethod the method we are resolving a placeholder for
*/
private void resolvePlaceholder(final Moonshine<R, I, ?, F> moonshine, final R receiver,
final Map<String, F> finalisedPlaceholders,
final Map<String, ContinuanceValue<?>> resolvingPlaceholders,
final MoonshineMethod<? extends R> moonshineMethod, final @Nullable Object[] parameters)
throws UnfinishedPlaceholderException {
final var weightedPlaceholderResolvers = moonshine.weightedPlaceholderResolvers();
// Shamelessly stealing kashike's joke
dancing:
while (!resolvingPlaceholders.isEmpty()) {
final var resolvingPlaceholderIterator = resolvingPlaceholders.entrySet().iterator();
while (resolvingPlaceholderIterator.hasNext()) {
final var continuanceEntry = resolvingPlaceholderIterator.next();
final String continuancePlaceholderName = continuanceEntry.getKey();
final Type type = continuanceEntry.getValue().type();
final Object value = continuanceEntry.getValue().value();
final Iterator<Type> hierarchyIterator =
new PrefixedDelegateIterator<>(type, this.supertypeStrategy.hierarchyIterator(type));
while (hierarchyIterator.hasNext()) {
final Type supertype = hierarchyIterator.next();
for (final var weighted : weightedPlaceholderResolvers.getOrDefault(supertype, emptyNavigableSet())) {
@SuppressWarnings("unchecked") // This should be equivalent.
final var placeholderResolver =
(IPlaceholderResolver<R, Object, ? extends F>) weighted.value();
final var resolverResult =
placeholderResolver.resolve(continuancePlaceholderName, value, receiver,
moonshineMethod.owner().getType(),
moonshineMethod.reflectMethod(), parameters);
if (resolverResult == null) {
// The resolver did not want to resolve this; pass it on.
continue;
}
resolvingPlaceholderIterator.remove();
resolverResult.forEach((resolvedName, resolvedValue) ->
resolvedValue.map(conclusionValue -> finalisedPlaceholders
.put(resolvedName, conclusionValue.value()),
continuanceValue -> resolvingPlaceholders.put(resolvedName, continuanceValue)));
continue dancing;
}
}
throw new UnfinishedPlaceholderException(moonshineMethod, continuancePlaceholderName, value);
}
}
}
}