Compare commits

..

4 commits

Author SHA1 Message Date
Nathan Adams
ff0da75678 Added javadoc to CommandDispatcher 2018-09-25 17:38:04 +02:00
Nathan Adams
e54a50f566 Added readme 2018-09-25 10:00:41 +02:00
Nathan Adams
7bc3563927 Add MIT license 2018-09-24 15:07:24 +02:00
Nathan Adams
7d201afc7f Add copyright to all code 2018-09-24 15:03:38 +02:00
46 changed files with 219 additions and 985 deletions

View file

@ -1,51 +0,0 @@
name: $(Rev:r)
trigger:
branches:
include:
- '*'
exclude:
- master
pr:
branches:
include:
- '*'
jobs:
- job: 'Build'
displayName: 'Build for testing'
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
container: adoptopenjdk/openjdk8:latest
workspace:
clean: all
steps:
- task: Gradle@2
displayName: Build and Test
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
options: '-PbuildNumber=0'
javaHomeOption: 'JDKVersion'
jdkUserInputPath: '/usr/java/openjdk-8'
testResultsFiles: '**/TEST-*.xml'
tasks: 'build test publish'
# This is a workaround for ComponentGovernanceComponentDetection@0 not recognizing the generated `.pom` file(s)
- task: Bash@3
displayName: Copy pom for component governance
inputs:
targetType: 'inline'
script: |
pompath=`find build/repo -name *.pom`
cp "${pompath}" build/pom.xml
- task: ComponentGovernanceComponentDetection@0
inputs:
scanType: 'Register'
verbosity: 'Verbose'
alertWarningLevel: 'High'

View file

@ -1,87 +0,0 @@
name: $(Rev:r)
trigger:
branches:
include:
- master
pr: none
variables:
rConnection: 'mc-java-sc'
storageAccount: 'librariesminecraftnet'
storageAccountContainer: 'librariesminecraftnet'
keyVault: 'mc-java-vault'
jobs:
- job: 'Build'
displayName: 'Build for release'
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
container: adoptopenjdk/openjdk8:latest
workspace:
clean: all
steps:
- task: Gradle@2
displayName: Build and Test
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
options: '-PbuildNumber=$(Build.BuildNumber)'
javaHomeOption: 'JDKVersion'
jdkUserInputPath: '/usr/java/openjdk-8'
testResultsFiles: '**/TEST-*.xml'
tasks: 'build test publish report'
# This is a workaround for ComponentGovernanceComponentDetection@0 not recognizing the generated `.pom` file(s)
- task: Bash@3
displayName: Copy pom for component governance
inputs:
targetType: 'inline'
script: |
pompath=`find build/repo -name *.pom`
cp "${pompath}" build/pom.xml
- task: ComponentGovernanceComponentDetection@0
inputs:
scanType: 'Register'
verbosity: 'Verbose'
alertWarningLevel: 'High'
- publish: 'build/repo/'
artifact: repo
- job: 'Publish'
displayName: 'Publish release'
dependsOn: Build
condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')
pool: 'MC-Build-1ES-Azure-Pipeline-Linux'
workspace:
clean: all
steps:
- download: current
artifact: repo
- task: AzureKeyVault@1
displayName: 'Fetching secrets'
name: secrets
inputs:
azureSubscription: '$(rConnection)'
KeyVaultName: '$(keyVault)'
SecretsFilter: 'access-key-prod-librariesminecraftnet'
RunAsPreJob: false
- task: AzureCLI@2
displayName: Azure CLI
inputs:
azureSubscription: '$(rConnection)'
scriptType: 'bash'
scriptLocation: 'inlineScript'
inlineScript: |
az storage blob upload-batch -s '$(Pipeline.Workspace)/repo' -d $(storageAccountContainer) --account-name $(storageAccount) --account-key $(access-key-prod-librariesminecraftnet)

View file

@ -1,22 +0,0 @@
name: pr-check
on: [ pull_request ]
jobs:
build:
name: Build and test
runs-on: ubuntu-latest
container:
image: adoptopenjdk/openjdk8:latest
steps:
- uses: actions/checkout@v3
- name: Build with Gradle
uses: gradle/gradle-build-action@v2
with:
arguments: build test
- name: Publish Test Report
uses: mikepenz/action-junit-report@v3
if: always()
with:
report_paths: '**/build/test-results/test/TEST-*.xml'

18
LICENSE
View file

@ -2,20 +2,8 @@ MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,5 +1,4 @@
# Brigadier [![Latest release](https://img.shields.io/github/release/Mojang/brigadier.svg)](https://github.com/Mojang/brigadier/releases/latest) [![License](https://img.shields.io/github/license/Mojang/brigadier.svg)](https://github.com/Mojang/brigadier/blob/master/LICENSE)
# Brigadier
Brigadier is a command parser & dispatcher, designed and developed for Minecraft: Java Edition and now freely available for use elsewhere under the MIT license.
# Installation
@ -38,7 +37,7 @@ And then use this library (change `(the latest version)` to the latest version!)
```
# Contributing
Contributions are welcome! :D
Contributions are suspended until we have a process in place to handle them.
Most contributions will require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
@ -50,20 +49,20 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio
# Usage
At the heart of Brigadier, you need a `CommandDispatcher<S>`, where `<S>` is any custom object you choose to identify a "command source".
A command dispatcher holds a "command tree", which is a series of `CommandNode`s that represent the various possible syntax options that form a valid command.
A command dispatcher holds a "command tree", which are a series of `CommandNode` which represent the various possible syntax that form a valid command.
## Registering a new command
Before we can start parsing and dispatching commands, we need to build up our command tree. Every registration is an append operation,
so you can freely extend existing commands in a project without needing access to the source code that created them.
Command registration also encourages the use of a builder pattern to keep code cruft to a minimum.
Command registration also encourages use of a builder pattern to keep code cruft to a minimum.
A "command" is a fairly loose term, but typically it means an exit point of the command tree.
Every node can have an `executes` function attached to it, which signifies that if the input stops here then this function will be called with the context so far.
Consider the following example:
```java
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher();
dispatcher.register(
literal("foo")
@ -95,12 +94,12 @@ Argument types will be asked to parse input as much as they can, and then store
For example, an integer argument would parse "123" and store it as `123` (`int`), but throw an error if the input were `onetwothree`.
When a command is actually run, it can access these arguments in the context provided to the registered function.
When a command is actually ran, it can access these arguments in the context provided to the registered function.
## Parsing user input
So, we've registered some commands and now we're ready to take in user input. If you're in a rush, you can just call `dispatcher.execute("foo 123", source)` and call it a day.
The result of `execute` is an integer that was returned from an evaluated command. The meaning of this integer depends on the command, and will typically not be useful to programmers.
The result of `execute` is an integer returned by the command it evaluated. Its meaning varies depending on command, and typically will not be useful to programmers.
The `source` is an object of `<S>`, your own custom class to track users/players/etc. It will be provided to the command so that it has some context on what's happening.
@ -126,10 +125,9 @@ It also contains a map of parse exceptions for each command node it encountered.
the reason why is inside this exception map.
## Displaying usage info
There are two forms of "usage strings" provided by this library, both require a target node.
There's two forms of "usage strings" provided by this library, both require a target node.
`getAllUsage(node, source, restricted)` will return a list of all possible commands (executable end-points) under the target node and their human readable path. If `restricted`, it will ignore commands that `source` does not have access to. This will look like [`foo`, `foo <bar>`].
`getAllUsage(node, source, restricted)` will return a list of all possible commands (executable end-points) under the target node and their human readable path. If `restricted`, it will ignore commands that `source` does not have access to. This will look like [`foo`, `foo <bar>`]
`getSmartUsage(node, source)` will return a map of the child nodes to their "smart usage" human readable path. This tries to squash future-nodes together and show optional & typed information, and can look like `foo (<bar>)`.
`getSmartUsage(node, source)` will return a map of the child nodes to their "smart usage" human readable path. This tries to squash future-nodes together and show optional & typed information, and can look like `foo (<bar>)`
[![GitHub forks](https://img.shields.io/github/forks/Mojang/brigadier.svg?style=social&label=Fork)](https://github.com/Mojang/brigadier/fork) [![GitHub stars](https://img.shields.io/github/stars/Mojang/brigadier.svg?style=social&label=Stars)](https://github.com/Mojang/brigadier/stargazers)

View file

@ -1,4 +1,6 @@
import groovy.io.FileType
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider
import com.amazonaws.services.s3.AmazonS3Client
apply plugin: 'java-library'
apply plugin: 'maven-publish'
@ -6,6 +8,10 @@ apply plugin: 'maven-publish'
group = 'com.mojang'
version = project.hasProperty('buildNumber') ? "${project.majorMinor}.${project.buildNumber}" : "${project.majorMinor}.0-SNAPSHOT"
task wrapper(type: Wrapper) {
gradleVersion = '4.0'
}
buildscript {
repositories {
mavenCentral()
@ -13,6 +19,10 @@ buildscript {
url "https://libraries.minecraft.net"
}
}
dependencies {
classpath 'com.amazonaws:aws-java-sdk:1.11.33'
}
}
repositories {
@ -23,13 +33,13 @@ repositories {
}
dependencies {
testCompile 'com.google.guava:guava:26.0-jre'
testCompile 'junit:junit-dep:4.11'
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'com.google.guava:guava-testlib:26.0-jre'
testCompile 'org.openjdk.jmh:jmh-core:1.21'
annotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.21'
api 'com.google.guava:guava:21.0'
testCompile 'junit:junit-dep:4.10'
testCompile 'org.hamcrest:hamcrest-library:1.2.1'
testCompile 'org.mockito:mockito-core:1.8.5'
testCompile 'com.google.guava:guava-testlib:21.0'
testCompile 'org.openjdk.jmh:jmh-core:1.19'
testCompile 'org.openjdk.jmh:jmh-generator-annprocess:1.19'
}
task sourcesJar(type: Jar) {
@ -80,12 +90,18 @@ publishing {
task report {
doLast {
println "##vso[build.updatebuildnumber]${project.version}"
println "##teamcity[buildNumber '${project.version}']"
}
}
def publishDir = file("$buildDir/repo")
def uploadFile(s3, bucket, path, filename) {
println "Uploading $filename to $bucket as $path"
s3.putObject(bucket, path, filename)
}
clean.doLast {
delete publishDir
}
@ -102,13 +118,14 @@ if (version.endsWith("SNAPSHOT")) {
}
publish.doLast {
def AWSRoleARN = (System.getenv("AWS_ROLE_ARN") != null && System.getenv("AWS_ROLE_ARN") != "" ? System.getenv("AWS_ROLE_ARN") : null)
if (AWSRoleARN == null) throw new GradleException("AWS Role has not been configured, use the `AWS_ROLE_ARN` environment variable")
def auth = new STSAssumeRoleSessionCredentialsProvider.Builder(AWSRoleARN, "JavaBrigadierPublish").build()
def s3 = new AmazonS3Client(auth)
publishDir.eachFileRecurse {
if (!it.isFile()) {
return
}
// Remove junk files
if (it.name.contains(".xml") || it.name.contains(".md5")) {
it.delete()
if (!it.name.contains(".xml") && !it.name.contains(".md5") && it.isFile()) {
def relPath = publishDir.toPath().relativize(it.toPath()).toFile().toString().replaceAll('\\\\', '/')
uploadFile(s3, "minecraft-libraries", relPath, it)
}
}
}

View file

@ -1 +1 @@
majorMinor: 1.1
majorMinor: 1.0

Binary file not shown.

View file

@ -1,6 +1,6 @@
#Sat Oct 06 16:17:40 EEST 2018
#Wed Jun 21 14:07:34 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-bin.zip

0
gradlew vendored Executable file → Normal file
View file

View file

@ -1,2 +1 @@
rootProject.name = 'brigadier'
enableFeaturePreview('STABLE_PUBLISHING')
rootProject.name = 'brigadier'

View file

@ -3,10 +3,14 @@
package com.mojang.brigadier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.context.SuggestionContext;
import com.mojang.brigadier.context.StringRange;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
@ -18,9 +22,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -55,7 +57,6 @@ public class CommandDispatcher<S> {
private static final String USAGE_OR = "|";
private final RootCommandNode<S> root;
private final Predicate<CommandNode<S>> hasCommand = new Predicate<CommandNode<S>>() {
@Override
public boolean test(final CommandNode<S> input) {
@ -230,7 +231,8 @@ public class CommandDispatcher<S> {
final CommandContext<S> child = context.getChild();
if (child != null) {
forked |= context.isForked();
if (child.hasNodes()) {
if (!child.getNodes().isEmpty()) {
foundCommand = true;
final RedirectModifier<S> modifier = context.getRedirectModifier();
if (modifier == null) {
if (next == null) {
@ -247,8 +249,6 @@ public class CommandDispatcher<S> {
for (final S source : results) {
next.add(child.copyFor(source));
}
} else {
foundCommand = true;
}
} catch (final CommandSyntaxException ex) {
consumer.onCommandComplete(context, false, 0);
@ -345,14 +345,24 @@ public class CommandDispatcher<S> {
* @see #execute(String, Object)
*/
public ParseResults<S> parse(final StringReader command, final S source) {
final CommandContextBuilder<S> context = new CommandContextBuilder<>(this, source, root, command.getCursor());
final CommandContextBuilder<S> context = new CommandContextBuilder<>(this, source, 0);
return parseNodes(root, command, context);
}
private static class PartialParse<S> {
public final CommandContextBuilder<S> context;
public final ParseResults<S> parse;
private PartialParse(final CommandContextBuilder<S> context, final ParseResults<S> parse) {
this.context = context;
this.parse = parse;
}
}
private ParseResults<S> parseNodes(final CommandNode<S> node, final StringReader originalReader, final CommandContextBuilder<S> contextSoFar) {
final S source = contextSoFar.getSource();
Map<CommandNode<S>, CommandSyntaxException> errors = null;
List<ParseResults<S>> potentials = null;
List<PartialParse<S>> potentials = null;
final int cursor = originalReader.getCursor();
for (final CommandNode<S> child : node.getRelevantNodes(originalReader)) {
@ -385,47 +395,48 @@ public class CommandDispatcher<S> {
if (reader.canRead(child.getRedirect() == null ? 2 : 1)) {
reader.skip();
if (child.getRedirect() != null) {
final CommandContextBuilder<S> childContext = new CommandContextBuilder<>(this, source, child.getRedirect(), reader.getCursor());
final CommandContextBuilder<S> childContext = new CommandContextBuilder<>(this, source, reader.getCursor());
childContext.withNode(child.getRedirect(), StringRange.between(cursor, reader.getCursor() - 1));
final ParseResults<S> parse = parseNodes(child.getRedirect(), reader, childContext);
context.withChild(parse.getContext());
return new ParseResults<>(context, parse.getReader(), parse.getExceptions());
return new ParseResults<>(context, originalReader.getCursor(), parse.getReader(), parse.getExceptions());
} else {
final ParseResults<S> parse = parseNodes(child, reader, context);
if (potentials == null) {
potentials = new ArrayList<>(1);
}
potentials.add(parse);
potentials.add(new PartialParse<>(context, parse));
}
} else {
if (potentials == null) {
potentials = new ArrayList<>(1);
}
potentials.add(new ParseResults<>(context, reader, Collections.emptyMap()));
potentials.add(new PartialParse<>(context, new ParseResults<>(context, originalReader.getCursor(), reader, Collections.emptyMap())));
}
}
if (potentials != null) {
if (potentials.size() > 1) {
potentials.sort((a, b) -> {
if (!a.getReader().canRead() && b.getReader().canRead()) {
if (!a.parse.getReader().canRead() && b.parse.getReader().canRead()) {
return -1;
}
if (a.getReader().canRead() && !b.getReader().canRead()) {
if (a.parse.getReader().canRead() && !b.parse.getReader().canRead()) {
return 1;
}
if (a.getExceptions().isEmpty() && !b.getExceptions().isEmpty()) {
if (a.parse.getExceptions().isEmpty() && !b.parse.getExceptions().isEmpty()) {
return -1;
}
if (!a.getExceptions().isEmpty() && b.getExceptions().isEmpty()) {
if (!a.parse.getExceptions().isEmpty() && b.parse.getExceptions().isEmpty()) {
return 1;
}
return 0;
});
}
return potentials.get(0);
return potentials.get(0).parse;
}
return new ParseResults<>(contextSoFar, originalReader, errors == null ? Collections.emptyMap() : errors);
return new ParseResults<>(contextSoFar, originalReader.getCursor(), originalReader, errors == null ? Collections.emptyMap() : errors);
}
/**
@ -450,7 +461,7 @@ public class CommandDispatcher<S> {
* @return array of full usage strings under the target node
*/
public String[] getAllUsage(final CommandNode<S> node, final S source, final boolean restricted) {
final ArrayList<String> result = new ArrayList<>();
final ArrayList<String> result = Lists.newArrayList();
getAllUsage(node, source, result, "", restricted);
return result.toArray(new String[result.size()]);
}
@ -496,7 +507,7 @@ public class CommandDispatcher<S> {
* @return array of full usage strings under the target node
*/
public Map<CommandNode<S>, String> getSmartUsage(final CommandNode<S> node, final S source) {
final Map<CommandNode<S>, String> result = new LinkedHashMap<>();
final Map<CommandNode<S>, String> result = Maps.newLinkedHashMap();
final boolean optional = node.getCommand() != null;
for (final CommandNode<S> child : node.getChildren()) {
@ -530,7 +541,7 @@ public class CommandDispatcher<S> {
return self + ARGUMENT_SEPARATOR + usage;
}
} else if (children.size() > 1) {
final Set<String> childUsage = new LinkedHashSet<>();
final Set<String> childUsage = Sets.newLinkedHashSet();
for (final CommandNode<S> child : children) {
final String usage = getSmartUsage(child, source, childOptional, true);
if (usage != null) {
@ -578,25 +589,37 @@ public class CommandDispatcher<S> {
* @return a future that will eventually resolve into a {@link Suggestions} object
*/
public CompletableFuture<Suggestions> getCompletionSuggestions(final ParseResults<S> parse) {
return getCompletionSuggestions(parse, parse.getReader().getTotalLength());
}
final CommandContextBuilder<S> rootContext = parse.getContext();
final CommandContextBuilder<S> context = rootContext.getLastChild();
final CommandNode<S> parent;
final int start;
public CompletableFuture<Suggestions> getCompletionSuggestions(final ParseResults<S> parse, int cursor) {
final CommandContextBuilder<S> context = parse.getContext();
if (context.getNodes().isEmpty()) {
parent = root;
start = parse.getStartIndex();
} else if (parse.getReader().canRead()) {
final Map.Entry<CommandNode<S>, StringRange> entry = Iterables.getLast(context.getNodes().entrySet());
parent = entry.getKey();
start = entry.getValue().getEnd() + 1;
} else if (context.getNodes().size() > 1) {
final Map.Entry<CommandNode<S>, StringRange> entry = Iterables.get(context.getNodes().entrySet(), context.getNodes().size() - 2);
parent = entry.getKey();
start = entry.getValue().getEnd() + 1;
} else if (rootContext != context && context.getNodes().size() > 0) {
final Map.Entry<CommandNode<S>, StringRange> entry = Iterables.getLast(context.getNodes().entrySet());
parent = entry.getKey();
start = entry.getValue().getEnd() + 1;
} else {
parent = root;
start = parse.getStartIndex();
}
final SuggestionContext<S> nodeBeforeCursor = context.findSuggestionContext(cursor);
final CommandNode<S> parent = nodeBeforeCursor.parent;
final int start = Math.min(nodeBeforeCursor.startPos, cursor);
final String fullInput = parse.getReader().getString();
final String truncatedInput = fullInput.substring(0, cursor);
final String truncatedInputLowerCase = truncatedInput.toLowerCase(Locale.ROOT);
@SuppressWarnings("unchecked") final CompletableFuture<Suggestions>[] futures = new CompletableFuture[parent.getChildren().size()];
int i = 0;
for (final CommandNode<S> node : parent.getChildren()) {
CompletableFuture<Suggestions> future = Suggestions.empty();
try {
future = node.listSuggestions(context.build(truncatedInput), new SuggestionsBuilder(truncatedInput, truncatedInputLowerCase, start));
future = node.listSuggestions(context.build(parse.getReader().getString()), new SuggestionsBuilder(parse.getReader().getString(), start));
} catch (final CommandSyntaxException ignored) {
}
futures[i++] = future;
@ -604,11 +627,11 @@ public class CommandDispatcher<S> {
final CompletableFuture<Suggestions> result = new CompletableFuture<>();
CompletableFuture.allOf(futures).thenRun(() -> {
final List<Suggestions> suggestions = new ArrayList<>();
final List<Suggestions> suggestions = Lists.newArrayList();
for (final CompletableFuture<Suggestions> future : futures) {
suggestions.add(future.join());
}
result.complete(Suggestions.merge(fullInput, suggestions));
result.complete(Suggestions.merge(parse.getReader().getString(), suggestions));
});
return result;

View file

@ -13,16 +13,22 @@ import java.util.Map;
public class ParseResults<S> {
private final CommandContextBuilder<S> context;
private final Map<CommandNode<S>, CommandSyntaxException> exceptions;
private final int startIndex;
private final ImmutableStringReader reader;
public ParseResults(final CommandContextBuilder<S> context, final ImmutableStringReader reader, final Map<CommandNode<S>, CommandSyntaxException> exceptions) {
public ParseResults(final CommandContextBuilder<S> context, final int startIndex, final ImmutableStringReader reader, final Map<CommandNode<S>, CommandSyntaxException> exceptions) {
this.context = context;
this.startIndex = startIndex;
this.reader = reader;
this.exceptions = exceptions;
}
public ParseResults(final CommandContextBuilder<S> context) {
this(context, new StringReader(""), Collections.emptyMap());
this(context, 0, new StringReader(""), Collections.emptyMap());
}
public int getStartIndex() {
return startIndex;
}
public CommandContextBuilder<S> getContext() {

View file

@ -6,6 +6,8 @@ package com.mojang.brigadier;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collection;
@FunctionalInterface
public interface SingleRedirectModifier<S> {
S apply(CommandContext<S> context) throws CommandSyntaxException;

View file

@ -7,8 +7,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException;
public class StringReader implements ImmutableStringReader {
private static final char SYNTAX_ESCAPE = '\\';
private static final char SYNTAX_DOUBLE_QUOTE = '"';
private static final char SYNTAX_SINGLE_QUOTE = '\'';
private static final char SYNTAX_QUOTE = '"';
private final String string;
private int cursor;
@ -88,10 +87,6 @@ public class StringReader implements ImmutableStringReader {
return c >= '0' && c <= '9' || c == '.' || c == '-';
}
public static boolean isQuotedStringStart(char c) {
return c == SYNTAX_DOUBLE_QUOTE || c == SYNTAX_SINGLE_QUOTE;
}
public void skipWhitespace() {
while (canRead() && Character.isWhitespace(peek())) {
skip();
@ -115,23 +110,6 @@ public class StringReader implements ImmutableStringReader {
}
}
public long readLong() throws CommandSyntaxException {
final int start = cursor;
while (canRead() && isAllowedNumber(peek())) {
skip();
}
final String number = string.substring(start, cursor);
if (number.isEmpty()) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedLong().createWithContext(this);
}
try {
return Long.parseLong(number);
} catch (final NumberFormatException ex) {
cursor = start;
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidLong().createWithContext(this, number);
}
}
public double readDouble() throws CommandSyntaxException {
final int start = cursor;
while (canRead() && isAllowedNumber(peek())) {
@ -185,22 +163,16 @@ public class StringReader implements ImmutableStringReader {
public String readQuotedString() throws CommandSyntaxException {
if (!canRead()) {
return "";
}
final char next = peek();
if (!isQuotedStringStart(next)) {
} else if (peek() != SYNTAX_QUOTE) {
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedStartOfQuote().createWithContext(this);
}
skip();
return readStringUntil(next);
}
public String readStringUntil(char terminator) throws CommandSyntaxException {
final StringBuilder result = new StringBuilder();
boolean escaped = false;
while (canRead()) {
final char c = read();
if (escaped) {
if (c == terminator || c == SYNTAX_ESCAPE) {
if (c == SYNTAX_QUOTE || c == SYNTAX_ESCAPE) {
result.append(c);
escaped = false;
} else {
@ -209,7 +181,7 @@ public class StringReader implements ImmutableStringReader {
}
} else if (c == SYNTAX_ESCAPE) {
escaped = true;
} else if (c == terminator) {
} else if (c == SYNTAX_QUOTE) {
return result.toString();
} else {
result.append(c);
@ -220,15 +192,11 @@ public class StringReader implements ImmutableStringReader {
}
public String readString() throws CommandSyntaxException {
if (!canRead()) {
return "";
if (canRead() && peek() == SYNTAX_QUOTE) {
return readQuotedString();
} else {
return readUnquotedString();
}
final char next = peek();
if (isQuotedStringStart(next)) {
skip();
return readStringUntil(next);
}
return readUnquotedString();
}
public boolean readBoolean() throws CommandSyntaxException {

View file

@ -5,6 +5,7 @@ package com.mojang.brigadier.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
@ -14,7 +15,7 @@ import java.util.Collections;
import java.util.concurrent.CompletableFuture;
public interface ArgumentType<T> {
T parse(StringReader reader) throws CommandSyntaxException;
<S> T parse(StringReader reader) throws CommandSyntaxException;
default <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
return Suggestions.empty();

View file

@ -5,6 +5,7 @@ package com.mojang.brigadier.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
@ -28,16 +29,16 @@ public class BoolArgumentType implements ArgumentType<Boolean> {
}
@Override
public Boolean parse(final StringReader reader) throws CommandSyntaxException {
public <S> Boolean parse(final StringReader reader) throws CommandSyntaxException {
return reader.readBoolean();
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
if ("true".startsWith(builder.getRemainingLowerCase())) {
if ("true".startsWith(builder.getRemaining().toLowerCase())) {
builder.suggest("true");
}
if ("false".startsWith(builder.getRemainingLowerCase())) {
if ("false".startsWith(builder.getRemaining().toLowerCase())) {
builder.suggest("false");
}
return builder.buildFuture();

View file

@ -46,7 +46,7 @@ public class DoubleArgumentType implements ArgumentType<Double> {
}
@Override
public Double parse(final StringReader reader) throws CommandSyntaxException {
public <S> Double parse(final StringReader reader) throws CommandSyntaxException {
final int start = reader.getCursor();
final double result = reader.readDouble();
if (result < minimum) {

View file

@ -46,7 +46,7 @@ public class FloatArgumentType implements ArgumentType<Float> {
}
@Override
public Float parse(final StringReader reader) throws CommandSyntaxException {
public <S> Float parse(final StringReader reader) throws CommandSyntaxException {
final int start = reader.getCursor();
final float result = reader.readFloat();
if (result < minimum) {

View file

@ -46,7 +46,7 @@ public class IntegerArgumentType implements ArgumentType<Integer> {
}
@Override
public Integer parse(final StringReader reader) throws CommandSyntaxException {
public <S> Integer parse(final StringReader reader) throws CommandSyntaxException {
final int start = reader.getCursor();
final int result = reader.readInt();
if (result < minimum) {
@ -84,9 +84,4 @@ public class IntegerArgumentType implements ArgumentType<Integer> {
return "integer(" + minimum + ", " + maximum + ")";
}
}
@Override
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View file

@ -1,92 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
import java.util.Collection;
public class LongArgumentType implements ArgumentType<Long> {
private static final Collection<String> EXAMPLES = Arrays.asList("0", "123", "-123");
private final long minimum;
private final long maximum;
private LongArgumentType(final long minimum, final long maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
public static LongArgumentType longArg() {
return longArg(Long.MIN_VALUE);
}
public static LongArgumentType longArg(final long min) {
return longArg(min, Long.MAX_VALUE);
}
public static LongArgumentType longArg(final long min, final long max) {
return new LongArgumentType(min, max);
}
public static long getLong(final CommandContext<?> context, final String name) {
return context.getArgument(name, long.class);
}
public long getMinimum() {
return minimum;
}
public long getMaximum() {
return maximum;
}
@Override
public Long parse(final StringReader reader) throws CommandSyntaxException {
final int start = reader.getCursor();
final long result = reader.readLong();
if (result < minimum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooLow().createWithContext(reader, result, minimum);
}
if (result > maximum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooHigh().createWithContext(reader, result, maximum);
}
return result;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof LongArgumentType)) return false;
final LongArgumentType that = (LongArgumentType) o;
return maximum == that.maximum && minimum == that.minimum;
}
@Override
public int hashCode() {
return 31 * Long.hashCode(minimum) + Long.hashCode(maximum);
}
@Override
public String toString() {
if (minimum == Long.MIN_VALUE && maximum == Long.MAX_VALUE) {
return "longArg()";
} else if (maximum == Long.MAX_VALUE) {
return "longArg(" + minimum + ")";
} else {
return "longArg(" + minimum + ", " + maximum + ")";
}
}
@Override
public Collection<String> getExamples() {
return EXAMPLES;
}
}

View file

@ -5,6 +5,7 @@ package com.mojang.brigadier.arguments;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Arrays;
@ -38,7 +39,7 @@ public class StringArgumentType implements ArgumentType<String> {
}
@Override
public String parse(final StringReader reader) throws CommandSyntaxException {
public <S> String parse(final StringReader reader) throws CommandSyntaxException {
if (type == StringType.GREEDY_PHRASE) {
final String text = reader.getRemaining();
reader.setCursor(reader.getTotalLength());

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.builder;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.SingleRedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
@ -21,7 +20,6 @@ public abstract class ArgumentBuilder<S, T extends ArgumentBuilder<S, T>> {
private CommandNode<S> target;
private RedirectModifier<S> modifier = null;
private boolean forks;
private Message description;
protected abstract T getThis();
@ -54,15 +52,6 @@ public abstract class ArgumentBuilder<S, T extends ArgumentBuilder<S, T>> {
return command;
}
public T describe(final Message description) {
this.description = description;
return getThis();
}
public Message getDescription() {
return description;
}
public T requires(final Predicate<S> requirement) {
this.requirement = requirement;
return getThis();

View file

@ -28,7 +28,7 @@ public class LiteralArgumentBuilder<S> extends ArgumentBuilder<S, LiteralArgumen
@Override
public LiteralCommandNode<S> build() {
final LiteralCommandNode<S> result = new LiteralCommandNode<>(getLiteral(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getDescription());
final LiteralCommandNode<S> result = new LiteralCommandNode<>(getLiteral(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork());
for (final CommandNode<S> argument : getArguments()) {
result.addChild(argument);

View file

@ -45,7 +45,7 @@ public class RequiredArgumentBuilder<S, T> extends ArgumentBuilder<S, RequiredAr
}
public ArgumentCommandNode<S, T> build() {
final ArgumentCommandNode<S, T> result = new ArgumentCommandNode<>(getName(), getType(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getSuggestionsProvider(), getDescription());
final ArgumentCommandNode<S, T> result = new ArgumentCommandNode<>(getName(), getType(), getCommand(), getRequirement(), getRedirect(), getRedirectModifier(), isFork(), getSuggestionsProvider());
for (final CommandNode<S> argument : getArguments()) {
result.addChild(argument);

View file

@ -3,46 +3,30 @@
package com.mojang.brigadier.context;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandContext<S> {
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = new HashMap<>();
static {
PRIMITIVE_TO_WRAPPER.put(boolean.class, Boolean.class);
PRIMITIVE_TO_WRAPPER.put(byte.class, Byte.class);
PRIMITIVE_TO_WRAPPER.put(short.class, Short.class);
PRIMITIVE_TO_WRAPPER.put(char.class, Character.class);
PRIMITIVE_TO_WRAPPER.put(int.class, Integer.class);
PRIMITIVE_TO_WRAPPER.put(long.class, Long.class);
PRIMITIVE_TO_WRAPPER.put(float.class, Float.class);
PRIMITIVE_TO_WRAPPER.put(double.class, Double.class);
}
private final S source;
private final String input;
private final Command<S> command;
private final Map<String, ParsedArgument<S, ?>> arguments;
private final CommandNode<S> rootNode;
private final List<ParsedCommandNode<S>> nodes;
private final Map<CommandNode<S>, StringRange> nodes;
private final StringRange range;
private final CommandContext<S> child;
private final RedirectModifier<S> modifier;
private final boolean forks;
public CommandContext(final S source, final String input, final Map<String, ParsedArgument<S, ?>> arguments, final Command<S> command, final CommandNode<S> rootNode, final List<ParsedCommandNode<S>> nodes, final StringRange range, final CommandContext<S> child, final RedirectModifier<S> modifier, boolean forks) {
public CommandContext(final S source, final String input, final Map<String, ParsedArgument<S, ?>> arguments, final Command<S> command, final Map<CommandNode<S>, StringRange> nodes, final StringRange range, final CommandContext<S> child, final RedirectModifier<S> modifier, boolean forks) {
this.source = source;
this.input = input;
this.arguments = arguments;
this.command = command;
this.rootNode = rootNode;
this.nodes = nodes;
this.range = range;
this.child = child;
@ -54,7 +38,7 @@ public class CommandContext<S> {
if (this.source == source) {
return this;
}
return new CommandContext<>(source, input, arguments, command, rootNode, nodes, range, child, modifier, forks);
return new CommandContext<>(source, input, arguments, command, nodes, range, child, modifier, forks);
}
public CommandContext<S> getChild() {
@ -86,7 +70,7 @@ public class CommandContext<S> {
}
final Object result = argument.getResult();
if (PRIMITIVE_TO_WRAPPER.getOrDefault(clazz, clazz).isAssignableFrom(result.getClass())) {
if (Primitives.wrap(clazz).isAssignableFrom(result.getClass())) {
return (V) result;
} else {
throw new IllegalArgumentException("Argument '" + name + "' is defined as " + result.getClass().getSimpleName() + ", not " + clazz);
@ -101,8 +85,7 @@ public class CommandContext<S> {
final CommandContext that = (CommandContext) o;
if (!arguments.equals(that.arguments)) return false;
if (!rootNode.equals(that.rootNode)) return false;
if (nodes.size() != that.nodes.size() || !nodes.equals(that.nodes)) return false;
if (!Iterables.elementsEqual(nodes.entrySet(), that.nodes.entrySet())) return false;
if (command != null ? !command.equals(that.command) : that.command != null) return false;
if (!source.equals(that.source)) return false;
if (child != null ? !child.equals(that.child) : that.child != null) return false;
@ -115,7 +98,6 @@ public class CommandContext<S> {
int result = source.hashCode();
result = 31 * result + arguments.hashCode();
result = 31 * result + (command != null ? command.hashCode() : 0);
result = 31 * result + rootNode.hashCode();
result = 31 * result + nodes.hashCode();
result = 31 * result + (child != null ? child.hashCode() : 0);
return result;
@ -133,18 +115,10 @@ public class CommandContext<S> {
return input;
}
public CommandNode<S> getRootNode() {
return rootNode;
}
public List<ParsedCommandNode<S>> getNodes() {
public Map<CommandNode<S>, StringRange> getNodes() {
return nodes;
}
public boolean hasNodes() {
return !nodes.isEmpty();
}
public boolean isForked() {
return forks;
}

View file

@ -3,20 +3,17 @@
package com.mojang.brigadier.context;
import com.google.common.collect.Maps;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.tree.CommandNode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CommandContextBuilder<S> {
private final Map<String, ParsedArgument<S, ?>> arguments = new LinkedHashMap<>();
private final CommandNode<S> rootNode;
private final List<ParsedCommandNode<S>> nodes = new ArrayList<>();
private final Map<String, ParsedArgument<S, ?>> arguments = Maps.newLinkedHashMap();
private final Map<CommandNode<S>, StringRange> nodes = Maps.newLinkedHashMap();
private final CommandDispatcher<S> dispatcher;
private S source;
private Command<S> command;
@ -25,8 +22,7 @@ public class CommandContextBuilder<S> {
private RedirectModifier<S> modifier = null;
private boolean forks;
public CommandContextBuilder(final CommandDispatcher<S> dispatcher, final S source, final CommandNode<S> rootNode, final int start) {
this.rootNode = rootNode;
public CommandContextBuilder(final CommandDispatcher<S> dispatcher, final S source, final int start) {
this.dispatcher = dispatcher;
this.source = source;
this.range = StringRange.at(start);
@ -41,10 +37,6 @@ public class CommandContextBuilder<S> {
return source;
}
public CommandNode<S> getRootNode() {
return rootNode;
}
public CommandContextBuilder<S> withArgument(final String name, final ParsedArgument<S, ?> argument) {
this.arguments.put(name, argument);
return this;
@ -60,7 +52,7 @@ public class CommandContextBuilder<S> {
}
public CommandContextBuilder<S> withNode(final CommandNode<S> node, final StringRange range) {
nodes.add(new ParsedCommandNode<>(node, range));
nodes.put(node, range);
this.range = StringRange.encompassing(this.range, range);
this.modifier = node.getRedirectModifier();
this.forks = node.isFork();
@ -68,10 +60,10 @@ public class CommandContextBuilder<S> {
}
public CommandContextBuilder<S> copy() {
final CommandContextBuilder<S> copy = new CommandContextBuilder<>(dispatcher, source, rootNode, range.getStart());
final CommandContextBuilder<S> copy = new CommandContextBuilder<>(dispatcher, source, range.getStart());
copy.command = command;
copy.arguments.putAll(arguments);
copy.nodes.addAll(nodes);
copy.nodes.putAll(nodes);
copy.child = child;
copy.range = range;
copy.forks = forks;
@ -99,12 +91,12 @@ public class CommandContextBuilder<S> {
return command;
}
public List<ParsedCommandNode<S>> getNodes() {
public Map<CommandNode<S>, StringRange> getNodes() {
return nodes;
}
public CommandContext<S> build(final String input) {
return new CommandContext<>(source, input, arguments, command, rootNode, nodes, range, child == null ? null : child.build(input), modifier, forks);
return new CommandContext<>(source, input, arguments, command, nodes, range, child == null ? null : child.build(input), modifier, forks);
}
public CommandDispatcher<S> getDispatcher() {
@ -114,33 +106,4 @@ public class CommandContextBuilder<S> {
public StringRange getRange() {
return range;
}
public SuggestionContext<S> findSuggestionContext(final int cursor) {
if (range.getStart() <= cursor) {
if (range.getEnd() < cursor) {
if (child != null) {
return child.findSuggestionContext(cursor);
} else if (!nodes.isEmpty()) {
final ParsedCommandNode<S> last = nodes.get(nodes.size() - 1);
return new SuggestionContext<>(last.getNode(), last.getRange().getEnd() + 1);
} else {
return new SuggestionContext<>(rootNode, range.getStart());
}
} else {
CommandNode<S> prev = rootNode;
for (final ParsedCommandNode<S> node : nodes) {
final StringRange nodeRange = node.getRange();
if (nodeRange.getStart() <= cursor && cursor <= nodeRange.getEnd()) {
return new SuggestionContext<>(prev, nodeRange.getStart());
}
prev = node.getNode();
}
if (prev == null) {
throw new IllegalStateException("Can't find node before cursor");
}
return new SuggestionContext<>(prev, range.getStart());
}
}
throw new IllegalStateException("Can't find node before cursor");
}
}

View file

@ -1,47 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.context;
import com.mojang.brigadier.tree.CommandNode;
import java.util.Objects;
public class ParsedCommandNode<S> {
private final CommandNode<S> node;
private final StringRange range;
public ParsedCommandNode(CommandNode<S> node, StringRange range) {
this.node = node;
this.range = range;
}
public CommandNode<S> getNode() {
return node;
}
public StringRange getRange() {
return range;
}
@Override
public String toString() {
return node + "@" + range;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParsedCommandNode<?> that = (ParsedCommandNode<?>) o;
return Objects.equals(node, that.node) &&
Objects.equals(range, that.range);
}
@Override
public int hashCode() {
return Objects.hash(node, range);
}
}

View file

@ -1,16 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.context;
import com.mojang.brigadier.tree.CommandNode;
public class SuggestionContext<S> {
public final CommandNode<S> parent;
public final int startPos;
public SuggestionContext(CommandNode<S> parent, int startPos) {
this.parent = parent;
this.startPos = startPos;
}
}

View file

@ -16,10 +16,6 @@ public interface BuiltInExceptionProvider {
Dynamic2CommandExceptionType integerTooHigh();
Dynamic2CommandExceptionType longTooLow();
Dynamic2CommandExceptionType longTooHigh();
DynamicCommandExceptionType literalIncorrect();
SimpleCommandExceptionType readerExpectedStartOfQuote();
@ -34,10 +30,6 @@ public interface BuiltInExceptionProvider {
SimpleCommandExceptionType readerExpectedInt();
DynamicCommandExceptionType readerInvalidLong();
SimpleCommandExceptionType readerExpectedLong();
DynamicCommandExceptionType readerInvalidDouble();
SimpleCommandExceptionType readerExpectedDouble();

View file

@ -15,9 +15,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
private static final Dynamic2CommandExceptionType INTEGER_TOO_SMALL = new Dynamic2CommandExceptionType((found, min) -> new LiteralMessage("Integer must not be less than " + min + ", found " + found));
private static final Dynamic2CommandExceptionType INTEGER_TOO_BIG = new Dynamic2CommandExceptionType((found, max) -> new LiteralMessage("Integer must not be more than " + max + ", found " + found));
private static final Dynamic2CommandExceptionType LONG_TOO_SMALL = new Dynamic2CommandExceptionType((found, min) -> new LiteralMessage("Long must not be less than " + min + ", found " + found));
private static final Dynamic2CommandExceptionType LONG_TOO_BIG = new Dynamic2CommandExceptionType((found, max) -> new LiteralMessage("Long must not be more than " + max + ", found " + found));
private static final DynamicCommandExceptionType LITERAL_INCORRECT = new DynamicCommandExceptionType(expected -> new LiteralMessage("Expected literal " + expected));
private static final SimpleCommandExceptionType READER_EXPECTED_START_OF_QUOTE = new SimpleCommandExceptionType(new LiteralMessage("Expected quote to start a string"));
@ -26,8 +23,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
private static final DynamicCommandExceptionType READER_INVALID_BOOL = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid bool, expected true or false but found '" + value + "'"));
private static final DynamicCommandExceptionType READER_INVALID_INT = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid integer '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_INT = new SimpleCommandExceptionType(new LiteralMessage("Expected integer"));
private static final DynamicCommandExceptionType READER_INVALID_LONG = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid long '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_LONG = new SimpleCommandExceptionType((new LiteralMessage("Expected long")));
private static final DynamicCommandExceptionType READER_INVALID_DOUBLE = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid double '" + value + "'"));
private static final SimpleCommandExceptionType READER_EXPECTED_DOUBLE = new SimpleCommandExceptionType(new LiteralMessage("Expected double"));
private static final DynamicCommandExceptionType READER_INVALID_FLOAT = new DynamicCommandExceptionType(value -> new LiteralMessage("Invalid float '" + value + "'"));
@ -70,16 +65,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
return INTEGER_TOO_BIG;
}
@Override
public Dynamic2CommandExceptionType longTooLow() {
return LONG_TOO_SMALL;
}
@Override
public Dynamic2CommandExceptionType longTooHigh() {
return LONG_TOO_BIG;
}
@Override
public DynamicCommandExceptionType literalIncorrect() {
return LITERAL_INCORRECT;
@ -115,16 +100,6 @@ public class BuiltInExceptions implements BuiltInExceptionProvider {
return READER_EXPECTED_INT;
}
@Override
public DynamicCommandExceptionType readerInvalidLong() {
return READER_INVALID_LONG;
}
@Override
public SimpleCommandExceptionType readerExpectedLong() {
return READER_EXPECTED_LONG;
}
@Override
public DynamicCommandExceptionType readerInvalidDouble() {
return READER_INVALID_DOUBLE;

View file

@ -3,9 +3,10 @@
package com.mojang.brigadier.suggestion;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mojang.brigadier.context.StringRange;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@ -14,7 +15,7 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
public class Suggestions {
private static final Suggestions EMPTY = new Suggestions(StringRange.at(0), new ArrayList<>());
private static final Suggestions EMPTY = new Suggestions(StringRange.at(0), Lists.newArrayList());
private final StringRange range;
private final List<Suggestion> suggestions;
@ -91,11 +92,11 @@ public class Suggestions {
end = Math.max(suggestion.getRange().getEnd(), end);
}
final StringRange range = new StringRange(start, end);
final Set<Suggestion> texts = new HashSet<>();
final Set<Suggestion> texts = Sets.newHashSet();
for (final Suggestion suggestion : suggestions) {
texts.add(suggestion.expand(command, range));
}
final List<Suggestion> sorted = new ArrayList<>(texts);
final List<Suggestion> sorted = Lists.newArrayList(texts);
sorted.sort((a, b) -> a.compareToIgnoreCase(b));
return new Suggestions(range, sorted);
}

View file

@ -8,27 +8,18 @@ import com.mojang.brigadier.context.StringRange;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class SuggestionsBuilder {
private final String input;
private final String inputLowerCase;
private final int start;
private final String remaining;
private final String remainingLowerCase;
private final List<Suggestion> result = new ArrayList<>();
public SuggestionsBuilder(final String input, final String inputLowerCase, final int start) {
public SuggestionsBuilder(final String input, final int start) {
this.input = input;
this.inputLowerCase = inputLowerCase;
this.start = start;
this.remaining = input.substring(start);
this.remainingLowerCase = inputLowerCase.substring(start);
}
public SuggestionsBuilder(final String input, final int start) {
this(input, input.toLowerCase(Locale.ROOT), start);
}
public String getInput() {
@ -43,10 +34,6 @@ public class SuggestionsBuilder {
return remaining;
}
public String getRemainingLowerCase() {
return remainingLowerCase;
}
public Suggestions build() {
return Suggestions.create(input, result);
}
@ -87,10 +74,10 @@ public class SuggestionsBuilder {
}
public SuggestionsBuilder createOffset(final int start) {
return new SuggestionsBuilder(input, inputLowerCase, start);
return new SuggestionsBuilder(input, start);
}
public SuggestionsBuilder restart() {
return createOffset(start);
return new SuggestionsBuilder(input, start);
}
}

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
@ -30,11 +29,7 @@ public class ArgumentCommandNode<S, T> extends CommandNode<S> {
private final SuggestionProvider<S> customSuggestions;
public ArgumentCommandNode(final String name, final ArgumentType<T> type, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final SuggestionProvider<S> customSuggestions) {
this(name, type, command, requirement, redirect, modifier, forks, customSuggestions, null);
}
public ArgumentCommandNode(final String name, final ArgumentType<T> type, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final SuggestionProvider<S> customSuggestions, final Message description) {
super(command, requirement, redirect, modifier, forks, description);
super(command, requirement, redirect, modifier, forks);
this.name = name;
this.type = type;
this.customSuggestions = customSuggestions;

View file

@ -3,7 +3,13 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.*;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
@ -13,45 +19,35 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
private final Map<String, CommandNode<S>> children = new LinkedHashMap<>();
private final Map<String, LiteralCommandNode<S>> literals = new LinkedHashMap<>();
private final Map<String, ArgumentCommandNode<S, ?>> arguments = new LinkedHashMap<>();
private Map<String, CommandNode<S>> children = Maps.newLinkedHashMap();
private Map<String, LiteralCommandNode<S>> literals = Maps.newLinkedHashMap();
private Map<String, ArgumentCommandNode<S, ?>> arguments = Maps.newLinkedHashMap();
private final Predicate<S> requirement;
private final CommandNode<S> redirect;
private final RedirectModifier<S> modifier;
private final boolean forks;
private Command<S> command;
private Message description;
protected CommandNode(final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks) {
this(command, requirement, redirect, modifier, forks, null);
}
protected CommandNode(final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final Message description) {
this.command = command;
this.requirement = requirement;
this.redirect = redirect;
this.modifier = modifier;
this.forks = forks;
this.description = description;
}
public Command<S> getCommand() {
return command;
}
public Message getDescription() {
return description;
}
public Collection<CommandNode<S>> getChildren() {
return children.values();
}
@ -94,10 +90,12 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
arguments.put(node.getName(), (ArgumentCommandNode<S, ?>) node);
}
}
children = children.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
public void findAmbiguities(final AmbiguityConsumer<S> consumer) {
Set<String> matches = new HashSet<>();
Set<String> matches = Sets.newHashSet();
for (final CommandNode<S> child : children.values()) {
for (final CommandNode<S> sibling : children.values()) {
@ -113,7 +111,7 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
if (matches.size() > 0) {
consumer.ambiguous(this, child, sibling, matches);
matches = new HashSet<>();
matches = Sets.newHashSet();
}
}
@ -178,11 +176,11 @@ public abstract class CommandNode<S> implements Comparable<CommandNode<S>> {
@Override
public int compareTo(final CommandNode<S> o) {
if (this instanceof LiteralCommandNode == o instanceof LiteralCommandNode) {
return getSortedKey().compareTo(o.getSortedKey());
}
return (o instanceof LiteralCommandNode) ? 1 : -1;
return ComparisonChain
.start()
.compareTrueFirst(this instanceof LiteralCommandNode, o instanceof LiteralCommandNode)
.compare(getSortedKey(), o.getSortedKey())
.result();
}
public boolean isFork() {

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier.tree;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.Message;
import com.mojang.brigadier.RedirectModifier;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
@ -17,22 +16,15 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
public class LiteralCommandNode<S> extends CommandNode<S> {
private final String literal;
private final String literalLowerCase;
public LiteralCommandNode(final String literal, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks) {
this(literal, command, requirement, redirect, modifier, forks, null);
}
public LiteralCommandNode(final String literal, final Command<S> command, final Predicate<S> requirement, final CommandNode<S> redirect, final RedirectModifier<S> modifier, final boolean forks, final Message description) {
super(command, requirement, redirect, modifier, forks, description);
super(command, requirement, redirect, modifier, forks);
this.literal = literal;
this.literalLowerCase = literal.toLowerCase(Locale.ROOT);
}
public String getLiteral() {
@ -74,7 +66,7 @@ public class LiteralCommandNode<S> extends CommandNode<S> {
@Override
public CompletableFuture<Suggestions> listSuggestions(final CommandContext<S> context, final SuggestionsBuilder builder) {
if (literalLowerCase.startsWith(builder.getRemainingLowerCase())) {
if (literal.toLowerCase().startsWith(builder.getRemaining().toLowerCase())) {
return builder.suggest(literal).buildFuture();
} else {
return Suggestions.empty();

View file

@ -17,7 +17,7 @@ import java.util.concurrent.CompletableFuture;
public class RootCommandNode<S> extends CommandNode<S> {
public RootCommandNode() {
super(null, c -> true, null, s -> Collections.singleton(s.getSource()), false, null);
super(null, c -> true, null, s -> Collections.singleton(s.getSource()), false);
}
@Override

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier;
import com.google.common.collect.Lists;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
@ -15,9 +14,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal;
import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument;
@ -263,33 +259,23 @@ public class CommandDispatcherTest {
@SuppressWarnings("unchecked")
@Test
public void testExecuteRedirectedMultipleTimes() throws Exception {
final LiteralCommandNode<Object> concreteNode = subject.register(literal("actual").executes(command));
final LiteralCommandNode<Object> redirectNode = subject.register(literal("redirected").redirect(subject.getRoot()));
subject.register(literal("actual").executes(command));
subject.register(literal("redirected").redirect(subject.getRoot()));
final String input = "redirected redirected actual";
final ParseResults<Object> parse = subject.parse(input, source);
assertThat(parse.getContext().getRange().get(input), equalTo("redirected"));
assertThat(parse.getContext().getNodes().size(), is(1));
assertThat(parse.getContext().getRootNode(), is(subject.getRoot()));
assertThat(parse.getContext().getNodes().get(0).getRange(), equalTo(parse.getContext().getRange()));
assertThat(parse.getContext().getNodes().get(0).getNode(), is(redirectNode));
final CommandContextBuilder<Object> child1 = parse.getContext().getChild();
assertThat(child1, is(notNullValue()));
assertThat(child1.getRange().get(input), equalTo("redirected"));
assertThat(child1.getNodes().size(), is(1));
assertThat(child1.getRootNode(), is(subject.getRoot()));
assertThat(child1.getNodes().get(0).getRange(), equalTo(child1.getRange()));
assertThat(child1.getNodes().get(0).getNode(), is(redirectNode));
assertThat(child1.getRange().get(input), equalTo("redirected redirected"));
assertThat(child1.getNodes().size(), is(2));
final CommandContextBuilder<Object> child2 = child1.getChild();
assertThat(child2, is(notNullValue()));
assertThat(child2.getRange().get(input), equalTo("actual"));
assertThat(child2.getNodes().size(), is(1));
assertThat(child2.getRootNode(), is(subject.getRoot()));
assertThat(child2.getNodes().get(0).getRange(), equalTo(child2.getRange()));
assertThat(child2.getNodes().get(0).getNode(), is(concreteNode));
assertThat(child2.getRange().get(input), equalTo("redirected actual"));
assertThat(child2.getNodes().size(), is(2));
assertThat(subject.execute(parse), is(42));
verify(command).run(any(CommandContext.class));
@ -304,25 +290,19 @@ public class CommandDispatcherTest {
when(modifier.apply(argThat(hasProperty("source", is(source))))).thenReturn(Lists.newArrayList(source1, source2));
final LiteralCommandNode<Object> concreteNode = subject.register(literal("actual").executes(command));
final LiteralCommandNode<Object> redirectNode = subject.register(literal("redirected").fork(subject.getRoot(), modifier));
subject.register(literal("actual").executes(command));
subject.register(literal("redirected").fork(subject.getRoot(), modifier));
final String input = "redirected actual";
final ParseResults<Object> parse = subject.parse(input, source);
assertThat(parse.getContext().getRange().get(input), equalTo("redirected"));
assertThat(parse.getContext().getNodes().size(), is(1));
assertThat(parse.getContext().getRootNode(), equalTo(subject.getRoot()));
assertThat(parse.getContext().getNodes().get(0).getRange(), equalTo(parse.getContext().getRange()));
assertThat(parse.getContext().getNodes().get(0).getNode(), is(redirectNode));
assertThat(parse.getContext().getSource(), is(source));
final CommandContextBuilder<Object> parent = parse.getContext().getChild();
assertThat(parent, is(notNullValue()));
assertThat(parent.getRange().get(input), equalTo("actual"));
assertThat(parent.getNodes().size(), is(1));
assertThat(parse.getContext().getRootNode(), equalTo(subject.getRoot()));
assertThat(parent.getNodes().get(0).getRange(), equalTo(parent.getRange()));
assertThat(parent.getNodes().get(0).getNode(), is(concreteNode));
assertThat(parent.getRange().get(input), equalTo("redirected actual"));
assertThat(parent.getNodes().size(), is(2));
assertThat(parent.getSource(), is(source));
assertThat(subject.execute(parse), is(2));
@ -330,37 +310,6 @@ public class CommandDispatcherTest {
verify(command).run(argThat(hasProperty("source", is(source2))));
}
@Test
public void testIncompleteRedirectShouldThrow() {
final LiteralCommandNode<Object> foo = subject.register(literal("foo")
.then(literal("bar")
.then(argument("value", integer()).executes(context -> IntegerArgumentType.getInteger(context, "value"))))
.then(literal("awa").executes(context -> 2)));
final LiteralCommandNode<Object> baz = subject.register(literal("baz").redirect(foo));
try {
int result = subject.execute("baz bar", source);
fail("Should have thrown an exception");
} catch (CommandSyntaxException e) {
assertThat(e.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand()));
}
}
@Test
public void testRedirectModifierEmptyResult() {
final LiteralCommandNode<Object> foo = subject.register(literal("foo")
.then(literal("bar")
.then(argument("value", integer()).executes(context -> IntegerArgumentType.getInteger(context, "value"))))
.then(literal("awa").executes(context -> 2)));
final RedirectModifier<Object> emptyModifier = context -> Collections.emptyList();
final LiteralCommandNode<Object> baz = subject.register(literal("baz").fork(foo, emptyModifier));
try {
int result = subject.execute("baz bar 100", source);
assertThat(result, is(0)); // No commands executed, so result is 0
} catch (CommandSyntaxException e) {
fail("Should not throw an exception");
}
}
@Test
public void testExecuteOrphanedSubcommand() throws Exception {
subject.register(literal("foo").then(

View file

@ -4,7 +4,6 @@
package com.mojang.brigadier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
@ -103,11 +102,11 @@ public class CommandDispatcherUsagesTest {
}
private CommandNode<Object> get(final String command) {
return Iterables.getLast(subject.parse(command, source).getContext().getNodes()).getNode();
return Iterators.getLast(subject.parse(command, source).getContext().getNodes().keySet().iterator());
}
private CommandNode<Object> get(final StringReader command) {
return Iterables.getLast(subject.parse(command, source).getContext().getNodes()).getNode();
return Iterators.getLast(subject.parse(command, source).getContext().getNodes().keySet().iterator());
}
@Test
@ -190,10 +189,10 @@ public class CommandDispatcherUsagesTest {
final Map<CommandNode<Object>, String> results = subject.getSmartUsage(get(offsetH), source);
assertThat(results, equalTo(ImmutableMap.builder()
.put(get("h 1"), "[1] i")
.put(get("h 2"), "[2] i ii")
.put(get("h 3"), "[3]")
.build()
.put(get("h 1"), "[1] i")
.put(get("h 2"), "[2] i ii")
.put(get("h 3"), "[3]")
.build()
));
}
}

View file

@ -14,8 +14,6 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static com.mojang.brigadier.arguments.StringArgumentType.word;
import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal;
@ -35,18 +33,6 @@ public class CommandSuggestionsTest {
subject = new CommandDispatcher<>();
}
private void testSuggestions(final String contents, final int cursor, final StringRange range, final String... suggestions) {
final Suggestions result = subject.getCompletionSuggestions(subject.parse(contents, source), cursor).join();
assertThat(result.getRange(), equalTo(range));
final List<Suggestion> expected = Lists.newArrayList();
for (final String suggestion : suggestions) {
expected.add(new Suggestion(range, suggestion));
}
assertThat(result.getList(), equalTo(expected));
}
private static StringReader inputWithOffset(final String input, final int offset) {
final StringReader result = new StringReader(input);
result.setCursor(offset);
@ -116,31 +102,6 @@ public class CommandSuggestionsTest {
assertThat(result.getList(), equalTo(Lists.newArrayList(new Suggestion(StringRange.at(7), "bar"), new Suggestion(StringRange.at(7), "baz"), new Suggestion(StringRange.at(7), "foo"))));
}
@Test
public void getCompletionSuggestions_movingCursor_subCommands() throws Exception {
subject.register(
literal("parent_one")
.then(literal("faz"))
.then(literal("fbz"))
.then(literal("gaz"))
);
subject.register(
literal("parent_two")
);
testSuggestions("parent_one faz ", 0, StringRange.at(0), "parent_one", "parent_two");
testSuggestions("parent_one faz ", 1, StringRange.between(0, 1), "parent_one", "parent_two");
testSuggestions("parent_one faz ", 7, StringRange.between(0, 7), "parent_one", "parent_two");
testSuggestions("parent_one faz ", 8, StringRange.between(0, 8), "parent_one");
testSuggestions("parent_one faz ", 10, StringRange.at(0));
testSuggestions("parent_one faz ", 11, StringRange.at(11), "faz", "fbz", "gaz");
testSuggestions("parent_one faz ", 12, StringRange.between(11, 12), "faz", "fbz");
testSuggestions("parent_one faz ", 13, StringRange.between(11, 13), "faz");
testSuggestions("parent_one faz ", 14, StringRange.at(0));
testSuggestions("parent_one faz ", 15, StringRange.at(0));
}
@Test
public void getCompletionSuggestions_subCommands_partial() throws Exception {
subject.register(
@ -160,10 +121,10 @@ public class CommandSuggestionsTest {
@Test
public void getCompletionSuggestions_subCommands_partial_withInputOffset() throws Exception {
subject.register(
literal("parent")
.then(literal("foo"))
.then(literal("bar"))
.then(literal("baz"))
literal("parent")
.then(literal("foo"))
.then(literal("bar"))
.then(literal("baz"))
);
final ParseResults<Object> parse = subject.parse(inputWithOffset("junk parent b", 5), source);
@ -197,29 +158,6 @@ public class CommandSuggestionsTest {
assertThat(result.getList(), equalTo(Lists.newArrayList(new Suggestion(StringRange.between(9, 10), "sub"))));
}
@Test
public void getCompletionSuggestions_movingCursor_redirect() throws Exception {
final LiteralCommandNode<Object> actualOne = subject.register(literal("actual_one")
.then(literal("faz"))
.then(literal("fbz"))
.then(literal("gaz"))
);
final LiteralCommandNode<Object> actualTwo = subject.register(literal("actual_two"));
subject.register(literal("redirect_one").redirect(actualOne));
subject.register(literal("redirect_two").redirect(actualOne));
testSuggestions("redirect_one faz ", 0, StringRange.at(0), "actual_one", "actual_two", "redirect_one", "redirect_two");
testSuggestions("redirect_one faz ", 9, StringRange.between(0, 9), "redirect_one", "redirect_two");
testSuggestions("redirect_one faz ", 10, StringRange.between(0, 10), "redirect_one");
testSuggestions("redirect_one faz ", 12, StringRange.at(0));
testSuggestions("redirect_one faz ", 13, StringRange.at(13), "faz", "fbz", "gaz");
testSuggestions("redirect_one faz ", 14, StringRange.between(13, 14), "faz", "fbz");
testSuggestions("redirect_one faz ", 15, StringRange.between(13, 15), "faz");
testSuggestions("redirect_one faz ", 16, StringRange.at(0));
testSuggestions("redirect_one faz ", 17, StringRange.at(0));
}
@Test
public void getCompletionSuggestions_redirectPartial_withInputOffset() throws Exception {

View file

@ -156,30 +156,6 @@ public class StringReaderTest {
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readSingleQuotedString() throws Exception {
final StringReader reader = new StringReader("'hello world'");
assertThat(reader.readQuotedString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("'hello world'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readMixedQuotedString_doubleInsideSingle() throws Exception {
final StringReader reader = new StringReader("'hello \"world\"'");
assertThat(reader.readQuotedString(), equalTo("hello \"world\""));
assertThat(reader.getRead(), equalTo("'hello \"world\"'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readMixedQuotedString_singleInsideDouble() throws Exception {
final StringReader reader = new StringReader("\"hello 'world'\"");
assertThat(reader.readQuotedString(), equalTo("hello 'world'"));
assertThat(reader.getRead(), equalTo("\"hello 'world'\""));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readQuotedString_empty() throws Exception {
final StringReader reader = new StringReader("");
@ -266,40 +242,6 @@ public class StringReaderTest {
}
}
@Test
public void readQuotedString_invalidQuoteEscape() throws Exception {
try {
new StringReader("'hello\\\"\'world").readQuotedString();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidEscape()));
assertThat(ex.getCursor(), is(7));
}
}
@Test
public void readString_noQuotes() throws Exception {
final StringReader reader = new StringReader("hello world");
assertThat(reader.readString(), equalTo("hello"));
assertThat(reader.getRead(), equalTo("hello"));
assertThat(reader.getRemaining(), equalTo(" world"));
}
@Test
public void readString_singleQuotes() throws Exception {
final StringReader reader = new StringReader("'hello world'");
assertThat(reader.readString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("'hello world'"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readString_doubleQuotes() throws Exception {
final StringReader reader = new StringReader("\"hello world\"");
assertThat(reader.readString(), equalTo("hello world"));
assertThat(reader.getRead(), equalTo("\"hello world\""));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readInt() throws Exception {
final StringReader reader = new StringReader("1234567890");
@ -352,58 +294,6 @@ public class StringReaderTest {
assertThat(reader.getRemaining(), equalTo("foo bar"));
}
@Test
public void readLong() throws Exception {
final StringReader reader = new StringReader("1234567890");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readLong_negative() throws Exception {
final StringReader reader = new StringReader("-1234567890");
assertThat(reader.readLong(), is(-1234567890L));
assertThat(reader.getRead(), equalTo("-1234567890"));
assertThat(reader.getRemaining(), equalTo(""));
}
@Test
public void readLong_invalid() throws Exception {
try {
new StringReader("12.34").readLong();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerInvalidLong()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void readLong_none() throws Exception {
try {
new StringReader("").readLong();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.readerExpectedLong()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void readLong_withRemaining() throws Exception {
final StringReader reader = new StringReader("1234567890 foo bar");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo(" foo bar"));
}
@Test
public void readLong_withRemainingImmediate() throws Exception {
final StringReader reader = new StringReader("1234567890foo bar");
assertThat(reader.readLong(), is(1234567890L));
assertThat(reader.getRead(), equalTo("1234567890"));
assertThat(reader.getRemaining(), equalTo("foo bar"));
}
@Test
public void readDouble() throws Exception {
final StringReader reader = new StringReader("123");

View file

@ -1,81 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.brigadier.arguments;
import com.google.common.testing.EqualsTester;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.context.CommandContextBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.mojang.brigadier.arguments.LongArgumentType.longArg;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@RunWith(MockitoJUnitRunner.class)
public class LongArgumentTypeTest {
private LongArgumentType type;
@Mock
private CommandContextBuilder<Object> context;
@Before
public void setUp() throws Exception {
type = longArg(-100, 1_000_000_000_000L);
}
@Test
public void parse() throws Exception {
final StringReader reader = new StringReader("15");
assertThat(longArg().parse(reader), is(15L));
assertThat(reader.canRead(), is(false));
}
@Test
public void parse_tooSmall() throws Exception {
final StringReader reader = new StringReader("-5");
try {
longArg(0, 100).parse(reader);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooLow()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void parse_tooBig() throws Exception {
final StringReader reader = new StringReader("5");
try {
longArg(-100, 0).parse(reader);
fail();
} catch (final CommandSyntaxException ex) {
assertThat(ex.getType(), is(CommandSyntaxException.BUILT_IN_EXCEPTIONS.longTooHigh()));
assertThat(ex.getCursor(), is(0));
}
}
@Test
public void testEquals() throws Exception {
new EqualsTester()
.addEqualityGroup(longArg(), longArg())
.addEqualityGroup(longArg(-100, 100), longArg(-100, 100))
.addEqualityGroup(longArg(-100, 50), longArg(-100, 50))
.addEqualityGroup(longArg(-50, 100), longArg(-50, 100))
.testEquals();
}
@Test
public void testToString() throws Exception {
assertThat(longArg(), hasToString("longArg()"));
assertThat(longArg(-100), hasToString("longArg(-100)"));
assertThat(longArg(-100, 100), hasToString("longArg(-100, 100)"));
assertThat(longArg(Long.MIN_VALUE, 100), hasToString("longArg(-9223372036854775808, 100)"));
}
}

View file

@ -7,13 +7,13 @@ import com.google.common.testing.EqualsTester;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.RootCommandNode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static com.mojang.brigadier.arguments.IntegerArgumentType.integer;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
@ -26,12 +26,9 @@ public class CommandContextTest {
@Mock
private CommandDispatcher<Object> dispatcher;
@Mock
private CommandNode<Object> rootNode;
@Before
public void setUp() throws Exception {
builder = new CommandContextBuilder<>(dispatcher, source, rootNode, 0);
builder = new CommandContextBuilder<>(dispatcher, source, 0);
}
@Test(expected = IllegalArgumentException.class)
@ -56,30 +53,22 @@ public class CommandContextTest {
assertThat(builder.build("").getSource(), is(source));
}
@Test
public void testRootNode() throws Exception {
assertThat(builder.build("").getRootNode(), is(rootNode));
}
@SuppressWarnings("unchecked")
@Test
public void testEquals() throws Exception {
final Object otherSource = new Object();
final Command<Object> command = mock(Command.class);
final Command<Object> otherCommand = mock(Command.class);
final CommandNode<Object> rootNode = mock(CommandNode.class);
final CommandNode<Object> otherRootNode = mock(CommandNode.class);
final CommandNode<Object> node = mock(CommandNode.class);
final CommandNode<Object> otherNode = mock(CommandNode.class);
new EqualsTester()
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, otherRootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, source, otherRootNode, 0).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, otherSource, rootNode, 0).build(""), new CommandContextBuilder<>(dispatcher, otherSource, rootNode, 0).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(command).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(command).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(otherCommand).build(""), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withCommand(otherCommand).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, rootNode, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).build(""), new CommandContextBuilder<>(dispatcher, source, 0).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, otherSource, 0).build(""), new CommandContextBuilder<>(dispatcher, otherSource, 0).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).withCommand(command).build(""), new CommandContextBuilder<>(dispatcher, source, 0).withCommand(command).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).withCommand(otherCommand).build(""), new CommandContextBuilder<>(dispatcher, source, 0).withCommand(otherCommand).build(""))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"), new CommandContextBuilder<>(dispatcher, source, 0).withArgument("foo", new ParsedArgument<>(0, 1, 123)).build("123"))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, 0).withNode(node, StringRange.between(0, 3)).withNode(otherNode, StringRange.between(4, 6)).build("123 456"))
.addEqualityGroup(new CommandContextBuilder<>(dispatcher, source, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"), new CommandContextBuilder<>(dispatcher, source, 0).withNode(otherNode, StringRange.between(0, 3)).withNode(node, StringRange.between(4, 6)).build("123 456"))
.testEquals();
}
}

View file

@ -32,7 +32,7 @@ public class ArgumentCommandNodeTest extends AbstractCommandNodeTest {
@Before
public void setUp() throws Exception {
node = argument("foo", integer()).build();
contextBuilder = new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), new RootCommandNode<>(), 0);
contextBuilder = new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), 0);
}
@Test

View file

@ -37,7 +37,7 @@ public class LiteralCommandNodeTest extends AbstractCommandNodeTest {
@Before
public void setUp() throws Exception {
node = literal("foo").build();
contextBuilder = new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), new RootCommandNode<>(), 0);
contextBuilder = new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), 0);
}
@Test

View file

@ -34,7 +34,7 @@ public class RootCommandNodeTest extends AbstractCommandNodeTest {
@Test
public void testParse() throws Exception {
final StringReader reader = new StringReader("hello world");
node.parse(reader, new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), new RootCommandNode<>(), 0));
node.parse(reader, new CommandContextBuilder<>(new CommandDispatcher<>(), new Object(), 0));
assertThat(reader.getCursor(), is(0));
}