PoweredByApartium / cocoa-beans

General purpose library for Java & Spigot
https://cocoa-beans.apartium.net/
MIT License
11 stars 1 forks source link

CompoundParser parser #122

Open liorsl opened 3 months ago

liorsl commented 3 months ago

Allow parsers to attempt to delegate parsing to another parser, for example:

@Override
public Optional<ParseResult<Location>> parse(CommandProcessingContext ctxt) {
       ParseDelegationResult<Player> playerParseResultInst = ctxt.delegate(playerParser);
       ParseDelegationResult<Player> playerParseResultStr = ctxt.delegate("<player>");
       ParseDelegationResult<Player> playerParseResultType = ctxt.delegate(Player.class);

}

record ParseDelegationResult<T>(Optional<ParseResult<T>> result, ArgumentParser<T> parser) {}

Doing so will allow to reduce code duplication and making parsers more readable

ikfir commented 3 months ago
public class LocationParser extends CompoundParser<Location> {

  public LocationParser(int priority) {
    super("location", Location.class, priority);
  }

  @ParserVariant("<world> <double> <double> <double>")
  public Location serialize(World world, double x, double y, double z) {
    return new Location(world, x, y, z);
  }

  @ParserVariant("<world> <double> <double> <double> <float> <float>")
  public Location serialize(World world, double x, double y, double z, float yaw, float pitch) {
    return new Location(world, x, y, z, yaw, pitch);
  }

  @SourceParser(keyword = "world", clazz = World.class)
  public Map<String, World> getWorlds() {
    return Bukkit.getWorlds().stream()
          .collect(Collectors.toMap(
              world -> world.getName(),
              world -> world
           ));
  }

}
ikfir commented 1 week ago

Should be happen when we have the new argument mapper #190

So we can pass those values