Crate brigadier_rs
source ·Expand description
Minecraft command parsing crate inspired by Brigadier
and nom
. This crate tries to combine the easy syntax from
Brigadier
with the performant parsing concepts of nom
.
Creating a parser
Using the builder pattern, different parsers can be chained together to
create a logical tree a command can be propagated through. This is done by
using the appropiate parser functions in the root of the crate. Custom
parsers can be implemented using CommandArgument
and most other traits.
It is recommended to look at parser structs in parsers
for inspiration.
Example
let parser = literal("foo")
.then(
integer_i32("bar")
.build_exec(|ctx: (), bar| {
println!("Bar is {}", bar);
Ok::<(), Infallible>(())
})
).build_exec(|ctx: ()| {
println!("Called foo with no arguments");
Ok::<(), Infallible>(())
});
This code creates a new parser that can parse commands in the forms of foo
and foo <bar>
and can be represented in a tree like this:
+-----------+ +---------+
| i32 (bar) +-----> | Execute |
+-----+-----+ +---------+
^
|
+---+------+
+-----------+ | (foo) | +---------+
| lit (foo) +-->| Then +----> | Execute |
+-----------+ +----------+ +---------+
The parser first expects a literal string “foo” as denoted by the
literal("foo")
. After this literal value, an optional integer can be
provided. Note that the second argument is optional due to the Execute
attached to the Then
that branches to that argument.
Unlike Mojang’s brigadier, arguments are not collected in a Context
object. They are instead fed directly into the provided closures. A generic
context however is provided so dependents can pass data to the closures
after parsing (ctx
in the example).
Command help
A HelpArgument
is provided to easily integrate a command into a help
system. This is done by calling help()
on a command parser like this:
let parser = literal("foo")
.then(
integer_i32("bar")
.build_exec(|ctx: (), bar| {
println!("Bar is {}", bar);
Ok::<(), Infallible>(())
})
).build_exec(|ctx| {
println!("Called foo with no arguments");
Ok::<(), Infallible>(())
})
.help("Short description of foo")
.build_exec(|ctx: (), usages: UsagePrint<_>| {
println!("'foo help' was called");
Ok::<(), Infallible>(())
});
The parser can now return foo
and Short description of foo
when queried
using HelpUsage
, this is useful for collecting a list of commands. This
also automatically chains a HelpArgument
for foo help
. The usages
variable is an iterator over all the different
syntaxes this parser understands (UsagePrint
). In this example, that
would be:
foo
foo <bar>
There will be as many syntaxes as action points (build_exec
orbuild_propagate
) defined. Note that foo help
is ignored.
Modules
Structs
MultipleUsage
iterators.MultipleUsage
iterator
with the contained SingleUsage
.MultipleUsage
iterator.Enums
CommandError
.Traits
MultipleUsage
that want to return a single “root” usage
in the parser tree.Execute
and HelpUsage
.MultipleUsage
.Write
.CommandArgument
).