Skip to content

Pass context to ArgumentType.parse #76

@Martmists-GH

Description

@Martmists-GH

For a few of my projects I'm considering using Brigadier, however one limitation has been stopping me from using this: ArgumentType.parse is not context-aware.

In many cases, the object to be returned requires context of where or by who the command was invoked. The simple solution would be to pass the source object to the parse method as second parameter, however this would cause breaking changes in the library.

To solve this, I propose to give the parse method two signatures: parse(StringReader reader) and parse(StringReader reader, Object context), both with a default implementation which returns null.
Sadly due to how the current arguments are implemented they do not supply the type of the context, but on a per-application basis this could be done with a manual cast in the parse() method. To handle both functions, the following could be done:

    // ArgumentCommandNode.java
    @Override
    public void parse(final StringReader reader, final CommandContextBuilder<S> contextBuilder) throws CommandSyntaxException {
        final int start = reader.getCursor();
        final T result = type.parse(reader);
        if (result == null) {
            // The context-unaware method was not implemented, call the context-aware method
            result = type.parse(reader, contextBuilder.getSource())
        }
        if (result == null) {
            // Throw an error to avoid magic NullPointerExceptions in the user's code
            throw CommandSyntaxException("No implementation for parse on argument type!")  // Simple error as example, should be improved
        }
        final ParsedArgument<S, T> parsed = new ParsedArgument<>(start, reader.getCursor(), result);

        contextBuilder.withArgument(name, parsed);
        contextBuilder.withNode(this, parsed.getRange());
    }

This way users can implement context-aware parse methods without breaking any existing code, unless someone implements an ArgumentType that returns a nullable value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions