Parse every command exactly as vanilla's Brigadier tree does
Ports vanilla's packrat parser with SNBT and component-predicate grammars, the entity selector, block state and item parsers, resource-or-inline codec arguments, and the remaining argument types, suggestion providers and error cursors. The tree gains compute, data modify compute, place, locate poi, datapack create, item modifiers and the parse-only commands (dialog, kick, posteffect, fetchprofile, spectate, publish, waypoint, debug, jfr), with release-dispatcher permissions. /particle takes the 26.3 option syntax. The oracle's stand-in server now holds a fresh world's real state (data pack managers, pack repository, empty storages, clocks, templates, an overworld), so vanilla answers every input instead of crashing on about 1,100 per level. The command parse harness matches on 39,685 of 39,685 commands at permission levels 4, 2 and 0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
//!
|
||||
//! usage: command_parse_fixture RESOURCES REGISTRIES.json CORPUS PERMISSION OUTPUT
|
||||
use horizon_client::{
|
||||
command::{ArgType, Dispatcher, NodeKind, Registries, vanilla},
|
||||
command::{ArgType, Dispatcher, NodeKind, Registries, args::RegistryIds, vanilla},
|
||||
lang,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
@@ -46,8 +46,23 @@ fn parser_id(ty: &ArgType) -> String {
|
||||
ArgType::ItemPredicate => "minecraft:item_predicate".into(),
|
||||
ArgType::BlockState => "minecraft:block_state".into(),
|
||||
ArgType::BlockPredicate => "minecraft:block_predicate".into(),
|
||||
ArgType::Resource(r) => format!("resource:{r:?}"),
|
||||
ArgType::Id(n) | ArgType::Name(n) => format!("id:{n}"),
|
||||
ArgType::Resource(_) => "minecraft:resource".into(),
|
||||
ArgType::Id(_) => "minecraft:resource_location".into(),
|
||||
ArgType::Res(_) => "minecraft:resource".into(),
|
||||
ArgType::ResKey(_) => "minecraft:resource_key".into(),
|
||||
ArgType::ResOrTag(_) => "minecraft:resource_or_tag".into(),
|
||||
ArgType::ResOrTagKey(_) => "minecraft:resource_or_tag_key".into(),
|
||||
ArgType::StrEnum(values, _) => match values.first().copied() {
|
||||
Some("world_surface") => "minecraft:heightmap".into(),
|
||||
Some("none") if values.len() == 3 && values[1] == "left_right" => "minecraft:template_mirror".into(),
|
||||
Some("none") if values.len() == 3 => "minecraft:swing_animation".into(),
|
||||
_ => "minecraft:template_rotation".into(),
|
||||
},
|
||||
ArgType::HexColor => "minecraft:hex_color".into(),
|
||||
ArgType::Uuid => "minecraft:uuid".into(),
|
||||
ArgType::GameProfile => "minecraft:game_profile".into(),
|
||||
ArgType::Style => "minecraft:style".into(),
|
||||
ArgType::Name(_) => "brigadier:string".into(),
|
||||
ArgType::Time { .. } => "minecraft:time".into(),
|
||||
ArgType::GameMode => "minecraft:gamemode".into(),
|
||||
ArgType::Message => "minecraft:message".into(),
|
||||
@@ -74,6 +89,16 @@ fn parser_id(ty: &ArgType) -> String {
|
||||
ArgType::Function => "minecraft:function".into(),
|
||||
ArgType::Slots => "minecraft:slots".into(),
|
||||
ArgType::Slot => "minecraft:item_slot".into(),
|
||||
ArgType::SlotSource => "minecraft:slot_source".into(),
|
||||
ArgType::ResourceOrId(r) => match *r {
|
||||
"minecraft:loot_table" => "minecraft:loot_table".into(),
|
||||
"minecraft:item_modifier" => "minecraft:loot_modifier".into(),
|
||||
"minecraft:predicate" => "minecraft:loot_predicate".into(),
|
||||
"minecraft:context_int_provider" => "minecraft:context_int_provider".into(),
|
||||
"minecraft:context_float_provider" => "minecraft:context_float_provider".into(),
|
||||
"minecraft:dialog" => "minecraft:dialog".into(),
|
||||
_ => "minecraft:feature".into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +131,7 @@ fn tree(d: &Dispatcher, node: usize) -> Value {
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.get(1).map(String::as_str) == Some("tree") {
|
||||
let d = vanilla::dispatcher();
|
||||
let d = vanilla::release_dispatcher();
|
||||
let mut v = tree(d, 0);
|
||||
v["type"] = json!("root");
|
||||
fs::write(&args[2], v.to_string())?;
|
||||
@@ -152,7 +177,40 @@ fn main() -> horizon_client::Result<()> {
|
||||
reg.teams = strings(&r["teams"]);
|
||||
reg.objectives = strings(&r["objectives"]);
|
||||
reg.tracked = strings(&r["tracked"]);
|
||||
let dispatcher = vanilla::dispatcher();
|
||||
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
|
||||
reg.by_registry.insert(
|
||||
name.clone(),
|
||||
RegistryIds {
|
||||
ids: strings(&entry["ids"]),
|
||||
tags: strings(&entry["tags"]),
|
||||
},
|
||||
);
|
||||
}
|
||||
reg.block_entities = strings(&r["block_entities"]).into_iter().collect();
|
||||
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
|
||||
reg.block_tag_members.insert(tag.clone(), strings(members));
|
||||
}
|
||||
reg.templates = strings(&r["templates"]);
|
||||
reg.persistent_components = strings(&r["persistent_components"]);
|
||||
reg.learnable_recipes = strings(&r["learnable_recipes"]);
|
||||
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
|
||||
reg.clock_time_markers.insert(clock.clone(), strings(markers));
|
||||
}
|
||||
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
|
||||
reg.advancement_criteria.insert(id.clone(), strings(criteria));
|
||||
}
|
||||
reg.datapacks_enabled = strings(&r["datapacks_selected"]);
|
||||
let enabled = reg.datapacks_enabled.clone();
|
||||
reg.datapacks_disabled = strings(&r["datapacks_enableable"])
|
||||
.into_iter()
|
||||
.filter(|p| !enabled.contains(p))
|
||||
.collect();
|
||||
reg.advancements = reg.ids("minecraft:advancement").to_vec();
|
||||
reg.recipes = reg.ids("minecraft:recipe").to_vec();
|
||||
reg.loot_tables = reg.ids("minecraft:loot_table").to_vec();
|
||||
reg.predicates = reg.ids("minecraft:predicate").to_vec();
|
||||
reg.item_modifiers = reg.ids("minecraft:item_modifier").to_vec();
|
||||
let dispatcher = vanilla::release_dispatcher();
|
||||
let mut out = String::new();
|
||||
for input in fs::read_to_string(&args[3])?.lines() {
|
||||
let parse = dispatcher.parse(input, ®);
|
||||
@@ -173,7 +231,8 @@ fn main() -> horizon_client::Result<()> {
|
||||
Err(e) => json!({
|
||||
"ok": false,
|
||||
"error": e.message.plain(),
|
||||
"cursor": utf16(input, if e.input.is_some() { e.cursor } else { parse.cursor }),
|
||||
// CommandSyntaxException.getCursor is -1 without context.
|
||||
"cursor": if e.input.is_some() { utf16(input, e.cursor) as i64 } else { -1 },
|
||||
}),
|
||||
};
|
||||
let (range, list) = dispatcher.suggestions(&parse, input.len(), ®);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,463 @@
|
||||
//! BlockStateParser: block states (`stone`, `oak_stairs[facing=up]{...}`)
|
||||
//! and block predicates (`#logs[axis=y]`), with vanilla's suggestions.
|
||||
use super::args::{BlockInput, Registries, read_identifier, suggest_resources};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Sugg {
|
||||
Nothing,
|
||||
Item,
|
||||
BlockIdOrTag,
|
||||
Tag,
|
||||
OpenVaguePropertiesOrNbt,
|
||||
OpenNbt,
|
||||
OpenPropertiesOrNbt,
|
||||
PropertyNameOrEnd,
|
||||
VaguePropertyNameOrEnd,
|
||||
PropertyName,
|
||||
VaguePropertyName,
|
||||
Equals,
|
||||
PropertyValues(String),
|
||||
NextPropertyOrEnd,
|
||||
VaguePropertyValue(String),
|
||||
}
|
||||
|
||||
type Props = Vec<(String, Vec<String>)>;
|
||||
|
||||
pub struct BlockParser<'r, 'a> {
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
for_testing: bool,
|
||||
allow_nbt: bool,
|
||||
id: String,
|
||||
/// The block's state definition (properties and values).
|
||||
definition: Option<&'r Props>,
|
||||
properties: Vec<(String, String)>,
|
||||
vague: Vec<(String, String)>,
|
||||
tag: Option<String>,
|
||||
nbt: Option<String>,
|
||||
sugg: Sugg,
|
||||
}
|
||||
|
||||
fn is_int_property(values: &[String]) -> bool {
|
||||
!values.is_empty() && values.iter().all(|v| v.parse::<i32>().is_ok())
|
||||
}
|
||||
/// Property.getValue.
|
||||
fn property_value(values: &[String], raw: &str) -> Option<String> {
|
||||
if is_int_property(values) {
|
||||
let v: i32 = super::args::java_parse_int(raw)?;
|
||||
let s = v.to_string();
|
||||
return values.contains(&s).then_some(s);
|
||||
}
|
||||
values.iter().any(|v| v == raw).then(|| raw.to_owned())
|
||||
}
|
||||
/// addSuggestions: every value (integers as integer suggestions).
|
||||
fn add_values(builder: &mut SuggestionsBuilder, values: &[String]) {
|
||||
let ints = is_int_property(values);
|
||||
for v in values {
|
||||
if ints {
|
||||
builder.suggest_int(v.parse().unwrap_or(0));
|
||||
} else {
|
||||
builder.suggest(v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r, 'a> BlockParser<'r, 'a> {
|
||||
pub fn new(
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
for_testing: bool,
|
||||
allow_nbt: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
reader,
|
||||
reg,
|
||||
for_testing,
|
||||
allow_nbt,
|
||||
id: "minecraft:".into(),
|
||||
definition: None,
|
||||
properties: Vec::new(),
|
||||
vague: Vec::new(),
|
||||
tag: None,
|
||||
nbt: None,
|
||||
sugg: Sugg::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_members(&self) -> &'r [String] {
|
||||
match &self.tag {
|
||||
Some(t) => self
|
||||
.reg
|
||||
.block_tag_members
|
||||
.get(t)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]),
|
||||
None => &[],
|
||||
}
|
||||
}
|
||||
fn block_props(&self, id: &str) -> &'r [(String, Vec<String>)] {
|
||||
self.reg.blocks.get(id).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn parse(&mut self) -> CmdResult<BlockInput> {
|
||||
self.sugg = if self.for_testing {
|
||||
Sugg::BlockIdOrTag
|
||||
} else {
|
||||
Sugg::Item
|
||||
};
|
||||
if self.reader.can_read() && self.reader.peek() == '#' {
|
||||
self.read_tag()?;
|
||||
self.sugg = Sugg::OpenVaguePropertiesOrNbt;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.read_vague_properties()?;
|
||||
self.sugg = Sugg::OpenNbt;
|
||||
}
|
||||
} else {
|
||||
self.read_block()?;
|
||||
self.sugg = Sugg::OpenPropertiesOrNbt;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.read_properties()?;
|
||||
self.sugg = Sugg::OpenNbt;
|
||||
}
|
||||
}
|
||||
if self.allow_nbt && self.reader.can_read() && self.reader.peek() == '{' {
|
||||
self.sugg = Sugg::Nothing;
|
||||
let start = self.reader.cursor;
|
||||
super::snbt::parse_compound_argument(self.reader)?;
|
||||
self.nbt = Some(self.reader.string[start..self.reader.cursor].to_owned());
|
||||
}
|
||||
let (id, properties) = match &self.tag {
|
||||
Some(t) => (t.clone(), self.vague.clone()),
|
||||
None => (self.id.clone(), self.properties.clone()),
|
||||
};
|
||||
Ok(BlockInput {
|
||||
id,
|
||||
properties,
|
||||
tag: self.tag.is_some(),
|
||||
nbt: self.nbt.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_block(&mut self) -> CmdResult<()> {
|
||||
let start = self.reader.cursor;
|
||||
self.id = read_identifier(self.reader)?;
|
||||
match self.reg.blocks.get(&self.id) {
|
||||
Some(props) => {
|
||||
self.definition = Some(props);
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
self.reader.cursor = start;
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.id.invalid",
|
||||
&[&self.id],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_tag(&mut self) -> CmdResult<()> {
|
||||
if !self.for_testing {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.tag.disallowed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
self.reader.expect('#')?;
|
||||
self.sugg = Sugg::Tag;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.reg.tags("minecraft:block").contains(&id) {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.block.tag.unknown",
|
||||
&[&id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.tag = Some(id);
|
||||
Ok(())
|
||||
}
|
||||
fn read_properties(&mut self) -> CmdResult<()> {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::PropertyNameOrEnd;
|
||||
self.reader.skip_whitespace();
|
||||
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let key_start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
let Some((_, values)) = definition.iter().find(|(n, _)| *n == key) else {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unknown",
|
||||
&[&self.id, &key],
|
||||
self.reader,
|
||||
));
|
||||
};
|
||||
if self.properties.iter().any(|(n, _)| *n == key) {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.duplicate",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::Equals;
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.novalue",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::PropertyValues(key.clone());
|
||||
let start = self.reader.cursor;
|
||||
let raw = self.reader.read_string()?;
|
||||
match property_value(values, &raw) {
|
||||
Some(v) => self.properties.push((key, v)),
|
||||
None => {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.invalid",
|
||||
&[&self.id, &raw, &key],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.sugg = Sugg::NextPropertyOrEnd;
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() {
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::PropertyName;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
fn read_vague_properties(&mut self) -> CmdResult<()> {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::VaguePropertyNameOrEnd;
|
||||
let mut value_start: Option<usize> = None;
|
||||
self.reader.skip_whitespace();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let key_start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
if self.vague.iter().any(|(n, _)| *n == key) {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.duplicate",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
self.reader.cursor = key_start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.novalue",
|
||||
&[&key, &self.id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::VaguePropertyValue(key.clone());
|
||||
value_start = Some(self.reader.cursor);
|
||||
let value = self.reader.read_string()?;
|
||||
self.vague.push((key, value));
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() {
|
||||
value_start = None;
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::VaguePropertyName;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
Ok(())
|
||||
} else {
|
||||
if let Some(v) = value_start {
|
||||
self.reader.cursor = v;
|
||||
}
|
||||
Err(CommandError::tr_at(
|
||||
"argument.block.property.unclosed",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn has_block_entity(&self) -> bool {
|
||||
if self.tag.is_none() {
|
||||
return self.reg.block_entities.contains(&self.id);
|
||||
}
|
||||
self.tag_members()
|
||||
.iter()
|
||||
.any(|b| self.reg.block_entities.contains(b))
|
||||
}
|
||||
|
||||
pub fn fill_suggestions(&self, builder: &mut SuggestionsBuilder) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
let empty = b.remaining().is_empty();
|
||||
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
|
||||
match &self.sugg {
|
||||
Sugg::Nothing => {}
|
||||
Sugg::Item => {
|
||||
let ids: Vec<&String> = self.reg.blocks.keys().collect();
|
||||
suggest_resources(&mut b, ids, "");
|
||||
}
|
||||
Sugg::Tag => suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#"),
|
||||
Sugg::BlockIdOrTag => {
|
||||
suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#");
|
||||
let ids: Vec<&String> = self.reg.blocks.keys().collect();
|
||||
suggest_resources(&mut b, ids, "");
|
||||
}
|
||||
Sugg::OpenVaguePropertiesOrNbt => {
|
||||
if empty && self.tag.is_some() {
|
||||
let members = self.tag_members();
|
||||
if members.iter().any(|m| !self.block_props(m).is_empty()) {
|
||||
b.suggest("[");
|
||||
}
|
||||
if members.iter().any(|m| self.reg.block_entities.contains(m)) {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::OpenNbt => {
|
||||
if empty && self.has_block_entity() {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
Sugg::OpenPropertiesOrNbt => {
|
||||
if empty {
|
||||
if !definition.is_empty() {
|
||||
b.suggest("[");
|
||||
}
|
||||
if self.reg.block_entities.contains(&self.id) {
|
||||
b.suggest("{");
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::PropertyNameOrEnd | Sugg::PropertyName => {
|
||||
if matches!(self.sugg, Sugg::PropertyNameOrEnd) && empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
let prefix = b.remaining_lower();
|
||||
for (name, _) in definition {
|
||||
if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) {
|
||||
b.suggest(format!("{name}="));
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::VaguePropertyNameOrEnd | Sugg::VaguePropertyName => {
|
||||
if matches!(self.sugg, Sugg::VaguePropertyNameOrEnd) && empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
let prefix = b.remaining_lower();
|
||||
for m in self.tag_members() {
|
||||
for (name, _) in self.block_props(m) {
|
||||
if !self.vague.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) {
|
||||
b.suggest(format!("{name}="));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::Equals => {
|
||||
if empty {
|
||||
b.suggest("=");
|
||||
}
|
||||
}
|
||||
Sugg::PropertyValues(key) => {
|
||||
if let Some((_, values)) = definition.iter().find(|(n, _)| n == key) {
|
||||
add_values(&mut b, values);
|
||||
}
|
||||
}
|
||||
Sugg::NextPropertyOrEnd => {
|
||||
if empty {
|
||||
b.suggest("]");
|
||||
}
|
||||
if empty && self.properties.len() < definition.len() {
|
||||
b.suggest(",");
|
||||
}
|
||||
}
|
||||
Sugg::VaguePropertyValue(key) => {
|
||||
let mut more = false;
|
||||
for m in self.tag_members() {
|
||||
let props = self.block_props(m);
|
||||
if let Some((_, values)) = props.iter().find(|(n, _)| n == key) {
|
||||
add_values(&mut b, values);
|
||||
}
|
||||
if !more {
|
||||
more = props
|
||||
.iter()
|
||||
.any(|(n, _)| !self.vague.iter().any(|(v, _)| v == n));
|
||||
}
|
||||
}
|
||||
if more {
|
||||
b.suggest(",");
|
||||
}
|
||||
b.suggest("]");
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// BlockStateParser.parseForBlock / parseForTesting (the reader is rewound on errors).
|
||||
pub fn parse(
|
||||
reader: &mut Reader,
|
||||
reg: &Registries,
|
||||
for_testing: bool,
|
||||
) -> CmdResult<BlockInput> {
|
||||
let cursor = reader.cursor;
|
||||
let r = BlockParser::new(reader, reg, for_testing, true).parse();
|
||||
if r.is_err() {
|
||||
reader.cursor = cursor;
|
||||
}
|
||||
r
|
||||
}
|
||||
/// BlockStateParser.fillSuggestions.
|
||||
pub fn suggest(builder: &mut SuggestionsBuilder, reg: &Registries, for_testing: bool) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut parser = BlockParser::new(&mut reader, reg, for_testing, true);
|
||||
let _ = parser.parse();
|
||||
parser.fill_suggestions(builder);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! ResourceOrIdArgument and the data-fixer-upper decoding of inline values
|
||||
//! commands accept (loot predicates, item modifiers, slot sources, context
|
||||
//! providers, dialogs), reproducing the codec error messages vanilla reports.
|
||||
use super::args::{Registries, is_id_char, parse_identifier};
|
||||
use super::{CmdResult, CommandError, Reader};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
|
||||
pub fn snbt(t: &Tag) -> String {
|
||||
crate::snbt::to_snbt(t)
|
||||
}
|
||||
pub fn not_map(t: &Tag) -> String {
|
||||
format!("Not a map: {}", snbt(t))
|
||||
}
|
||||
pub fn not_list(t: &Tag) -> String {
|
||||
format!("Not a list: {}", snbt(t))
|
||||
}
|
||||
pub fn no_key(key: &str, t: &Tag) -> String {
|
||||
format!("No key {key} in MapLike[{}]", snbt(t))
|
||||
}
|
||||
pub fn either(a: String, b: String) -> String {
|
||||
format!("Failed to parse either. First: {a}; Second: {b}")
|
||||
}
|
||||
pub fn get<'t>(map: &'t Compound, key: &str) -> Option<&'t Tag> {
|
||||
map.get(&JavaString::from(key))
|
||||
}
|
||||
pub fn is_number(t: &Tag) -> bool {
|
||||
matches!(
|
||||
t,
|
||||
Tag::Byte(_) | Tag::Short(_) | Tag::Int(_) | Tag::Long(_) | Tag::Float(_) | Tag::Double(_)
|
||||
)
|
||||
}
|
||||
pub fn as_string(t: &Tag) -> Option<String> {
|
||||
match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// KeyDispatchCodec over a type registry: the map, its `type` and the
|
||||
/// type's own fields (`fields` checks them).
|
||||
fn dispatch(
|
||||
t: &Tag,
|
||||
reg: &Registries,
|
||||
type_registry: &str,
|
||||
fields: &dyn Fn(&str, &Compound, &Tag) -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
let Tag::Compound(map) = t else {
|
||||
return Err(not_map(t));
|
||||
};
|
||||
let Some(ty) = get(map, "type") else {
|
||||
return Err(no_key("type", t));
|
||||
};
|
||||
let Some(name) = as_string(ty) else {
|
||||
return Err("Not a string".into());
|
||||
};
|
||||
let Some(id) = parse_identifier(&name) else {
|
||||
return Err(format!("Not a valid resource location: {name}"));
|
||||
};
|
||||
let known = reg.ids(type_registry);
|
||||
if !known.is_empty() && !known.contains(&id) {
|
||||
return Err(format!(
|
||||
"Unknown registry key in ResourceKey[minecraft:root / {type_registry}]: {id}"
|
||||
));
|
||||
}
|
||||
fields(&id, map, t)
|
||||
}
|
||||
/// Required fields, reported in vanilla's order when missing.
|
||||
fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> {
|
||||
let missing: Vec<String> = keys
|
||||
.iter()
|
||||
.filter(|k| get(map, k).is_none())
|
||||
.map(|k| no_key(k, t))
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(missing.join("; "))
|
||||
}
|
||||
}
|
||||
fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:uniform" => require(map, t, &["max", "min"]),
|
||||
"minecraft:constant" => require(map, t, &["value"]),
|
||||
"minecraft:binomial" => require(map, t, &["n", "p"]),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// A holder list codec: a single element, a `#tag`, or a list.
|
||||
fn element_or_list(
|
||||
t: &Tag,
|
||||
element: &dyn Fn(&Tag) -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
let first = match element(t) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let tag_ref = match as_string(t) {
|
||||
Some(s) if s.starts_with('#') => return Ok(()),
|
||||
Some(_) => "Not a tag id".to_owned(),
|
||||
None => "Not a string".to_owned(),
|
||||
};
|
||||
let list = match t {
|
||||
Tag::List(items) => {
|
||||
let errors: Vec<String> = items.iter().filter_map(|i| element(i).err()).collect();
|
||||
if errors.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
errors.join("; ")
|
||||
}
|
||||
_ => not_list(t),
|
||||
};
|
||||
let last = element(t).err().unwrap_or_default();
|
||||
Err(either(first, either(tag_ref, either(list, last))))
|
||||
}
|
||||
|
||||
/// Decode an inline value of a ResourceOrIdArgument registry.
|
||||
pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> {
|
||||
match registry {
|
||||
"minecraft:context_int_provider" | "minecraft:context_float_provider" => {
|
||||
if is_number(t) {
|
||||
return Ok(());
|
||||
}
|
||||
let ty = format!("{registry}_type");
|
||||
let second = dispatch(t, reg, &ty, &provider_fields);
|
||||
second.map_err(|e| either("Not a number".into(), e))
|
||||
}
|
||||
"minecraft:predicate" => {
|
||||
dispatch(t, reg, "minecraft:loot_condition_type", &|_, _, _| Ok(()))
|
||||
}
|
||||
"minecraft:item_modifier" => element_or_list(t, &|x| {
|
||||
dispatch(x, reg, "minecraft:loot_function_type", &|_, _, _| Ok(()))
|
||||
}),
|
||||
"minecraft:slot_source" => element_or_list(t, &|x| {
|
||||
dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(()))
|
||||
}),
|
||||
"minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|_, _, _| Ok(())),
|
||||
"minecraft:worldgen/feature" | "minecraft:loot_table" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifier.readNonEmpty (None when empty or invalid).
|
||||
fn read_non_empty(reader: &mut Reader) -> Option<String> {
|
||||
let start = reader.cursor;
|
||||
while reader.can_read() && is_id_char(reader.peek()) {
|
||||
reader.skip();
|
||||
}
|
||||
let raw = &reader.string[start..reader.cursor];
|
||||
let id = if raw.is_empty() {
|
||||
None
|
||||
} else {
|
||||
parse_identifier(raw)
|
||||
};
|
||||
if id.is_none() {
|
||||
reader.cursor = start;
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// ResourceOrIdArgument.parse: a registry id (checked) or an inline SNBT
|
||||
/// value decoded with the registry's codec.
|
||||
pub fn resource_or_id(reader: &mut Reader, reg: &Registries, registry: &str) -> CmdResult<()> {
|
||||
let start = reader.cursor;
|
||||
let mut r = reader.clone();
|
||||
r.skip_whitespace();
|
||||
if let Some(id) = read_non_empty(&mut r) {
|
||||
reader.cursor = r.cursor;
|
||||
if !reg.ids(registry).contains(&id) {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.resource_or_id.no_such_element",
|
||||
&[&id, ®istry],
|
||||
reader,
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
reader.cursor = start;
|
||||
let tag = super::snbt::parse_tag_argument(reader)?;
|
||||
decode(registry, &tag, reg).map_err(|m| {
|
||||
CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of
|
||||
//! SNBT text components, with the data-fixer-upper error messages
|
||||
//! (ComponentArgument, StyleArgument and component-valued item data).
|
||||
use super::codec::{get, no_key, not_list, not_map, snbt};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
/// A DataResult error: its message and whether it carries a partial result.
|
||||
struct E {
|
||||
msg: String,
|
||||
partial: bool,
|
||||
}
|
||||
type R = Result<(), E>;
|
||||
fn err(msg: impl Into<String>) -> R {
|
||||
Err(E {
|
||||
msg: msg.into(),
|
||||
partial: false,
|
||||
})
|
||||
}
|
||||
fn partial(msg: impl Into<String>) -> R {
|
||||
Err(E {
|
||||
msg: msg.into(),
|
||||
partial: true,
|
||||
})
|
||||
}
|
||||
/// Codec.either.
|
||||
fn either(first: R, second: impl FnOnce() -> R) -> R {
|
||||
let a = match first {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let b = match second() {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if a.partial {
|
||||
return Err(a);
|
||||
}
|
||||
if b.partial {
|
||||
return Err(b);
|
||||
}
|
||||
err(format!(
|
||||
"Failed to parse either. First: {}; Second: {}",
|
||||
a.msg, b.msg
|
||||
))
|
||||
}
|
||||
fn is_string(t: &Tag) -> bool {
|
||||
matches!(t, Tag::String(_))
|
||||
}
|
||||
fn string(t: &Tag) -> R {
|
||||
if is_string(t) { Ok(()) } else { err("Not a string") }
|
||||
}
|
||||
fn string_of(t: &Tag) -> Option<String> {
|
||||
match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// ListCodec: element errors (newest first) with the decoded rest as partial.
|
||||
fn list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> Result<usize, E> {
|
||||
let Tag::List(items) = t else {
|
||||
return Err(E {
|
||||
msg: not_list(t),
|
||||
partial: false,
|
||||
});
|
||||
};
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
let mut ok = 0;
|
||||
for i in items {
|
||||
match element(i) {
|
||||
Ok(()) => ok += 1,
|
||||
Err(e) => {
|
||||
if e.partial {
|
||||
ok += 1;
|
||||
}
|
||||
errors.push(e.msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
return Ok(ok);
|
||||
}
|
||||
errors.reverse();
|
||||
Err(E {
|
||||
msg: errors.join("; "),
|
||||
partial: true,
|
||||
})
|
||||
}
|
||||
/// ExtraCodecs.nonEmptyList(listOf(element)).
|
||||
fn non_empty_list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> R {
|
||||
match list(t, element) {
|
||||
Ok(0) => err("List must have contents"),
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) if !e.partial => Err(e),
|
||||
Err(e) => {
|
||||
// The partial result is validated too.
|
||||
let decoded = match t {
|
||||
Tag::List(items) => items.iter().filter(|i| element(i).is_ok()).count(),
|
||||
_ => 0,
|
||||
};
|
||||
if decoded == 0 {
|
||||
err(format!("{}; List must have contents", e.msg))
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bool_value(t: &Tag) -> R {
|
||||
if super::codec::is_number(t) {
|
||||
Ok(())
|
||||
} else {
|
||||
err("Not a number")
|
||||
}
|
||||
}
|
||||
/// Identifier.CODEC.
|
||||
pub fn identifier(t: &Tag) -> Result<(), String> {
|
||||
let Some(s) = string_of(t) else {
|
||||
return Err("Not a string".into());
|
||||
};
|
||||
let (ns, path) = match s.split_once(':') {
|
||||
Some(("", p)) => ("minecraft".to_owned(), p.to_owned()),
|
||||
Some((n, p)) => (n.to_owned(), p.to_owned()),
|
||||
None => ("minecraft".to_owned(), s.clone()),
|
||||
};
|
||||
let ns_ok = ns != ".."
|
||||
&& ns
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
|
||||
if !ns_ok {
|
||||
return Err(format!(
|
||||
"Not a valid resource location: {s} Non [a-z0-9_.-] character in namespace of location: {ns}:{path}"
|
||||
));
|
||||
}
|
||||
let path_ok = path
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/'));
|
||||
if !path_ok {
|
||||
return Err(format!(
|
||||
"Not a valid resource location: {s} Non [a-z0-9/._-] character in path of location: {ns}:{path}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// TextColor.CODEC.
|
||||
fn color(t: &Tag) -> R {
|
||||
let Some(s) = string_of(t) else {
|
||||
return partial("Not a string");
|
||||
};
|
||||
if let Some(hex) = s.strip_prefix('#') {
|
||||
let digits = hex.strip_prefix(['+', '-']).unwrap_or(hex);
|
||||
let valid = !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit());
|
||||
return match i64::from_str_radix(hex, 16) {
|
||||
Ok(v) if valid && i32::try_from(v).is_ok() => {
|
||||
if (0..=0xFF_FFFF).contains(&v) {
|
||||
Ok(())
|
||||
} else {
|
||||
partial(format!("Color value out of range: {s}"))
|
||||
}
|
||||
}
|
||||
_ => partial(format!("Invalid color value: {s}")),
|
||||
};
|
||||
}
|
||||
if crate::text::named_color(&s).is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
partial(format!("Invalid color name: {s}"))
|
||||
}
|
||||
}
|
||||
/// A KeyDispatch over an action enum (`Unknown element name:`), with
|
||||
/// required fields per action.
|
||||
fn action_event(t: &Tag, actions: &[(&str, &[&str])]) -> R {
|
||||
let Tag::Compound(map) = t else {
|
||||
return partial(not_map(t));
|
||||
};
|
||||
let Some(action) = get(map, "action") else {
|
||||
return partial(no_key("action", t));
|
||||
};
|
||||
let Some(name) = string_of(action) else {
|
||||
return partial("Not a string");
|
||||
};
|
||||
let Some((_, fields)) = actions.iter().find(|(a, _)| *a == name) else {
|
||||
return partial(format!("Unknown element name:{name}"));
|
||||
};
|
||||
for f in *fields {
|
||||
if get(map, f).is_none() {
|
||||
return partial(no_key(f, t));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
const CLICK_ACTIONS: &[(&str, &[&str])] = &[
|
||||
("open_url", &["url"]),
|
||||
("open_file", &["path"]),
|
||||
("run_command", &["command"]),
|
||||
("suggest_command", &["command"]),
|
||||
("show_dialog", &["dialog"]),
|
||||
("change_page", &["page"]),
|
||||
("copy_to_clipboard", &["value"]),
|
||||
("custom", &["id"]),
|
||||
];
|
||||
const HOVER_ACTIONS: &[(&str, &[&str])] = &[
|
||||
("show_text", &["value"]),
|
||||
("show_item", &["id"]),
|
||||
("show_entity", &["id", "uuid"]),
|
||||
];
|
||||
/// Style.Serializer.MAP_CODEC (every field optional; errors keep a partial style).
|
||||
fn style_fields(map: &Compound) -> R {
|
||||
if let Some(c) = get(map, "color") {
|
||||
color(c)?;
|
||||
}
|
||||
for key in ["bold", "italic", "underlined", "strikethrough", "obfuscated"] {
|
||||
if let Some(v) = get(map, key)
|
||||
&& bool_value(v).is_err()
|
||||
{
|
||||
return partial("Not a number");
|
||||
}
|
||||
}
|
||||
if let Some(v) = get(map, "click_event") {
|
||||
action_event(v, CLICK_ACTIONS)?;
|
||||
}
|
||||
if let Some(v) = get(map, "hover_event") {
|
||||
action_event(v, HOVER_ACTIONS)?;
|
||||
}
|
||||
if let Some(v) = get(map, "insertion")
|
||||
&& !is_string(v)
|
||||
{
|
||||
return partial("Not a string");
|
||||
}
|
||||
if let Some(v) = get(map, "font")
|
||||
&& let Err(m) = identifier(v)
|
||||
{
|
||||
return partial(m);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn selector_string(t: &Tag) -> bool {
|
||||
let Some(s) = string_of(t) else { return false };
|
||||
let reg = super::args::Registries {
|
||||
permission: 4,
|
||||
..Default::default()
|
||||
};
|
||||
let mut r = super::Reader::new(&s);
|
||||
super::selector::parse(&mut r, ®, true).is_ok() && !r.can_read()
|
||||
}
|
||||
fn optional_component(map: &Compound, key: &str) -> bool {
|
||||
get(map, key).is_none_or(|v| component(v).is_ok())
|
||||
}
|
||||
/// The content codecs (PlainText, Translatable, Keybind, Score, Selector, Nbt, Object).
|
||||
fn content(kind: &str, map: &Compound) -> bool {
|
||||
match kind {
|
||||
"text" => get(map, "text").is_some_and(is_string),
|
||||
"translatable" => {
|
||||
get(map, "translate").is_some_and(is_string)
|
||||
&& get(map, "fallback").is_none_or(is_string)
|
||||
&& get(map, "with").is_none_or(|w| matches!(w, Tag::List(_)))
|
||||
}
|
||||
"keybind" => get(map, "keybind").is_some_and(is_string),
|
||||
"score" => match get(map, "score") {
|
||||
Some(Tag::Compound(s)) => {
|
||||
get(s, "name").is_some_and(is_string) && get(s, "objective").is_some_and(is_string)
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
"selector" => {
|
||||
get(map, "selector").is_some_and(selector_string) && optional_component(map, "separator")
|
||||
}
|
||||
"nbt" => {
|
||||
let path_ok = get(map, "nbt").and_then(string_of).is_some_and(|p| {
|
||||
crate::nbt_path::NbtPath::parse(&p).is_ok()
|
||||
});
|
||||
let source = if let Some(e) = get(map, "entity") {
|
||||
selector_string(e)
|
||||
} else if let Some(b) = get(map, "block") {
|
||||
string_of(b).is_some_and(|s| {
|
||||
let reg = super::args::Registries::default();
|
||||
let mut r = super::Reader::new(&s);
|
||||
super::ArgType::BlockPos.parse(&mut r, ®).is_ok() && !r.can_read()
|
||||
})
|
||||
} else if let Some(s) = get(map, "storage") {
|
||||
identifier(s).is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
path_ok && source && optional_component(map, "separator")
|
||||
}
|
||||
"object" => {
|
||||
let kind = get(map, "object").and_then(string_of);
|
||||
let atlas = || {
|
||||
get(map, "sprite").is_some_and(|s| identifier(s).is_ok())
|
||||
&& get(map, "atlas").is_none_or(|a| identifier(a).is_ok())
|
||||
};
|
||||
let player = || get(map, "player").is_some();
|
||||
match kind.as_deref() {
|
||||
Some("atlas") => atlas(),
|
||||
Some("player") => player(),
|
||||
Some(_) => false,
|
||||
None => atlas() || player(),
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
const CONTENT_TYPES: [&str; 7] = [
|
||||
"text",
|
||||
"translatable",
|
||||
"keybind",
|
||||
"score",
|
||||
"selector",
|
||||
"nbt",
|
||||
"object",
|
||||
];
|
||||
fn full(t: &Tag) -> R {
|
||||
let Tag::Compound(map) = t else {
|
||||
return err(not_map(t));
|
||||
};
|
||||
let contents_ok = if let Some(ty) = get(map, "type") {
|
||||
let Some(name) = string_of(ty) else {
|
||||
return err("Not a string");
|
||||
};
|
||||
if !CONTENT_TYPES.contains(&name.as_str()) {
|
||||
return err(format!("Unknown element id: {name}"));
|
||||
}
|
||||
content(&name, map)
|
||||
} else {
|
||||
CONTENT_TYPES.iter().any(|k| content(k, map))
|
||||
};
|
||||
if !contents_ok {
|
||||
return err("No matching codec found");
|
||||
}
|
||||
if let Some(extra) = get(map, "extra") {
|
||||
match non_empty_list(extra, &component) {
|
||||
Ok(()) => {}
|
||||
Err(e) => return partial(e.msg),
|
||||
}
|
||||
}
|
||||
style_fields(map)
|
||||
}
|
||||
fn component(t: &Tag) -> R {
|
||||
either(
|
||||
either(string(t), || non_empty_list(t, &component)),
|
||||
|| full(t),
|
||||
)
|
||||
}
|
||||
/// ComponentSerialization.CODEC.parse: the error message on failure.
|
||||
pub fn decode(t: &Tag) -> Result<(), String> {
|
||||
component(t).map_err(|e| e.msg)
|
||||
}
|
||||
/// Style.Serializer.CODEC.parse.
|
||||
pub fn decode_style(t: &Tag) -> Result<(), String> {
|
||||
match t {
|
||||
Tag::Compound(map) => style_fields(map).map_err(|e| e.msg),
|
||||
_ => Err(not_map(t)),
|
||||
}
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _keep(t: &Tag) -> String {
|
||||
snbt(t)
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
//! ItemParser (item stacks with components, `stone[damage=5]`) and
|
||||
//! ItemPredicateArgument (ComponentPredicateParser's packrat grammar:
|
||||
//! `#logs[count~1..|!damage]`), with vanilla's errors and suggestions.
|
||||
use super::args::{ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources};
|
||||
use super::codec::{either, is_number, not_map, snbt};
|
||||
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, opt, seq};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::rc::Rc;
|
||||
|
||||
fn int_of(t: &Tag) -> Option<i64> {
|
||||
Some(match t {
|
||||
Tag::Byte(v) => i64::from(*v),
|
||||
Tag::Short(v) => i64::from(*v),
|
||||
Tag::Int(v) => i64::from(*v),
|
||||
Tag::Long(v) => *v as i32 as i64,
|
||||
Tag::Float(v) => f32::from_bits(*v) as i32 as i64,
|
||||
Tag::Double(v) => f64::from_bits(*v) as i32 as i64,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// The codecs of the item components commands commonly set.
|
||||
pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:damage" | "minecraft:repair_cost" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if v < 0 {
|
||||
return Err(format!("Value must be non-negative: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:max_damage" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if v <= 0 {
|
||||
return Err(format!("Value must be positive: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:max_stack_size" => {
|
||||
let v = int_of(t).ok_or("Not a number")?;
|
||||
if !(1..=99).contains(&v) {
|
||||
return Err(format!("Value must be within range [1;99]: {v}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"minecraft:rarity" => match t {
|
||||
Tag::String(s) => {
|
||||
let s = s.to_string_lossy();
|
||||
if ["common", "uncommon", "rare", "epic"].contains(&s.as_str()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Unknown element name:{s}"))
|
||||
}
|
||||
}
|
||||
_ => Err("Not a string".into()),
|
||||
},
|
||||
"minecraft:enchantments" | "minecraft:stored_enchantments" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
"minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
/// MinMaxBounds.Ints.CODEC.
|
||||
fn int_bounds(t: &Tag) -> Result<(), String> {
|
||||
match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ if is_number(t) => Ok(()),
|
||||
_ => Err(either(not_map(t), "Not a number".into())),
|
||||
}
|
||||
}
|
||||
/// DataComponentPredicate type codecs.
|
||||
pub fn decode_predicate(id: &str, t: &Tag) -> Result<(), String> {
|
||||
match id {
|
||||
"minecraft:count" => int_bounds(t),
|
||||
"minecraft:damage" => match t {
|
||||
Tag::Compound(_) => Ok(()),
|
||||
_ => Err(not_map(t)),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ItemParser -------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ISugg {
|
||||
Nothing,
|
||||
Item,
|
||||
StartComponents,
|
||||
ComponentAssignmentOrRemoval,
|
||||
Component,
|
||||
Assignment,
|
||||
NextOrEndComponents,
|
||||
}
|
||||
|
||||
struct ItemState<'r, 'a> {
|
||||
reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
sugg: ISugg,
|
||||
}
|
||||
impl ItemState<'_, '_> {
|
||||
fn parse(&mut self) -> CmdResult<ItemInput> {
|
||||
self.sugg = ISugg::Item;
|
||||
let cursor = self.reader.cursor;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.reg.ids("minecraft:item").contains(&id) {
|
||||
self.reader.cursor = cursor;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.item.id.invalid",
|
||||
&[&id],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.sugg = ISugg::StartComponents;
|
||||
let mut components = None;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.sugg = ISugg::Nothing;
|
||||
let start = self.reader.cursor;
|
||||
self.read_components()?;
|
||||
components = Some(self.reader.string[start..self.reader.cursor].to_owned());
|
||||
}
|
||||
Ok(ItemInput {
|
||||
id,
|
||||
tag: false,
|
||||
any: false,
|
||||
components,
|
||||
})
|
||||
}
|
||||
fn component_type(&mut self) -> CmdResult<String> {
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.expected",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let cursor = self.reader.cursor;
|
||||
let id = read_identifier(self.reader)?;
|
||||
if self.reg.persistent_components.contains(&id) {
|
||||
return Ok(id);
|
||||
}
|
||||
self.reader.cursor = cursor;
|
||||
Err(CommandError::tr_at(
|
||||
"arguments.item.component.unknown",
|
||||
&[&id],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
fn read_components(&mut self) -> CmdResult<()> {
|
||||
self.reader.expect('[')?;
|
||||
self.sugg = ISugg::ComponentAssignmentOrRemoval;
|
||||
let mut visited: Vec<String> = Vec::new();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '!' {
|
||||
self.reader.skip();
|
||||
self.sugg = ISugg::Component;
|
||||
let ty = self.component_type()?;
|
||||
if visited.contains(&ty) {
|
||||
return Err(CommandError::tr("arguments.item.component.repeated", &[&ty]));
|
||||
}
|
||||
visited.push(ty);
|
||||
self.sugg = ISugg::Nothing;
|
||||
self.reader.skip_whitespace();
|
||||
} else {
|
||||
let ty = self.component_type()?;
|
||||
if visited.contains(&ty) {
|
||||
return Err(CommandError::tr("arguments.item.component.repeated", &[&ty]));
|
||||
}
|
||||
visited.push(ty.clone());
|
||||
self.sugg = ISugg::Assignment;
|
||||
self.reader.skip_whitespace();
|
||||
self.reader.expect('=')?;
|
||||
self.sugg = ISugg::Nothing;
|
||||
self.reader.skip_whitespace();
|
||||
let cursor = self.reader.cursor;
|
||||
let tag = super::snbt::parse_tag_argument(self.reader)?;
|
||||
if let Err(m) = decode_component(&ty, &tag) {
|
||||
self.reader.cursor = cursor;
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.malformed",
|
||||
&[&ty, &m],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
}
|
||||
self.sugg = ISugg::NextOrEndComponents;
|
||||
if !self.reader.can_read() || self.reader.peek() != ',' {
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = ISugg::ComponentAssignmentOrRemoval;
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"arguments.item.component.expected",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.reader.expect(']')?;
|
||||
self.sugg = ISugg::Nothing;
|
||||
Ok(())
|
||||
}
|
||||
fn suggest_component(&self, b: &mut SuggestionsBuilder, suffix: &str) {
|
||||
let contents = b.remaining_lower();
|
||||
for id in &self.reg.persistent_components {
|
||||
let matched = if contents.contains(':') {
|
||||
super::args::matches_sub_str(&contents, id)
|
||||
} else {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
super::args::matches_sub_str(&contents, ns)
|
||||
|| super::args::matches_sub_str(&contents, path)
|
||||
};
|
||||
if matched {
|
||||
b.suggest(format!("{id}{suffix}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn fill(&self, builder: &mut SuggestionsBuilder) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
let empty = b.remaining().is_empty();
|
||||
match self.sugg {
|
||||
ISugg::Nothing => {}
|
||||
ISugg::Item => suggest_resources(&mut b, self.reg.ids("minecraft:item"), ""),
|
||||
ISugg::StartComponents => {
|
||||
if empty {
|
||||
b.suggest("[");
|
||||
}
|
||||
}
|
||||
ISugg::ComponentAssignmentOrRemoval => {
|
||||
b.suggest("!");
|
||||
self.suggest_component(&mut b, "=");
|
||||
}
|
||||
ISugg::Component => self.suggest_component(&mut b, ""),
|
||||
ISugg::Assignment => {
|
||||
if empty {
|
||||
b.suggest("=");
|
||||
}
|
||||
}
|
||||
ISugg::NextOrEndComponents => {
|
||||
if empty {
|
||||
b.suggest(",");
|
||||
b.suggest("]");
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// ItemArgument.parse (ItemParser.parse; the reader is rewound on errors).
|
||||
pub fn parse_stack(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
|
||||
let cursor = reader.cursor;
|
||||
let r = ItemState {
|
||||
reader,
|
||||
reg,
|
||||
sugg: ISugg::Nothing,
|
||||
}
|
||||
.parse();
|
||||
if r.is_err() {
|
||||
reader.cursor = cursor;
|
||||
}
|
||||
r
|
||||
}
|
||||
/// ItemParser.fillSuggestions.
|
||||
pub fn suggest_stack(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut state = ItemState {
|
||||
reader: &mut reader,
|
||||
reg,
|
||||
sugg: ISugg::Nothing,
|
||||
};
|
||||
let _ = state.parse();
|
||||
state.fill(builder);
|
||||
}
|
||||
|
||||
// ---- ItemPredicateArgument ------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TypeRes {
|
||||
Item(String),
|
||||
Tag(String),
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum IV {
|
||||
Id(String),
|
||||
Type(Option<TypeRes>),
|
||||
Elem(TypeRes),
|
||||
Unit,
|
||||
Test,
|
||||
Comp(String),
|
||||
Pred(String),
|
||||
Tag(Tag),
|
||||
List(Vec<IV>),
|
||||
}
|
||||
impl Value for IV {
|
||||
fn list(items: Vec<Self>) -> Self {
|
||||
IV::List(items)
|
||||
}
|
||||
}
|
||||
|
||||
fn reg<'a>(state: &State<'a, IV>) -> &'a Registries {
|
||||
state
|
||||
.ctx
|
||||
.and_then(|c| c.downcast_ref::<Registries>())
|
||||
.expect("item predicate grammar needs the registries")
|
||||
}
|
||||
|
||||
/// IdentifierParseRule: skip whitespace, a non-empty identifier (no error).
|
||||
fn id_rule(state: &mut State<IV>) -> Option<IV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
let start = r.cursor;
|
||||
while r.can_read() && is_id_char(r.peek()) {
|
||||
r.skip();
|
||||
}
|
||||
let raw = &r.string[start..r.cursor];
|
||||
let id = if raw.is_empty() {
|
||||
None
|
||||
} else {
|
||||
parse_identifier(raw)
|
||||
};
|
||||
match id {
|
||||
Some(id) => {
|
||||
state.set_reader(&r);
|
||||
Some(IV::Id(id))
|
||||
}
|
||||
None => {
|
||||
r.cursor = start;
|
||||
state.set_reader(&r);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ResourceLookupRule: an identifier validated by `validate`.
|
||||
fn lookup(
|
||||
state: &mut State<IV>,
|
||||
id_rule: usize,
|
||||
possible: Rc<Vec<String>>,
|
||||
validate: &dyn Fn(&str, &Reader) -> Result<IV, CommandError>,
|
||||
) -> Option<IV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let mark = state.cursor;
|
||||
match state.parse(id_rule) {
|
||||
Some(IV::Id(id)) => match validate(&id, &state.reader()) {
|
||||
Ok(v) => Some(v),
|
||||
Err(e) => {
|
||||
state.store(mark, Sugg::Resources(possible), Reason::Error(e));
|
||||
None
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
state.store(
|
||||
mark,
|
||||
Sugg::Resources(possible),
|
||||
Reason::Delayed("argument.id.invalid", Vec::new()),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn predicate_grammar() -> Grammar<IV> {
|
||||
let mut g: Grammar<IV> = Grammar::new();
|
||||
let id = g.put_custom("id", id_rule);
|
||||
let ty = g.named("type");
|
||||
let conditions = g.named("conditions");
|
||||
let ty2 = g.named("type");
|
||||
g.put_term(
|
||||
"top",
|
||||
alt(vec![
|
||||
seq(vec![ty, ch('['), Term::Cut, opt(conditions), ch(']')]),
|
||||
ty2,
|
||||
]),
|
||||
|s| {
|
||||
let mut out = Vec::new();
|
||||
if let Some(t) = s.scope.get("type") {
|
||||
out.push(t);
|
||||
}
|
||||
if let Some(IV::List(c)) = s.scope.get("conditions") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let element = g.named("element_type");
|
||||
let tag = g.named("tag_type");
|
||||
let any = g.named("any_type");
|
||||
g.put_term(
|
||||
"type",
|
||||
alt(vec![element, seq(vec![ch('#'), Term::Cut, tag]), any]),
|
||||
|s| {
|
||||
Some(IV::Type(match s.scope.get_any(&["element_type", "tag_type"]) {
|
||||
Some(IV::Elem(t)) => Some(t),
|
||||
_ => None,
|
||||
}))
|
||||
},
|
||||
);
|
||||
g.put_term("any_type", ch('*'), |_| Some(IV::Unit));
|
||||
g.put_custom("element_type", move |s| {
|
||||
let r = reg(s);
|
||||
let items = Rc::new(r.ids("minecraft:item").to_vec());
|
||||
lookup(s, id, items, &|id, reader| {
|
||||
if r.ids("minecraft:item").iter().any(|i| i == id) {
|
||||
Ok(IV::Elem(TypeRes::Item(id.to_owned())))
|
||||
} else {
|
||||
Err(CommandError::tr_at("argument.item.id.invalid", &[&id], reader))
|
||||
}
|
||||
})
|
||||
});
|
||||
g.put_custom("tag_type", move |s| {
|
||||
let r = reg(s);
|
||||
let tags = Rc::new(r.tags("minecraft:item").to_vec());
|
||||
lookup(s, id, tags, &|id, reader| {
|
||||
if r.tags("minecraft:item").iter().any(|i| i == id) {
|
||||
Ok(IV::Elem(TypeRes::Tag(id.to_owned())))
|
||||
} else {
|
||||
Err(CommandError::tr_at("arguments.item.tag.unknown", &[&id], reader))
|
||||
}
|
||||
})
|
||||
});
|
||||
let alternatives = g.named("alternatives");
|
||||
let rest = g.named("conditions");
|
||||
g.put_term(
|
||||
"conditions",
|
||||
seq(vec![alternatives, opt(seq(vec![ch(','), rest]))]),
|
||||
|s| {
|
||||
let mut out = vec![IV::Test];
|
||||
if let Some(IV::List(c)) = s.scope.get("conditions") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let term = g.named("term");
|
||||
let rest = g.named("alternatives");
|
||||
g.put_term(
|
||||
"alternatives",
|
||||
seq(vec![term, opt(seq(vec![ch('|'), rest]))]),
|
||||
|s| {
|
||||
let mut out = vec![s.scope.get("term").unwrap_or(IV::Test)];
|
||||
if let Some(IV::List(c)) = s.scope.get("alternatives") {
|
||||
out.extend(c);
|
||||
}
|
||||
Some(IV::List(out))
|
||||
},
|
||||
);
|
||||
let test = g.named("test");
|
||||
let negation = g.named("negation");
|
||||
g.put_term("term", alt(vec![test, seq(vec![ch('!'), negation])]), |s| {
|
||||
s.scope.get_any(&["test", "negation"])
|
||||
});
|
||||
let test = g.named("test");
|
||||
g.put_term("negation", test, |_| Some(IV::Test));
|
||||
let comp = g.named("component_type");
|
||||
let tag_a = g.named("tag");
|
||||
let pred = g.named("predicate_type");
|
||||
let tag_b = g.named("tag");
|
||||
let comp2 = g.named("component_type");
|
||||
g.put_term(
|
||||
"test",
|
||||
alt(vec![
|
||||
seq(vec![comp, ch('='), Term::Cut, tag_a]),
|
||||
seq(vec![pred, ch('~'), Term::Cut, tag_b]),
|
||||
comp2,
|
||||
]),
|
||||
|s| {
|
||||
let value = match s.scope.get("tag") {
|
||||
Some(IV::Tag(t)) => Some(t),
|
||||
_ => None,
|
||||
};
|
||||
let reader = s.reader();
|
||||
let result = if let Some(IV::Pred(p)) = s.scope.get("predicate_type") {
|
||||
decode_predicate(&p, value.as_ref().unwrap_or(&Tag::End)).map_err(|m| {
|
||||
CommandError::tr_at("arguments.item.predicate.malformed", &[&p, &m], &reader)
|
||||
})
|
||||
} else if let (Some(IV::Comp(c)), Some(v)) = (s.scope.get("component_type"), value) {
|
||||
decode_component(&c, &v).map_err(|m| {
|
||||
CommandError::tr_at("arguments.item.component.malformed", &[&c, &m], &reader)
|
||||
})
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
match result {
|
||||
Ok(()) => Some(IV::Test),
|
||||
Err(e) => {
|
||||
s.store(s.cursor, Sugg::Empty, Reason::Error(e));
|
||||
None
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
g.put_custom("component_type", move |s| {
|
||||
let r = reg(s);
|
||||
let mut list = vec!["minecraft:count".to_owned()];
|
||||
list.extend(r.persistent_components.iter().cloned());
|
||||
lookup(s, id, Rc::new(list), &|id, reader| {
|
||||
if id == "minecraft:count" {
|
||||
return Ok(IV::Comp(id.to_owned()));
|
||||
}
|
||||
let known = r.ids("minecraft:data_component_type").iter().any(|c| c == id);
|
||||
if known && r.persistent_components.iter().any(|c| c == id) {
|
||||
Ok(IV::Comp(id.to_owned()))
|
||||
} else {
|
||||
Err(CommandError::tr_at("arguments.item.component.unknown", &[&id], reader))
|
||||
}
|
||||
})
|
||||
});
|
||||
g.put_custom("predicate_type", move |s| {
|
||||
let r = reg(s);
|
||||
let mut list = vec!["minecraft:count".to_owned()];
|
||||
list.extend(r.ids("minecraft:data_component_predicate_type").iter().cloned());
|
||||
lookup(s, id, Rc::new(list), &|id, reader| {
|
||||
if id == "minecraft:count"
|
||||
|| r.ids("minecraft:data_component_predicate_type").iter().any(|c| c == id)
|
||||
{
|
||||
return Ok(IV::Pred(id.to_owned()));
|
||||
}
|
||||
if r.ids("minecraft:data_component_type").iter().any(|c| c == id) {
|
||||
// A component existence predicate (decodes Unit).
|
||||
return Ok(IV::Pred(format!("exists:{id}")));
|
||||
}
|
||||
Err(CommandError::tr_at("arguments.item.predicate.unknown", &[&id], reader))
|
||||
})
|
||||
});
|
||||
g.put_custom("tag", |s| super::snbt::rule_in(s, IV::Tag));
|
||||
g.top = g.id("top");
|
||||
g
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PREDICATE: Grammar<IV> = predicate_grammar();
|
||||
}
|
||||
/// ItemPredicateArgument.parse.
|
||||
pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
|
||||
let start = reader.cursor;
|
||||
let result = PREDICATE.with(|g| g.parse_for_commands_with(reader, Some(reg)))?;
|
||||
let IV::List(items) = result else {
|
||||
return Err(CommandError::tr_at("argument.id.invalid", &[], reader));
|
||||
};
|
||||
let text = &reader.string[start..reader.cursor];
|
||||
let (id, tag, any) = match items.first() {
|
||||
Some(IV::Type(Some(TypeRes::Item(i)))) => (i.clone(), false, false),
|
||||
Some(IV::Type(Some(TypeRes::Tag(t)))) => (t.clone(), true, false),
|
||||
_ => ("*".to_owned(), false, true),
|
||||
};
|
||||
let components = text.find('[').map(|i| text[i..].to_owned());
|
||||
Ok(ItemInput {
|
||||
id,
|
||||
tag,
|
||||
any,
|
||||
components,
|
||||
})
|
||||
}
|
||||
/// ItemPredicateArgument.listSuggestions.
|
||||
pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
PREDICATE.with(|g| g.parse_for_suggestions_with(builder, Some(reg)));
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _unused(t: &Tag) -> String {
|
||||
snbt(t)
|
||||
}
|
||||
@@ -4,8 +4,16 @@
|
||||
//! usage text and the vanilla error messages. Argument types live in
|
||||
//! [`args`]; the vanilla command tree in [`vanilla`].
|
||||
pub mod args;
|
||||
pub mod block;
|
||||
pub mod codec;
|
||||
pub mod component;
|
||||
pub mod item;
|
||||
pub mod packrat;
|
||||
pub mod selector;
|
||||
pub mod snbt;
|
||||
pub mod tree_data;
|
||||
pub mod tree_execute;
|
||||
pub mod tree_extra;
|
||||
pub mod tree_misc;
|
||||
pub mod tree_scoreboard;
|
||||
pub mod tree_world;
|
||||
@@ -23,6 +31,9 @@ pub struct CommandError {
|
||||
pub cursor: usize,
|
||||
/// BuiltInExceptions.literalIncorrect (summarised specially by the chat UI).
|
||||
pub literal_incorrect: bool,
|
||||
/// The translation key of the exception type, when known (the
|
||||
/// exception "type" vanilla code compares against).
|
||||
pub key: String,
|
||||
}
|
||||
impl CommandError {
|
||||
pub fn new(message: Text) -> Self {
|
||||
@@ -31,10 +42,13 @@ impl CommandError {
|
||||
input: None,
|
||||
cursor: 0,
|
||||
literal_incorrect: false,
|
||||
key: String::new(),
|
||||
}
|
||||
}
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
Self::new(Text::tr(key, args))
|
||||
let mut e = Self::new(Text::tr(key, args));
|
||||
e.key = key.to_owned();
|
||||
e
|
||||
}
|
||||
pub fn at(message: Text, reader: &Reader) -> Self {
|
||||
Self {
|
||||
@@ -42,10 +56,13 @@ impl CommandError {
|
||||
input: Some(reader.string.to_owned()),
|
||||
cursor: reader.cursor,
|
||||
literal_incorrect: false,
|
||||
key: String::new(),
|
||||
}
|
||||
}
|
||||
pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self {
|
||||
Self::at(Text::tr(key, args), reader)
|
||||
let mut e = Self::at(Text::tr(key, args), reader);
|
||||
e.key = key.to_owned();
|
||||
e
|
||||
}
|
||||
/// CommandSyntaxException.getContext: up to ten characters before the
|
||||
/// cursor followed by "<--[HERE]".
|
||||
@@ -266,6 +283,30 @@ pub struct Node {
|
||||
pub redirect: Option<usize>,
|
||||
/// Required permission level (0 everyone, 2 game masters, 4 owners).
|
||||
pub permission: u8,
|
||||
/// A custom suggestion provider (`.suggests(...)`), used instead of the
|
||||
/// argument type's own suggestions.
|
||||
pub suggests: Option<Suggests>,
|
||||
}
|
||||
/// The custom SuggestionProviders vanilla command nodes use.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Suggests {
|
||||
/// FunctionCommand.SUGGEST_FUNCTION: `#tags` and functions.
|
||||
Functions,
|
||||
/// A fixed list (SharedSuggestionProvider.suggest).
|
||||
Fixed(&'static [&'static str]),
|
||||
/// No candidates (providers over state an empty world lacks).
|
||||
Nothing,
|
||||
/// AdvancementCommands: the criteria of the parsed `advancement`.
|
||||
AdvancementCriteria,
|
||||
/// SuggestionProviders.SUMMONABLE_ENTITIES (with the type names as tooltips).
|
||||
SummonableEntities,
|
||||
/// TimeCommand.suggestTimeMarkers for the parsed `clock` (or the overworld clock).
|
||||
TimeMarkers,
|
||||
/// TriggerCommand.suggestObjectives: the source's enabled trigger objectives.
|
||||
Triggers,
|
||||
/// ScoreboardCommand.suggestTriggers: trigger objectives some of the
|
||||
/// parsed `targets` have no score in, or a locked one.
|
||||
EnableTriggers,
|
||||
}
|
||||
impl Node {
|
||||
pub fn name(&self) -> &str {
|
||||
@@ -412,6 +453,8 @@ pub struct Suggestion {
|
||||
pub range: Range,
|
||||
pub text: String,
|
||||
pub tooltip: Option<String>,
|
||||
/// IntegerSuggestion: sorted numerically against other integers.
|
||||
pub int_value: Option<i32>,
|
||||
}
|
||||
impl Suggestion {
|
||||
/// Suggestion.apply.
|
||||
@@ -447,9 +490,19 @@ impl<'a> SuggestionsBuilder<'a> {
|
||||
range: (self.start, self.input.len()),
|
||||
text,
|
||||
tooltip: None,
|
||||
int_value: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
/// SuggestionsBuilder.suggest(int).
|
||||
pub fn suggest_int(&mut self, value: i32) {
|
||||
self.out.push(Suggestion {
|
||||
range: (self.start, self.input.len()),
|
||||
text: value.to_string(),
|
||||
tooltip: None,
|
||||
int_value: Some(value),
|
||||
});
|
||||
}
|
||||
pub fn suggest_tooltip(&mut self, text: impl Into<String>, tooltip: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if text != self.remaining() {
|
||||
@@ -457,21 +510,71 @@ impl<'a> SuggestionsBuilder<'a> {
|
||||
range: (self.start, self.input.len()),
|
||||
text,
|
||||
tooltip: Some(tooltip.into()),
|
||||
int_value: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> {
|
||||
SuggestionsBuilder::new(self.input, start)
|
||||
}
|
||||
/// SharedSuggestionProvider.suggest: candidates starting with the remaining text.
|
||||
/// SuggestionsBuilder.add: keep another builder's suggestions (with their own ranges).
|
||||
pub fn add(&mut self, other: SuggestionsBuilder) {
|
||||
self.out.extend(other.out);
|
||||
}
|
||||
/// SharedSuggestionProvider.suggest: candidates matching the remaining
|
||||
/// text at the start or after a `.`, `_` or `/`.
|
||||
pub fn suggest_matching<'b>(&mut self, candidates: impl IntoIterator<Item = &'b str>) {
|
||||
let lower = self.remaining_lower();
|
||||
for c in candidates {
|
||||
if c.to_lowercase().starts_with(&lower) {
|
||||
if args::matches_sub_str(&lower, &c.to_lowercase()) {
|
||||
self.suggest(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The same with a tooltip per candidate.
|
||||
pub fn suggest_matching_tooltip<'b>(
|
||||
&mut self,
|
||||
candidates: impl IntoIterator<Item = (&'b str, String)>,
|
||||
) {
|
||||
let lower = self.remaining_lower();
|
||||
for (c, tip) in candidates {
|
||||
if args::matches_sub_str(&lower, &c.to_lowercase()) {
|
||||
self.suggest_tooltip(c, tip);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// String.compareToIgnoreCase.
|
||||
pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let fold = |c: char| -> char {
|
||||
let u = c.to_uppercase().next().unwrap_or(c);
|
||||
u.to_lowercase().next().unwrap_or(u)
|
||||
};
|
||||
let mut x = a.chars();
|
||||
let mut y = b.chars();
|
||||
loop {
|
||||
match (x.next(), y.next()) {
|
||||
(None, None) => return std::cmp::Ordering::Equal,
|
||||
(None, Some(_)) => return std::cmp::Ordering::Less,
|
||||
(Some(_), None) => return std::cmp::Ordering::Greater,
|
||||
(Some(c1), Some(c2)) => {
|
||||
if c1 != c2 {
|
||||
let (l1, l2) = (fold(c1), fold(c2));
|
||||
if l1 != l2 {
|
||||
return l1.cmp(&l2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Suggestion.compareToIgnoreCase (IntegerSuggestion compares numerically).
|
||||
fn compare_suggestions(a: &Suggestion, b: &Suggestion) -> std::cmp::Ordering {
|
||||
match (a.int_value, b.int_value) {
|
||||
(Some(x), Some(y)) => x.cmp(&y),
|
||||
(Some(_), None) => a.text.cmp(&b.text),
|
||||
_ => compare_ignore_case(&a.text, &b.text),
|
||||
}
|
||||
}
|
||||
/// Suggestions.create: merged, expanded to a common range and sorted case-insensitively.
|
||||
pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Suggestion>) {
|
||||
@@ -481,6 +584,8 @@ pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Sugg
|
||||
let start = list.iter().map(|s| s.range.0).min().unwrap_or(0);
|
||||
let end = list.iter().map(|s| s.range.1).max().unwrap_or(0);
|
||||
let mut out: Vec<Suggestion> = Vec::new();
|
||||
let mut seen: std::collections::HashSet<(String, Option<String>)> =
|
||||
std::collections::HashSet::new();
|
||||
for s in list {
|
||||
// Suggestion.expand: pad the text with the input around it.
|
||||
let text = format!(
|
||||
@@ -493,13 +598,93 @@ pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Sugg
|
||||
range: (start, end),
|
||||
text,
|
||||
tooltip: s.tooltip,
|
||||
int_value: if s.range == (start, end) {
|
||||
s.int_value
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
if !out.iter().any(|o| o.text == expanded.text) {
|
||||
if seen.insert((expanded.text.clone(), expanded.tooltip.clone())) {
|
||||
out.push(expanded);
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|a| a.text.to_lowercase());
|
||||
((start, end), out)
|
||||
let ints = out.iter().filter(|s| s.int_value.is_some()).count();
|
||||
if ints == 0 || ints == out.len() {
|
||||
out.sort_by(compare_suggestions);
|
||||
return ((start, end), out);
|
||||
}
|
||||
// A stable insertion sort (the comparator mixes numeric and text order).
|
||||
let mut sorted: Vec<Suggestion> = Vec::with_capacity(out.len());
|
||||
for s in out {
|
||||
let pos = sorted.partition_point(|x| compare_suggestions(x, &s) != std::cmp::Ordering::Greater);
|
||||
sorted.insert(pos, s);
|
||||
}
|
||||
((start, end), sorted)
|
||||
}
|
||||
|
||||
impl Suggests {
|
||||
/// The provider's candidates; `context` is the whole parse context
|
||||
/// (CommandContextBuilder.build), whose arguments some providers read.
|
||||
pub fn suggest(&self, builder: &mut SuggestionsBuilder, reg: &Registries, context: &Context) {
|
||||
match self {
|
||||
Suggests::AdvancementCriteria => {
|
||||
if let Some(Arg::Resource(id)) = context.get("advancement")
|
||||
&& let Some(criteria) = reg.advancement_criteria.get(id)
|
||||
{
|
||||
builder.suggest_matching(criteria.iter().map(String::as_str));
|
||||
}
|
||||
}
|
||||
Suggests::Functions => {
|
||||
args::suggest_resources(builder, ®.function_tags, "#");
|
||||
args::suggest_resources(builder, ®.functions, "");
|
||||
}
|
||||
Suggests::Fixed(values) => builder.suggest_matching(values.iter().copied()),
|
||||
Suggests::SummonableEntities => {
|
||||
let contents = builder.remaining_lower();
|
||||
for id in ®.summonable {
|
||||
if args::resource_matches(&contents, id) {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
let name = crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', ".")));
|
||||
builder.suggest_tooltip(id.clone(), name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Suggests::TimeMarkers => {
|
||||
let clock = match context.get("clock") {
|
||||
Some(Arg::Resource(id)) => id.clone(),
|
||||
_ => "minecraft:overworld".to_owned(),
|
||||
};
|
||||
match reg.clock_time_markers.get(&clock) {
|
||||
Some(markers) => args::suggest_resources(builder, markers, ""),
|
||||
None if clock == "minecraft:overworld" => {
|
||||
args::suggest_resources(builder, ®.time_markers, "")
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Suggests::EnableTriggers => {
|
||||
// getNamesWithDefaultWildcard: `*` means every tracked holder.
|
||||
let targets: Vec<String> = match context.get("targets") {
|
||||
Some(Arg::ScoreHolder(args::ScoreHolderArg::Name(n))) => vec![n.clone()],
|
||||
Some(Arg::ScoreHolder(args::ScoreHolderArg::Wildcard)) => reg.tracked.clone(),
|
||||
_ => reg.players.clone(),
|
||||
};
|
||||
let available: Vec<&str> = reg
|
||||
.trigger_scores
|
||||
.iter()
|
||||
.filter(|(_, scores)| {
|
||||
targets.iter().any(|t| scores.get(t).is_none_or(|locked| *locked))
|
||||
})
|
||||
.map(|(o, _)| o.as_str())
|
||||
.collect();
|
||||
builder.suggest_matching(available);
|
||||
}
|
||||
Suggests::Triggers => {
|
||||
builder.suggest_matching(reg.trigger_objectives.iter().map(String::as_str))
|
||||
}
|
||||
Suggests::Nothing => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command tree (CommandDispatcher). Node 0 is the root.
|
||||
@@ -521,6 +706,7 @@ impl Dispatcher {
|
||||
command: None,
|
||||
redirect: None,
|
||||
permission: 0,
|
||||
suggests: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
@@ -545,6 +731,7 @@ impl Dispatcher {
|
||||
command: None,
|
||||
redirect: None,
|
||||
permission,
|
||||
suggests: None,
|
||||
});
|
||||
let id = self.nodes.len() - 1;
|
||||
self.nodes[parent].children.push(id);
|
||||
@@ -570,6 +757,10 @@ impl Dispatcher {
|
||||
self.nodes[node].redirect = Some(target);
|
||||
node
|
||||
}
|
||||
pub fn suggests(&mut self, node: usize, provider: Suggests) -> usize {
|
||||
self.nodes[node].suggests = Some(provider);
|
||||
node
|
||||
}
|
||||
pub fn requires(&mut self, node: usize, level: u8) -> usize {
|
||||
self.nodes[node].permission = level;
|
||||
node
|
||||
@@ -745,10 +936,8 @@ impl Dispatcher {
|
||||
let start = start.min(cursor);
|
||||
let truncated = &parse.input[..cursor.min(parse.input.len())];
|
||||
let mut all = Vec::new();
|
||||
// Brigadier lists every child, whatever its requirement.
|
||||
for &child in &self.nodes[parent].children {
|
||||
if self.nodes[child].permission > reg.permission {
|
||||
continue;
|
||||
}
|
||||
let mut builder = SuggestionsBuilder::new(truncated, start);
|
||||
match &self.nodes[child].kind {
|
||||
NodeKind::Literal(l) => {
|
||||
@@ -756,7 +945,10 @@ impl Dispatcher {
|
||||
builder.suggest(l.clone());
|
||||
}
|
||||
}
|
||||
NodeKind::Argument { ty, name } => ty.suggest(&mut builder, reg, context, name),
|
||||
NodeKind::Argument { ty, name } => match &self.nodes[child].suggests {
|
||||
Some(provider) => provider.suggest(&mut builder, reg, &parse.context),
|
||||
None => ty.suggest(&mut builder, reg, context, name),
|
||||
},
|
||||
NodeKind::Root => {}
|
||||
}
|
||||
all.extend(builder.out);
|
||||
|
||||
@@ -0,0 +1,627 @@
|
||||
//! A port of vanilla's packrat parsing library (`net.minecraft.util.parsing.packrat`):
|
||||
//! terms, named rules with per-position memoisation, scopes with frames,
|
||||
//! cuts, and the "longest only" error collector whose entries become both
|
||||
//! the parse error and the completion suggestions.
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder, args};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub type Atom = &'static str;
|
||||
pub type RuleId = usize;
|
||||
|
||||
/// A value a rule produces (an element of `Scope`).
|
||||
pub trait Value: Clone {
|
||||
fn list(items: Vec<Self>) -> Self;
|
||||
}
|
||||
|
||||
/// Why a term failed (DelayedException or a ready exception).
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Reason {
|
||||
/// A translatable exception created at the error cursor.
|
||||
Delayed(&'static str, Vec<String>),
|
||||
/// An exception with its own cursor.
|
||||
Error(CommandError),
|
||||
}
|
||||
|
||||
/// SuggestionSupplier.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Sugg {
|
||||
Empty,
|
||||
Values(Rc<Vec<String>>),
|
||||
/// ResourceSuggestion: ids completed with suggestResource.
|
||||
Resources(Rc<Vec<String>>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Key {
|
||||
Frame(usize),
|
||||
Atom(Atom),
|
||||
}
|
||||
|
||||
/// Scope: a stack of frames of atom values.
|
||||
pub struct Scope<V> {
|
||||
stack: Vec<(Key, Option<V>)>,
|
||||
top_entry: usize,
|
||||
top_marker: usize,
|
||||
}
|
||||
impl<V: Clone> Scope<V> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
stack: vec![(Key::Frame(0), None)],
|
||||
top_entry: 0,
|
||||
top_marker: 0,
|
||||
}
|
||||
}
|
||||
fn set(&mut self, i: usize, key: Key, value: Option<V>) {
|
||||
while self.stack.len() <= i {
|
||||
self.stack.push((Key::Frame(0), None));
|
||||
}
|
||||
self.stack[i] = (key, value);
|
||||
}
|
||||
fn value_index(&self, atoms: &[Atom]) -> Option<usize> {
|
||||
let mut i = self.top_entry;
|
||||
while i > self.top_marker {
|
||||
if let Key::Atom(a) = self.stack[i].0
|
||||
&& atoms.contains(&a)
|
||||
{
|
||||
return Some(i);
|
||||
}
|
||||
i -= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
fn setup_new_frame(&mut self) {
|
||||
self.top_entry += 1;
|
||||
let prev = self.top_marker;
|
||||
self.set(self.top_entry, Key::Frame(prev), None);
|
||||
self.top_marker = self.top_entry;
|
||||
}
|
||||
fn previous_marker(&self, marker: usize) -> usize {
|
||||
match self.stack[marker].0 {
|
||||
Key::Frame(p) => p,
|
||||
Key::Atom(_) => 0,
|
||||
}
|
||||
}
|
||||
pub fn push_frame(&mut self) {
|
||||
self.setup_new_frame();
|
||||
}
|
||||
pub fn pop_frame(&mut self) {
|
||||
let marker = self.top_marker;
|
||||
self.top_entry = marker - 1;
|
||||
self.top_marker = self.previous_marker(marker);
|
||||
}
|
||||
fn split_frame(&mut self) {
|
||||
let current = self.top_marker;
|
||||
let n = self.top_entry - self.top_marker;
|
||||
self.setup_new_frame();
|
||||
let mut source = current + 1;
|
||||
let mut target = self.top_entry;
|
||||
for _ in 0..n {
|
||||
target += 1;
|
||||
let key = self.stack[source].0;
|
||||
self.set(target, key, None);
|
||||
source += 1;
|
||||
}
|
||||
self.top_entry = target;
|
||||
}
|
||||
fn clear_frame_values(&mut self) {
|
||||
let mut i = self.top_entry;
|
||||
while i > self.top_marker {
|
||||
self.stack[i].1 = None;
|
||||
i -= 1;
|
||||
}
|
||||
}
|
||||
fn merge_frame(&mut self) {
|
||||
let previous_marker = self.previous_marker(self.top_marker);
|
||||
let mut previous = previous_marker;
|
||||
let mut current = self.top_marker;
|
||||
while current < self.top_entry {
|
||||
previous += 1;
|
||||
current += 1;
|
||||
let (new_key, new_value) = self.stack[current].clone();
|
||||
let old_key = self.stack.get(previous).map(|e| e.0);
|
||||
if old_key != Some(new_key) {
|
||||
self.set(previous, new_key, new_value);
|
||||
} else if new_value.is_some() {
|
||||
self.stack[previous].1 = new_value;
|
||||
}
|
||||
}
|
||||
self.top_entry = previous;
|
||||
self.top_marker = previous_marker;
|
||||
}
|
||||
pub fn put(&mut self, atom: Atom, value: V) {
|
||||
match self.value_index(&[atom]) {
|
||||
Some(i) => self.stack[i].1 = Some(value),
|
||||
None => {
|
||||
self.top_entry += 1;
|
||||
self.set(self.top_entry, Key::Atom(atom), Some(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn get(&self, atom: Atom) -> Option<V> {
|
||||
self.value_index(&[atom]).and_then(|i| self.stack[i].1.clone())
|
||||
}
|
||||
/// Scope.getAny: the newest of several atoms.
|
||||
pub fn get_any(&self, atoms: &[Atom]) -> Option<V> {
|
||||
self.value_index(atoms).and_then(|i| self.stack[i].1.clone())
|
||||
}
|
||||
/// Whether the atom has an entry (even a null one).
|
||||
pub fn has(&self, atom: Atom) -> bool {
|
||||
self.value_index(&[atom]).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A rule: a term with an action, or hand-written parsing.
|
||||
pub enum Rule<V> {
|
||||
Term(Term<V>, Rc<dyn Fn(&mut State<V>) -> Option<V>>),
|
||||
Custom(Rc<dyn Fn(&mut State<V>) -> Option<V>>),
|
||||
}
|
||||
|
||||
pub enum Term<V> {
|
||||
Seq(Vec<Term<V>>),
|
||||
Alt(Vec<Term<V>>),
|
||||
Opt(Box<Term<V>>),
|
||||
Repeated {
|
||||
rule: RuleId,
|
||||
list: Atom,
|
||||
min: usize,
|
||||
},
|
||||
RepeatedSep {
|
||||
rule: RuleId,
|
||||
list: Atom,
|
||||
sep: Box<Term<V>>,
|
||||
min: usize,
|
||||
trailing: bool,
|
||||
},
|
||||
Look(Box<Term<V>>, bool),
|
||||
Marker(Atom, V),
|
||||
Cut,
|
||||
Empty,
|
||||
Fail(Reason),
|
||||
Named {
|
||||
rule: RuleId,
|
||||
store: Atom,
|
||||
},
|
||||
/// StringReaderTerms.TerminalCharacters: one of `values` (or `accept`).
|
||||
Chars {
|
||||
values: Vec<char>,
|
||||
accept: Option<fn(char) -> bool>,
|
||||
},
|
||||
/// StringReaderTerms.TerminalWord.
|
||||
Word(String),
|
||||
}
|
||||
|
||||
pub fn seq<V>(t: Vec<Term<V>>) -> Term<V> {
|
||||
Term::Seq(t)
|
||||
}
|
||||
pub fn alt<V>(t: Vec<Term<V>>) -> Term<V> {
|
||||
Term::Alt(t)
|
||||
}
|
||||
pub fn opt<V>(t: Term<V>) -> Term<V> {
|
||||
Term::Opt(Box::new(t))
|
||||
}
|
||||
pub fn ch<V>(c: char) -> Term<V> {
|
||||
Term::Chars {
|
||||
values: vec![c],
|
||||
accept: None,
|
||||
}
|
||||
}
|
||||
pub fn chs<V>(a: char, b: char) -> Term<V> {
|
||||
Term::Chars {
|
||||
values: vec![a, b],
|
||||
accept: None,
|
||||
}
|
||||
}
|
||||
pub fn look<V>(t: Term<V>) -> Term<V> {
|
||||
Term::Look(Box::new(t), true)
|
||||
}
|
||||
|
||||
/// Dictionary: named rules, with forward references.
|
||||
pub struct Grammar<V> {
|
||||
names: Vec<Atom>,
|
||||
rules: Vec<Option<Rule<V>>>,
|
||||
pub top: RuleId,
|
||||
}
|
||||
impl<V: Value> Default for Grammar<V> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl<V: Value> Grammar<V> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
names: Vec::new(),
|
||||
rules: Vec::new(),
|
||||
top: 0,
|
||||
}
|
||||
}
|
||||
/// Dictionary.forward / getOrCreateEntry.
|
||||
pub fn id(&mut self, name: Atom) -> RuleId {
|
||||
if let Some(i) = self.names.iter().position(|n| *n == name) {
|
||||
return i;
|
||||
}
|
||||
self.names.push(name);
|
||||
self.rules.push(None);
|
||||
self.names.len() - 1
|
||||
}
|
||||
pub fn put(&mut self, name: Atom, rule: Rule<V>) -> RuleId {
|
||||
let id = self.id(name);
|
||||
assert!(self.rules[id].is_none(), "Trying to override rule: {name}");
|
||||
self.rules[id] = Some(rule);
|
||||
id
|
||||
}
|
||||
pub fn put_term(
|
||||
&mut self,
|
||||
name: Atom,
|
||||
term: Term<V>,
|
||||
action: impl Fn(&mut State<V>) -> Option<V> + 'static,
|
||||
) -> RuleId {
|
||||
self.put(name, Rule::Term(term, Rc::new(action)))
|
||||
}
|
||||
pub fn put_custom(
|
||||
&mut self,
|
||||
name: Atom,
|
||||
f: impl Fn(&mut State<V>) -> Option<V> + 'static,
|
||||
) -> RuleId {
|
||||
self.put(name, Rule::Custom(Rc::new(f)))
|
||||
}
|
||||
/// Dictionary.named: parse the rule and store it under its own name.
|
||||
pub fn named(&mut self, name: Atom) -> Term<V> {
|
||||
let rule = self.id(name);
|
||||
Term::Named { rule, store: name }
|
||||
}
|
||||
/// Dictionary.namedWithAlias.
|
||||
pub fn named_as(&mut self, name: Atom, store: Atom) -> Term<V> {
|
||||
let rule = self.id(name);
|
||||
Term::Named { rule, store }
|
||||
}
|
||||
|
||||
/// Grammar.parseForCommands: parse at the reader's cursor; on failure
|
||||
/// the first error stored at the furthest position.
|
||||
pub fn parse_for_commands(&self, reader: &mut Reader) -> CmdResult<V> {
|
||||
self.parse_for_commands_with(reader, None)
|
||||
}
|
||||
/// parse_for_commands with a context value the rules can read (`State::ctx`).
|
||||
pub fn parse_for_commands_with(
|
||||
&self,
|
||||
reader: &mut Reader,
|
||||
ctx: Option<&dyn std::any::Any>,
|
||||
) -> CmdResult<V> {
|
||||
let mut state = State::new(self, reader.string, reader.cursor);
|
||||
state.ctx = ctx;
|
||||
let result = state.parse_top();
|
||||
reader.cursor = state.cursor;
|
||||
match result {
|
||||
Some(v) => Ok(v),
|
||||
None => Err(state.first_error()),
|
||||
}
|
||||
}
|
||||
/// Grammar.parseForSuggestions.
|
||||
pub fn parse_for_suggestions(&self, builder: &mut SuggestionsBuilder) {
|
||||
self.parse_for_suggestions_with(builder, None)
|
||||
}
|
||||
pub fn parse_for_suggestions_with(
|
||||
&self,
|
||||
builder: &mut SuggestionsBuilder,
|
||||
ctx: Option<&dyn std::any::Any>,
|
||||
) {
|
||||
let mut state = State::new(self, builder.input, builder.start);
|
||||
state.ctx = ctx;
|
||||
state.parse_top();
|
||||
if state.errors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut offset = builder.offset(state.last_cursor.max(0) as usize);
|
||||
for (sugg, _) in &state.errors {
|
||||
match sugg {
|
||||
Sugg::Empty => {}
|
||||
Sugg::Values(v) => offset.suggest_matching(v.iter().map(String::as_str)),
|
||||
Sugg::Resources(ids) => args::suggest_resources(&mut offset, ids.iter(), ""),
|
||||
}
|
||||
}
|
||||
builder.add(offset);
|
||||
}
|
||||
}
|
||||
|
||||
/// CachedParseState over a string (StringReaderParserState) with a
|
||||
/// LongestOnly error collector.
|
||||
pub struct State<'g, V> {
|
||||
grammar: &'g Grammar<V>,
|
||||
pub input: &'g str,
|
||||
pub cursor: usize,
|
||||
cache: HashMap<(usize, RuleId), Option<(V, usize)>>,
|
||||
pub scope: Scope<V>,
|
||||
controls: Vec<bool>,
|
||||
errors: Vec<(Sugg, Reason)>,
|
||||
last_cursor: isize,
|
||||
/// Context for the rules (e.g. the registries a lookup checks).
|
||||
pub ctx: Option<&'g dyn std::any::Any>,
|
||||
}
|
||||
const UNBOUND: usize = usize::MAX;
|
||||
impl<'g, V: Value> State<'g, V> {
|
||||
pub fn new(grammar: &'g Grammar<V>, input: &'g str, cursor: usize) -> Self {
|
||||
Self {
|
||||
grammar,
|
||||
input,
|
||||
cursor,
|
||||
cache: HashMap::new(),
|
||||
scope: Scope::new(),
|
||||
controls: Vec::new(),
|
||||
errors: Vec::new(),
|
||||
last_cursor: -1,
|
||||
ctx: None,
|
||||
}
|
||||
}
|
||||
pub fn reader(&self) -> Reader<'g> {
|
||||
Reader {
|
||||
string: self.input,
|
||||
cursor: self.cursor,
|
||||
}
|
||||
}
|
||||
pub fn set_reader(&mut self, r: &Reader) {
|
||||
self.cursor = r.cursor;
|
||||
}
|
||||
fn discard_shorter(&mut self, cursor: usize) {
|
||||
if cursor as isize > self.last_cursor {
|
||||
self.last_cursor = cursor as isize;
|
||||
self.errors.clear();
|
||||
}
|
||||
}
|
||||
/// ErrorCollector.store.
|
||||
pub fn store(&mut self, cursor: usize, sugg: Sugg, reason: Reason) {
|
||||
self.discard_shorter(cursor);
|
||||
if cursor as isize == self.last_cursor {
|
||||
self.errors.push((sugg, reason));
|
||||
}
|
||||
}
|
||||
pub fn store_at_mark(&mut self, reason: Reason) {
|
||||
self.store(self.cursor, Sugg::Empty, reason);
|
||||
}
|
||||
fn parse_top(&mut self) -> Option<V> {
|
||||
let r = self.parse(self.grammar.top);
|
||||
if r.is_some() {
|
||||
self.discard_shorter(self.cursor);
|
||||
}
|
||||
r
|
||||
}
|
||||
fn first_error(&self) -> CommandError {
|
||||
for (_, reason) in &self.errors {
|
||||
return match reason {
|
||||
Reason::Delayed(key, args) => {
|
||||
let args: Vec<&dyn std::fmt::Display> =
|
||||
args.iter().map(|a| a as &dyn std::fmt::Display).collect();
|
||||
CommandError::tr_at(
|
||||
key,
|
||||
&args,
|
||||
&Reader {
|
||||
string: self.input,
|
||||
cursor: self.last_cursor.max(0) as usize,
|
||||
},
|
||||
)
|
||||
}
|
||||
Reason::Error(e) => e.clone(),
|
||||
};
|
||||
}
|
||||
CommandError::new(crate::text::Text::literal("Failed to parse"))
|
||||
}
|
||||
/// CachedParseState.parse: a named rule, memoised per position.
|
||||
pub fn parse(&mut self, rule: RuleId) -> Option<V> {
|
||||
let mark = self.cursor;
|
||||
if let Some(entry) = self.cache.get(&(mark, rule)) {
|
||||
return match entry {
|
||||
None => None,
|
||||
Some((v, after)) => {
|
||||
let v = v.clone();
|
||||
self.cursor = *after;
|
||||
Some(v)
|
||||
}
|
||||
};
|
||||
}
|
||||
let result = match self.grammar.rules[rule].as_ref() {
|
||||
Some(Rule::Term(term, action)) => {
|
||||
let action = action.clone();
|
||||
self.scope.push_frame();
|
||||
let ok = self.term(term, UNBOUND, false);
|
||||
let r = if ok { action(self) } else { None };
|
||||
self.scope.pop_frame();
|
||||
r
|
||||
}
|
||||
Some(Rule::Custom(f)) => {
|
||||
let f = f.clone();
|
||||
f(self)
|
||||
}
|
||||
None => panic!("Unbound rule {}", self.grammar.names[rule]),
|
||||
};
|
||||
let entry = result.clone().map(|v| (v, self.cursor));
|
||||
self.cache.insert((mark, rule), entry);
|
||||
result
|
||||
}
|
||||
fn skip_whitespace(&mut self) {
|
||||
let mut r = self.reader();
|
||||
r.skip_whitespace();
|
||||
self.cursor = r.cursor;
|
||||
}
|
||||
fn term(&mut self, term: &'g Term<V>, control: usize, silent: bool) -> bool {
|
||||
match term {
|
||||
Term::Seq(items) => {
|
||||
let mark = self.cursor;
|
||||
for t in items {
|
||||
if !self.term(t, control, silent) {
|
||||
self.cursor = mark;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Alt(items) => {
|
||||
self.controls.push(false);
|
||||
let ctl = self.controls.len() - 1;
|
||||
let mark = self.cursor;
|
||||
self.scope.split_frame();
|
||||
let mut ok = false;
|
||||
for t in items {
|
||||
if self.term(t, ctl, silent) {
|
||||
self.scope.merge_frame();
|
||||
ok = true;
|
||||
break;
|
||||
}
|
||||
self.scope.clear_frame_values();
|
||||
self.cursor = mark;
|
||||
if self.controls[ctl] {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
self.scope.pop_frame();
|
||||
}
|
||||
self.controls.pop();
|
||||
ok
|
||||
}
|
||||
Term::Opt(t) => {
|
||||
let mark = self.cursor;
|
||||
if !self.term(t, control, silent) {
|
||||
self.cursor = mark;
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Repeated { rule, list, min } => {
|
||||
let mark = self.cursor;
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let entry = self.cursor;
|
||||
match self.parse(*rule) {
|
||||
Some(v) => items.push(v),
|
||||
None => {
|
||||
self.cursor = entry;
|
||||
if items.len() < *min {
|
||||
self.cursor = mark;
|
||||
return false;
|
||||
}
|
||||
self.scope.put(list, V::list(items));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Term::RepeatedSep {
|
||||
rule,
|
||||
list,
|
||||
sep,
|
||||
min,
|
||||
trailing,
|
||||
} => {
|
||||
let list_mark = self.cursor;
|
||||
let mut items = Vec::new();
|
||||
let mut first = true;
|
||||
loop {
|
||||
let before = self.cursor;
|
||||
if !first && !self.term(sep, control, silent) {
|
||||
self.cursor = before;
|
||||
break;
|
||||
}
|
||||
let after = self.cursor;
|
||||
match self.parse(*rule) {
|
||||
Some(v) => items.push(v),
|
||||
None => {
|
||||
if first {
|
||||
self.cursor = after;
|
||||
} else {
|
||||
if !*trailing {
|
||||
self.cursor = list_mark;
|
||||
return false;
|
||||
}
|
||||
self.cursor = after;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
if items.len() < *min {
|
||||
self.cursor = list_mark;
|
||||
return false;
|
||||
}
|
||||
self.scope.put(list, V::list(items));
|
||||
true
|
||||
}
|
||||
Term::Look(t, positive) => {
|
||||
let mark = self.cursor;
|
||||
let r = self.term(t, control, true);
|
||||
self.cursor = mark;
|
||||
*positive == r
|
||||
}
|
||||
Term::Marker(atom, v) => {
|
||||
self.scope.put(atom, v.clone());
|
||||
true
|
||||
}
|
||||
Term::Cut => {
|
||||
if control != UNBOUND {
|
||||
self.controls[control] = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
Term::Empty => true,
|
||||
Term::Fail(reason) => {
|
||||
if !silent {
|
||||
self.store(self.cursor, Sugg::Empty, reason.clone());
|
||||
}
|
||||
false
|
||||
}
|
||||
Term::Named { rule, store } => match self.parse(*rule) {
|
||||
Some(v) => {
|
||||
self.scope.put(store, v);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
Term::Chars { values, accept } => {
|
||||
self.skip_whitespace();
|
||||
let cursor = self.cursor;
|
||||
let mut r = self.reader();
|
||||
if r.can_read() {
|
||||
let c = r.read();
|
||||
self.cursor = r.cursor;
|
||||
let ok = match accept {
|
||||
Some(f) => f(c),
|
||||
None => values.contains(&c),
|
||||
};
|
||||
if ok {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if !silent {
|
||||
let joined = values
|
||||
.iter()
|
||||
.map(char::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
let sugg = Sugg::Values(Rc::new(values.iter().map(char::to_string).collect()));
|
||||
self.store(
|
||||
cursor,
|
||||
sugg,
|
||||
Reason::Delayed("argument.literal.incorrect", vec![joined]),
|
||||
);
|
||||
}
|
||||
false
|
||||
}
|
||||
Term::Word(word) => {
|
||||
self.skip_whitespace();
|
||||
let cursor = self.cursor;
|
||||
let mut r = self.reader();
|
||||
let value = r.read_unquoted_string();
|
||||
self.cursor = r.cursor;
|
||||
if value != word {
|
||||
if !silent {
|
||||
self.store(
|
||||
cursor,
|
||||
Sugg::Values(Rc::new(vec![word.clone()])),
|
||||
Reason::Delayed("argument.literal.incorrect", vec![word.clone()]),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,808 @@
|
||||
//! EntitySelectorParser and EntitySelectorOptions: `@e[...]` selectors,
|
||||
//! player names and UUIDs, with the suggestion state vanilla keeps while
|
||||
//! parsing (`fillSuggestions`).
|
||||
use super::args::{
|
||||
AdvCondition, GameMode, Registries, Selector, Sort, read_double_bounds, read_float_bounds,
|
||||
read_identifier, read_int_bounds, suggest_resources,
|
||||
};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
|
||||
/// The option names in vanilla's registration order.
|
||||
const OPTIONS: [&str; 21] = [
|
||||
"name",
|
||||
"distance",
|
||||
"level",
|
||||
"x",
|
||||
"y",
|
||||
"z",
|
||||
"dx",
|
||||
"dy",
|
||||
"dz",
|
||||
"x_rotation",
|
||||
"y_rotation",
|
||||
"limit",
|
||||
"sort",
|
||||
"gamemode",
|
||||
"team",
|
||||
"type",
|
||||
"tag",
|
||||
"nbt",
|
||||
"scores",
|
||||
"advancements",
|
||||
"predicate",
|
||||
];
|
||||
const SELECTOR_KINDS: [(&str, &str); 6] = [
|
||||
("@p", "argument.entity.selector.nearestPlayer"),
|
||||
("@a", "argument.entity.selector.allPlayers"),
|
||||
("@r", "argument.entity.selector.randomPlayer"),
|
||||
("@s", "argument.entity.selector.self"),
|
||||
("@e", "argument.entity.selector.allEntities"),
|
||||
("@n", "argument.entity.selector.nearestEntity"),
|
||||
];
|
||||
|
||||
/// InvertableSetOptionState.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct InvertableSet {
|
||||
/// 0 none, 1 single, 2 multiple.
|
||||
state: u8,
|
||||
tags: Vec<String>,
|
||||
}
|
||||
impl InvertableSet {
|
||||
fn can_parse_positive(&self) -> bool {
|
||||
self.state == 0
|
||||
}
|
||||
fn can_parse_negative(&self) -> bool {
|
||||
self.state != 1
|
||||
}
|
||||
fn can_parse_any_tag(&self) -> bool {
|
||||
self.can_parse_negative()
|
||||
}
|
||||
fn can_parse_tag(&self, tag: &str) -> bool {
|
||||
self.can_parse_any_tag() && !self.tags.iter().any(|t| t == tag)
|
||||
}
|
||||
fn can_parse_any(&self) -> bool {
|
||||
self.state != 1
|
||||
}
|
||||
fn can_parse_element(&self, inverted: bool) -> bool {
|
||||
if inverted {
|
||||
self.can_parse_negative()
|
||||
} else {
|
||||
self.can_parse_positive()
|
||||
}
|
||||
}
|
||||
fn mark_element(&mut self, inverted: bool) {
|
||||
self.state = if inverted { 2 } else { 1 };
|
||||
}
|
||||
fn mark_tag(&mut self, tag: String) {
|
||||
self.state = 2;
|
||||
self.tags.push(tag);
|
||||
}
|
||||
}
|
||||
|
||||
/// The suggestion function the parser last set.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Sugg {
|
||||
Nothing,
|
||||
NameOrSelector,
|
||||
Name,
|
||||
Selector,
|
||||
OpenOptions,
|
||||
OptionsKeyOrClose,
|
||||
OptionsKey,
|
||||
OptionsNextOrClose,
|
||||
Sort,
|
||||
GameMode,
|
||||
Type,
|
||||
}
|
||||
|
||||
/// EntitySelectorParser over a reader.
|
||||
pub struct SelectorParser<'r, 'a> {
|
||||
pub reader: &'r mut Reader<'a>,
|
||||
reg: &'r Registries,
|
||||
allow_selectors: bool,
|
||||
s: Selector,
|
||||
sugg: Sugg,
|
||||
start_position: usize,
|
||||
current_entity: bool,
|
||||
has_distance: bool,
|
||||
has_level: bool,
|
||||
has_rot_x: bool,
|
||||
has_rot_y: bool,
|
||||
name_option: InvertableSet,
|
||||
limited: bool,
|
||||
sorted: bool,
|
||||
gamemode_option: InvertableSet,
|
||||
team_option: InvertableSet,
|
||||
type_option: InvertableSet,
|
||||
scores_option: bool,
|
||||
advancements_option: bool,
|
||||
}
|
||||
|
||||
/// UUID.fromString.
|
||||
pub fn java_uuid(name: &str) -> Option<u128> {
|
||||
if name.encode_utf16().count() > 36 {
|
||||
return None;
|
||||
}
|
||||
let parts: Vec<&str> = name.split('-').collect();
|
||||
if parts.len() != 5 {
|
||||
return None;
|
||||
}
|
||||
let mut v: [i64; 5] = [0; 5];
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
// Long.parseLong(s, 16): an optional sign then hex digits.
|
||||
let digits = p.strip_prefix(['+', '-']).unwrap_or(p);
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
v[i] = i64::from_str_radix(p, 16).ok()?;
|
||||
}
|
||||
let msb = (((v[0] as u64) & 0xffff_ffff) << 32)
|
||||
| (((v[1] as u64) & 0xffff) << 16)
|
||||
| ((v[2] as u64) & 0xffff);
|
||||
let lsb = (((v[3] as u64) & 0xffff) << 48) | ((v[4] as u64) & 0xffff_ffff_ffff);
|
||||
Some((u128::from(msb) << 64) | u128::from(lsb))
|
||||
}
|
||||
|
||||
fn rollback(reader: &mut Reader, start: usize, key: &str, args: &[&dyn std::fmt::Display]) -> CommandError {
|
||||
reader.cursor = start;
|
||||
CommandError::tr_at(key, args, reader)
|
||||
}
|
||||
|
||||
impl<'r, 'a> SelectorParser<'r, 'a> {
|
||||
pub fn new(reader: &'r mut Reader<'a>, reg: &'r Registries, allow_selectors: bool) -> Self {
|
||||
Self {
|
||||
reader,
|
||||
reg,
|
||||
allow_selectors,
|
||||
s: Selector::default(),
|
||||
sugg: Sugg::Nothing,
|
||||
start_position: 0,
|
||||
current_entity: false,
|
||||
has_distance: false,
|
||||
has_level: false,
|
||||
has_rot_x: false,
|
||||
has_rot_y: false,
|
||||
name_option: InvertableSet::default(),
|
||||
limited: false,
|
||||
sorted: false,
|
||||
gamemode_option: InvertableSet::default(),
|
||||
team_option: InvertableSet::default(),
|
||||
type_option: InvertableSet::default(),
|
||||
scores_option: false,
|
||||
advancements_option: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// EntitySelectorParser.parse.
|
||||
pub fn parse(&mut self) -> CmdResult<Selector> {
|
||||
self.start_position = self.reader.cursor;
|
||||
self.sugg = Sugg::NameOrSelector;
|
||||
if self.reader.can_read() && self.reader.peek() == '@' {
|
||||
if !self.allow_selectors {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.not_allowed",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.parse_selector()?;
|
||||
} else {
|
||||
self.parse_name_or_uuid()?;
|
||||
}
|
||||
Ok(self.s.clone())
|
||||
}
|
||||
|
||||
fn parse_selector(&mut self) -> CmdResult<()> {
|
||||
self.sugg = Sugg::Selector;
|
||||
if !self.reader.can_read() {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.missing",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
let kind = self.reader.read();
|
||||
let s = &mut self.s;
|
||||
s.kind = kind;
|
||||
match kind {
|
||||
'a' => {
|
||||
s.limit = usize::MAX;
|
||||
s.include_entities = false;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
'e' => {
|
||||
s.limit = usize::MAX;
|
||||
s.include_entities = true;
|
||||
}
|
||||
'n' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = true;
|
||||
s.sort = Sort::Nearest;
|
||||
}
|
||||
'p' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = false;
|
||||
s.sort = Sort::Nearest;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
'r' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = false;
|
||||
s.sort = Sort::Random;
|
||||
s.types.push(("minecraft:player".into(), false));
|
||||
}
|
||||
's' => {
|
||||
s.limit = 1;
|
||||
s.include_entities = true;
|
||||
self.current_entity = true;
|
||||
}
|
||||
other => {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.selector.unknown",
|
||||
&[&format!("@{other}")],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
}
|
||||
self.sugg = Sugg::OpenOptions;
|
||||
if self.reader.can_read() && self.reader.peek() == '[' {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::OptionsKeyOrClose;
|
||||
self.parse_options()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_name_or_uuid(&mut self) -> CmdResult<()> {
|
||||
if self.reader.can_read() {
|
||||
self.sugg = Sugg::Name;
|
||||
}
|
||||
let start = self.reader.cursor;
|
||||
let name = self.reader.read_string()?;
|
||||
if let Some(uuid) = java_uuid(&name) {
|
||||
self.s.uuid = Some(uuid);
|
||||
self.s.include_entities = true;
|
||||
self.s.player_name = Some(name);
|
||||
} else {
|
||||
if name.is_empty() || name.encode_utf16().count() > 16 {
|
||||
self.reader.cursor = start;
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.invalid",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
self.s.include_entities = false;
|
||||
self.s.player_name = Some(name);
|
||||
}
|
||||
self.s.kind = '\0';
|
||||
self.s.limit = 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn can_use(&self, option: &str) -> bool {
|
||||
match option {
|
||||
"name" => self.name_option.can_parse_any(),
|
||||
"distance" => !self.has_distance,
|
||||
"level" => !self.has_level,
|
||||
"x" => self.s.pos[0].is_none(),
|
||||
"y" => self.s.pos[1].is_none(),
|
||||
"z" => self.s.pos[2].is_none(),
|
||||
"dx" => self.s.delta[0].is_none(),
|
||||
"dy" => self.s.delta[1].is_none(),
|
||||
"dz" => self.s.delta[2].is_none(),
|
||||
"x_rotation" => !self.has_rot_x,
|
||||
"y_rotation" => !self.has_rot_y,
|
||||
"limit" => !self.current_entity && !self.limited,
|
||||
"sort" => !self.current_entity && !self.sorted,
|
||||
"gamemode" => self.gamemode_option.can_parse_any(),
|
||||
"team" => self.team_option.can_parse_any(),
|
||||
"type" => self.type_option.can_parse_any(),
|
||||
"scores" => !self.scores_option,
|
||||
"advancements" => !self.advancements_option,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_options(&mut self) -> CmdResult<()> {
|
||||
self.sugg = Sugg::OptionsKey;
|
||||
self.reader.skip_whitespace();
|
||||
while self.reader.can_read() && self.reader.peek() != ']' {
|
||||
self.reader.skip_whitespace();
|
||||
let start = self.reader.cursor;
|
||||
let key = self.reader.read_string()?;
|
||||
if !OPTIONS.contains(&key.as_str()) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.unknown",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
if !self.can_use(&key) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
self.reader.skip_whitespace();
|
||||
if !self.reader.can_read() || self.reader.peek() != '=' {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.valueless",
|
||||
&[&key],
|
||||
));
|
||||
}
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::Nothing;
|
||||
self.handle(&key)?;
|
||||
self.reader.skip_whitespace();
|
||||
self.sugg = Sugg::OptionsNextOrClose;
|
||||
if self.reader.can_read() {
|
||||
if self.reader.peek() != ',' {
|
||||
if self.reader.peek() != ']' {
|
||||
return Err(CommandError::tr_at(
|
||||
"argument.entity.options.unterminated",
|
||||
&[],
|
||||
self.reader,
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::OptionsKey;
|
||||
}
|
||||
}
|
||||
if self.reader.can_read() {
|
||||
self.reader.skip();
|
||||
self.sugg = Sugg::Nothing;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommandError::tr_at(
|
||||
"argument.entity.options.unterminated",
|
||||
&[],
|
||||
self.reader,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn should_invert(&mut self) -> bool {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '!' {
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
fn is_tag(&mut self) -> bool {
|
||||
self.reader.skip_whitespace();
|
||||
if self.reader.can_read() && self.reader.peek() == '#' {
|
||||
self.reader.skip();
|
||||
self.reader.skip_whitespace();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(&mut self, key: &str) -> CmdResult<()> {
|
||||
match key {
|
||||
"name" => {
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
let name = self.reader.read_string()?;
|
||||
if !self.name_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"name"],
|
||||
));
|
||||
}
|
||||
self.name_option.mark_element(inverted);
|
||||
self.s.names.push((name, inverted));
|
||||
}
|
||||
"distance" => {
|
||||
let start = self.reader.cursor;
|
||||
let value = read_double_bounds(self.reader)?;
|
||||
if value.0.is_some_and(|v| v < 0.0) || value.1.is_some_and(|v| v < 0.0) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.distance.negative",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.distance = Some(value);
|
||||
self.has_distance = true;
|
||||
}
|
||||
"level" => {
|
||||
let start = self.reader.cursor;
|
||||
let value = read_int_bounds(self.reader)?;
|
||||
if value.0.is_some_and(|v| v < 0) || value.1.is_some_and(|v| v < 0) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.level.negative",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.level = Some(value);
|
||||
self.has_level = true;
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
"x" | "y" | "z" => {
|
||||
let i = usize::from(key.as_bytes()[0] - b'x');
|
||||
self.s.pos[i] = Some(self.reader.read_double()?);
|
||||
}
|
||||
"dx" | "dy" | "dz" => {
|
||||
let i = usize::from(key.as_bytes()[1] - b'x');
|
||||
self.s.delta[i] = Some(self.reader.read_double()?);
|
||||
}
|
||||
"x_rotation" | "y_rotation" => {
|
||||
let (lo, hi) = read_float_bounds(self.reader)?;
|
||||
let range = (lo.map(f64::from), hi.map(f64::from));
|
||||
if key == "x_rotation" {
|
||||
self.s.x_rotation = Some(range);
|
||||
self.has_rot_x = true;
|
||||
} else {
|
||||
self.s.y_rotation = Some(range);
|
||||
self.has_rot_y = true;
|
||||
}
|
||||
}
|
||||
"limit" => {
|
||||
let start = self.reader.cursor;
|
||||
let count = self.reader.read_int()?;
|
||||
if count < 1 {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.limit.toosmall",
|
||||
&[],
|
||||
));
|
||||
}
|
||||
self.s.limit = count as usize;
|
||||
self.limited = true;
|
||||
}
|
||||
"sort" => {
|
||||
let start = self.reader.cursor;
|
||||
let name = self.reader.read_unquoted_string();
|
||||
self.sugg = Sugg::Sort;
|
||||
self.s.sort = match name {
|
||||
"nearest" => Sort::Nearest,
|
||||
"furthest" => Sort::Furthest,
|
||||
"random" => Sort::Random,
|
||||
"arbitrary" => Sort::Arbitrary,
|
||||
_ => {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.sort.irreversible",
|
||||
&[&name],
|
||||
));
|
||||
}
|
||||
};
|
||||
self.sorted = true;
|
||||
}
|
||||
"gamemode" => {
|
||||
self.sugg = Sugg::GameMode;
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
if !self.gamemode_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"gamemode"],
|
||||
));
|
||||
}
|
||||
let name = self.reader.read_unquoted_string();
|
||||
if GameMode::from_name(name).is_none() {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.mode.invalid",
|
||||
&[&name],
|
||||
));
|
||||
}
|
||||
self.s.include_entities = false;
|
||||
self.s.gamemodes.push((name.to_owned(), inverted));
|
||||
self.gamemode_option.mark_element(inverted);
|
||||
}
|
||||
"team" => {
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
let name = self.reader.read_unquoted_string().to_owned();
|
||||
if !self.team_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"team"],
|
||||
));
|
||||
}
|
||||
self.s.teams.push((name, inverted));
|
||||
self.team_option.mark_element(inverted);
|
||||
}
|
||||
"type" => {
|
||||
self.sugg = Sugg::Type;
|
||||
let start = self.reader.cursor;
|
||||
let inverted = self.should_invert();
|
||||
if self.is_tag() {
|
||||
if !self.type_option.can_parse_any_tag() {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
let id = read_identifier(self.reader)?;
|
||||
if !self.type_option.can_parse_tag(&id) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
self.s.types.push((format!("#{id}"), inverted));
|
||||
self.type_option.mark_tag(id);
|
||||
} else {
|
||||
if !self.type_option.can_parse_element(inverted) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.inapplicable",
|
||||
&[&"type"],
|
||||
));
|
||||
}
|
||||
let id = read_identifier(self.reader)?;
|
||||
let types = self.reg.ids("minecraft:entity_type");
|
||||
if !types.is_empty() && !types.contains(&id) {
|
||||
return Err(rollback(
|
||||
self.reader,
|
||||
start,
|
||||
"argument.entity.options.type.invalid",
|
||||
&[&id],
|
||||
));
|
||||
}
|
||||
if id == "minecraft:player" && !inverted {
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
if !inverted {
|
||||
// limitToType replaces the player type of @a/@p/@r.
|
||||
self.s.types.retain(|(t, n)| *n || t.starts_with('#'));
|
||||
}
|
||||
self.s.types.push((id, inverted));
|
||||
self.type_option.mark_element(inverted);
|
||||
}
|
||||
}
|
||||
"tag" => {
|
||||
let inverted = self.should_invert();
|
||||
let tag = self.reader.read_unquoted_string().to_owned();
|
||||
self.s.tags.push((tag, inverted));
|
||||
}
|
||||
"nbt" => {
|
||||
let inverted = self.should_invert();
|
||||
let start = self.reader.cursor;
|
||||
super::snbt::parse_compound_argument(self.reader)?;
|
||||
let text = self.reader.string[start..self.reader.cursor].to_owned();
|
||||
self.s.nbt.push((text, inverted));
|
||||
}
|
||||
"scores" => {
|
||||
let r = &mut *self.reader;
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
let mut expected = Vec::new();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let name = r.read_unquoted_string().to_owned();
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
let value = read_int_bounds(r)?;
|
||||
expected.push((name, value));
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.expect('}')?;
|
||||
self.s.scores.extend(expected);
|
||||
self.scores_option = true;
|
||||
}
|
||||
"advancements" => {
|
||||
let r = &mut *self.reader;
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
let mut expected = Vec::new();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let name = read_identifier(r)?;
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == '{' {
|
||||
let mut progress = Vec::new();
|
||||
r.skip_whitespace();
|
||||
r.expect('{')?;
|
||||
r.skip_whitespace();
|
||||
while r.can_read() && r.peek() != '}' {
|
||||
r.skip_whitespace();
|
||||
let criterion = r.read_unquoted_string().to_owned();
|
||||
r.skip_whitespace();
|
||||
r.expect('=')?;
|
||||
r.skip_whitespace();
|
||||
let value = r.read_boolean()?;
|
||||
progress.push((criterion, value));
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.skip_whitespace();
|
||||
r.expect('}')?;
|
||||
r.skip_whitespace();
|
||||
expected.push((name, AdvCondition::Criteria(progress)));
|
||||
} else {
|
||||
let value = r.read_boolean()?;
|
||||
expected.push((name, AdvCondition::Done(value)));
|
||||
}
|
||||
r.skip_whitespace();
|
||||
if r.can_read() && r.peek() == ',' {
|
||||
r.skip();
|
||||
}
|
||||
}
|
||||
r.expect('}')?;
|
||||
if !expected.is_empty() {
|
||||
self.s.include_entities = false;
|
||||
}
|
||||
self.s.advancements.extend(expected);
|
||||
self.advancements_option = true;
|
||||
}
|
||||
"predicate" => {
|
||||
let inverted = self.should_invert();
|
||||
let id = read_identifier(self.reader)?;
|
||||
self.s.predicates.push((id, inverted));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fill_selectors(builder: &mut SuggestionsBuilder) {
|
||||
for (s, tip) in SELECTOR_KINDS {
|
||||
builder.suggest_tooltip(s, crate::lang::get(tip));
|
||||
}
|
||||
}
|
||||
|
||||
/// EntitySelectorParser.fillSuggestions: `names` adds the name
|
||||
/// candidates (online players for most arguments).
|
||||
pub fn fill_suggestions(
|
||||
&self,
|
||||
builder: &mut SuggestionsBuilder,
|
||||
names: &dyn Fn(&mut SuggestionsBuilder),
|
||||
) {
|
||||
let mut b = builder.offset(self.reader.cursor);
|
||||
match self.sugg {
|
||||
Sugg::Nothing => {}
|
||||
Sugg::NameOrSelector => {
|
||||
names(&mut b);
|
||||
if self.allow_selectors {
|
||||
Self::fill_selectors(&mut b);
|
||||
}
|
||||
}
|
||||
Sugg::Name => {
|
||||
let mut sub = b.offset(self.start_position);
|
||||
names(&mut sub);
|
||||
b.add(sub);
|
||||
}
|
||||
Sugg::Selector => {
|
||||
let mut sub = b.offset(b.start - 1);
|
||||
Self::fill_selectors(&mut sub);
|
||||
b.add(sub);
|
||||
}
|
||||
Sugg::OpenOptions => b.suggest("["),
|
||||
Sugg::OptionsKeyOrClose => {
|
||||
b.suggest("]");
|
||||
self.suggest_names(&mut b);
|
||||
}
|
||||
Sugg::OptionsKey => self.suggest_names(&mut b),
|
||||
Sugg::OptionsNextOrClose => {
|
||||
b.suggest(",");
|
||||
b.suggest("]");
|
||||
}
|
||||
Sugg::Sort => b.suggest_matching(["nearest", "furthest", "random", "arbitrary"]),
|
||||
Sugg::GameMode => {
|
||||
let state = &self.gamemode_option;
|
||||
let mut prefix = b.remaining_lower();
|
||||
let mut add_normal = state.can_parse_positive();
|
||||
let mut add_inverted = state.can_parse_negative();
|
||||
if !prefix.is_empty() {
|
||||
if prefix.starts_with('!') {
|
||||
add_normal = false;
|
||||
prefix.remove(0);
|
||||
} else {
|
||||
add_inverted = false;
|
||||
}
|
||||
}
|
||||
for mode in GameMode::ALL {
|
||||
if mode.name().starts_with(&prefix) {
|
||||
if add_inverted {
|
||||
b.suggest(format!("!{}", mode.name()));
|
||||
}
|
||||
if add_normal {
|
||||
b.suggest(mode.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Sugg::Type => {
|
||||
let state = &self.type_option;
|
||||
let types = self.reg.ids("minecraft:entity_type");
|
||||
if state.can_parse_negative() {
|
||||
suggest_resources(&mut b, types, "!");
|
||||
}
|
||||
if state.can_parse_positive() {
|
||||
suggest_resources(&mut b, types, "");
|
||||
}
|
||||
if state.can_parse_any_tag() {
|
||||
let tags: Vec<String> = self
|
||||
.reg
|
||||
.tags("minecraft:entity_type")
|
||||
.iter()
|
||||
.filter(|t| state.can_parse_tag(t))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !tags.is_empty() {
|
||||
suggest_resources(&mut b, &tags, "#");
|
||||
suggest_resources(&mut b, &tags, "!#");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.add(b);
|
||||
}
|
||||
|
||||
fn suggest_names(&self, b: &mut SuggestionsBuilder) {
|
||||
let lower = b.remaining_lower();
|
||||
for o in OPTIONS {
|
||||
if self.can_use(o) && o.starts_with(&lower) {
|
||||
b.suggest_tooltip(
|
||||
format!("{o}="),
|
||||
crate::lang::get(&format!("argument.entity.options.{o}.description")),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a selector from `reader` (EntitySelectorParser.parse).
|
||||
pub fn parse(reader: &mut Reader, reg: &Registries, allow_selectors: bool) -> CmdResult<Selector> {
|
||||
SelectorParser::new(reader, reg, allow_selectors).parse()
|
||||
}
|
||||
|
||||
/// Re-parse the text from `builder.start` and fill the selector suggestions.
|
||||
pub fn suggest(
|
||||
builder: &mut SuggestionsBuilder,
|
||||
reg: &Registries,
|
||||
names: &dyn Fn(&mut SuggestionsBuilder),
|
||||
) {
|
||||
let mut reader = Reader {
|
||||
string: builder.input,
|
||||
cursor: builder.start,
|
||||
};
|
||||
let mut parser = SelectorParser::new(&mut reader, reg, reg.permission >= 2);
|
||||
let _ = parser.parse();
|
||||
parser.fill_suggestions(builder, names);
|
||||
}
|
||||
@@ -0,0 +1,943 @@
|
||||
//! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its
|
||||
//! error messages and completion suggestions, producing NBT tags.
|
||||
use super::packrat::{
|
||||
Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq,
|
||||
};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TypeSuffix {
|
||||
Float,
|
||||
Double,
|
||||
Byte,
|
||||
Short,
|
||||
Int,
|
||||
Long,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Base {
|
||||
Binary,
|
||||
Decimal,
|
||||
Hex,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArrayPrefix {
|
||||
Byte,
|
||||
Int,
|
||||
Long,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IntLit {
|
||||
minus: bool,
|
||||
base: Base,
|
||||
digits: String,
|
||||
/// Some(true) signed, Some(false) unsigned.
|
||||
signed: Option<bool>,
|
||||
ty: Option<TypeSuffix>,
|
||||
}
|
||||
|
||||
/// The values SnbtGrammar's rules produce.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SV {
|
||||
Tag(Tag),
|
||||
Str(String),
|
||||
/// A sign: true for minus.
|
||||
Sign(bool),
|
||||
Suffix(Option<bool>, Option<TypeSuffix>),
|
||||
Type(TypeSuffix),
|
||||
Int(IntLit),
|
||||
/// float exponent: (minus, digits)
|
||||
Exp(bool, String),
|
||||
Prefix(ArrayPrefix),
|
||||
List(Vec<SV>),
|
||||
Entry(String, Tag),
|
||||
}
|
||||
impl Value for SV {
|
||||
fn list(items: Vec<Self>) -> Self {
|
||||
SV::List(items)
|
||||
}
|
||||
}
|
||||
fn delayed(key: &'static str) -> Reason {
|
||||
Reason::Delayed(key, Vec::new())
|
||||
}
|
||||
|
||||
fn can_start_number(c: char) -> bool {
|
||||
matches!(c, '+' | '-' | '.' | '0'..='9')
|
||||
}
|
||||
|
||||
/// NumberRunParseRule.
|
||||
fn number_run(
|
||||
state: &mut State<SV>,
|
||||
accept: fn(char) -> bool,
|
||||
no_value: &'static str,
|
||||
) -> Option<SV> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let start = state.cursor;
|
||||
let rest = &state.input[start..];
|
||||
let len: usize = rest
|
||||
.chars()
|
||||
.take_while(|c| accept(*c))
|
||||
.map(char::len_utf8)
|
||||
.sum();
|
||||
if len == 0 {
|
||||
state.store_at_mark(delayed(no_value));
|
||||
return None;
|
||||
}
|
||||
let s = &rest[..len];
|
||||
if s.starts_with('_') || s.ends_with('_') {
|
||||
state.store_at_mark(delayed("snbt.parser.underscore_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
state.cursor = start + len;
|
||||
Some(SV::Str(s.to_owned()))
|
||||
}
|
||||
/// GreedyPredicateParseRule (no whitespace skipping).
|
||||
fn greedy(
|
||||
state: &mut State<SV>,
|
||||
accept: fn(char) -> bool,
|
||||
min: usize,
|
||||
max: usize,
|
||||
error: Reason,
|
||||
) -> Option<SV> {
|
||||
let start = state.cursor;
|
||||
let rest = &state.input[start..];
|
||||
let mut len = 0;
|
||||
let mut count = 0;
|
||||
for c in rest.chars() {
|
||||
if !accept(c) || count >= max {
|
||||
break;
|
||||
}
|
||||
len += c.len_utf8();
|
||||
count += c.len_utf16();
|
||||
}
|
||||
if count < min {
|
||||
state.store_at_mark(error);
|
||||
return None;
|
||||
}
|
||||
state.cursor = start + len;
|
||||
Some(SV::Str(rest[..len].to_owned()))
|
||||
}
|
||||
|
||||
fn number_error(message: String) -> Reason {
|
||||
Reason::Delayed("snbt.parser.number_parse_failure", vec![message])
|
||||
}
|
||||
fn for_input(s: &str, radix: u32) -> String {
|
||||
if radix == 10 {
|
||||
format!("For input string: \"{s}\"")
|
||||
} else {
|
||||
format!("For input string: \"{s}\" under radix {radix}")
|
||||
}
|
||||
}
|
||||
/// Long.parseLong(s, radix) with its NumberFormatException messages.
|
||||
fn parse_long(s: &str, radix: u32) -> Result<i64, String> {
|
||||
let digits = s.strip_prefix(['-', '+']).unwrap_or(s);
|
||||
if digits.is_empty() {
|
||||
return Err(for_input(s, radix));
|
||||
}
|
||||
i64::from_str_radix(s.strip_prefix('+').unwrap_or(s), radix).map_err(|_| for_input(s, radix))
|
||||
}
|
||||
fn parse_int(s: &str, radix: u32) -> Result<i32, String> {
|
||||
let v = parse_long(s, radix).map_err(|_| for_input(s, radix))?;
|
||||
i32::try_from(v).map_err(|_| for_input(s, radix))
|
||||
}
|
||||
fn parse_small(s: &str, radix: u32, lo: i32, hi: i32) -> Result<i32, String> {
|
||||
let v = parse_int(s, radix)?;
|
||||
if v < lo || v > hi {
|
||||
return Err(format!("Value out of range. Value:\"{s}\" Radix:{radix}"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
fn parse_unsigned_int(s: &str, radix: u32) -> Result<i32, String> {
|
||||
if s.starts_with('-') {
|
||||
return Err(format!("Illegal leading minus sign on unsigned string {s}."));
|
||||
}
|
||||
let len = s.chars().count();
|
||||
if len <= 5 || (radix == 10 && len <= 9) {
|
||||
return parse_int(s, radix);
|
||||
}
|
||||
let v = parse_long(s, radix)?;
|
||||
if (v as u64) & 0xffff_ffff_0000_0000 == 0 {
|
||||
Ok(v as u32 as i32)
|
||||
} else {
|
||||
Err(format!("String value {s} exceeds range of unsigned int."))
|
||||
}
|
||||
}
|
||||
fn parse_unsigned_long(s: &str, radix: u32) -> Result<i64, String> {
|
||||
if s.starts_with('-') {
|
||||
return Err(format!("Illegal leading minus sign on unsigned string {s}."));
|
||||
}
|
||||
let digits = s.strip_prefix('+').unwrap_or(s);
|
||||
match u64::from_str_radix(digits, radix) {
|
||||
Ok(v) => Ok(v as i64),
|
||||
Err(_) => {
|
||||
if digits.chars().all(|c| c.is_digit(radix)) && !digits.is_empty() {
|
||||
Err(format!("String value {s} exceeds range of unsigned long."))
|
||||
} else {
|
||||
Err(for_input(s, radix))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IntLit {
|
||||
fn signed_or_default(&self) -> bool {
|
||||
self.signed.unwrap_or(self.base == Base::Decimal)
|
||||
}
|
||||
fn cleaned(&self) -> String {
|
||||
let mut out = String::new();
|
||||
if self.minus {
|
||||
out.push('-');
|
||||
}
|
||||
out.extend(self.digits.chars().filter(|c| *c != '_'));
|
||||
out
|
||||
}
|
||||
/// IntegerLiteral.create with the given type.
|
||||
fn create(&self, ty: TypeSuffix, state: &mut State<SV>) -> Option<Tag> {
|
||||
let signed = self.signed_or_default();
|
||||
if !signed && self.minus {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_non_negative_number"));
|
||||
return None;
|
||||
}
|
||||
let s = self.cleaned();
|
||||
let radix = match self.base {
|
||||
Base::Binary => 2,
|
||||
Base::Decimal => 10,
|
||||
Base::Hex => 16,
|
||||
};
|
||||
let r = if signed {
|
||||
match ty {
|
||||
TypeSuffix::Byte => parse_small(&s, radix, -128, 127).map(|v| Tag::Byte(v as i8)),
|
||||
TypeSuffix::Short => {
|
||||
parse_small(&s, radix, -32768, 32767).map(|v| Tag::Short(v as i16))
|
||||
}
|
||||
TypeSuffix::Int => parse_int(&s, radix).map(Tag::Int),
|
||||
TypeSuffix::Long => parse_long(&s, radix).map(Tag::Long),
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match ty {
|
||||
TypeSuffix::Byte => parse_int(&s, radix).and_then(|v| {
|
||||
if v >> 8 == 0 {
|
||||
Ok(Tag::Byte(v as u8 as i8))
|
||||
} else {
|
||||
Err(format!("out of range: {v}"))
|
||||
}
|
||||
}),
|
||||
TypeSuffix::Short => parse_int(&s, radix).and_then(|v| {
|
||||
if v >> 16 == 0 {
|
||||
Ok(Tag::Short(v as u16 as i16))
|
||||
} else {
|
||||
Err(format!("out of range: {v}"))
|
||||
}
|
||||
}),
|
||||
TypeSuffix::Int => parse_unsigned_int(&s, radix).map(Tag::Int),
|
||||
TypeSuffix::Long => parse_unsigned_long(&s, radix).map(Tag::Long),
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
};
|
||||
match r {
|
||||
Ok(t) => Some(t),
|
||||
Err(m) => {
|
||||
state.store_at_mark(number_error(m));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn float_tag(text: &str, ty: Option<TypeSuffix>, state: &mut State<SV>) -> Option<Tag> {
|
||||
match ty {
|
||||
Some(TypeSuffix::Float) => {
|
||||
let v: f32 = text.parse().unwrap_or(f32::NAN);
|
||||
if !v.is_finite() {
|
||||
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
Some(Tag::Float(v.to_bits()))
|
||||
}
|
||||
None | Some(TypeSuffix::Double) => {
|
||||
let v: f64 = text.parse().unwrap_or(f64::NAN);
|
||||
if !v.is_finite() {
|
||||
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
|
||||
return None;
|
||||
}
|
||||
Some(Tag::Double(v.to_bits()))
|
||||
}
|
||||
_ => {
|
||||
state.store_at_mark(delayed("snbt.parser.expected_float_type"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_str(state: &State<SV>, atom: &'static str) -> Option<String> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::Str(s)) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn get_tag(state: &State<SV>, atom: &'static str) -> Option<Tag> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::Tag(t)) => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn get_list(state: &State<SV>, atom: &'static str) -> Vec<SV> {
|
||||
match state.scope.get(atom) {
|
||||
Some(SV::List(l)) => l,
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(c: char) -> bool {
|
||||
c.is_ascii_hexdigit()
|
||||
}
|
||||
|
||||
/// SnbtGrammar.createParser over NBT.
|
||||
pub fn grammar() -> Grammar<SV> {
|
||||
let mut g: Grammar<SV> = Grammar::new();
|
||||
g.put_term(
|
||||
"sign",
|
||||
alt(vec![
|
||||
seq(vec![ch('+'), Term::Marker("sign", SV::Sign(false))]),
|
||||
seq(vec![ch('-'), Term::Marker("sign", SV::Sign(true))]),
|
||||
]),
|
||||
|s| s.scope.get("sign"),
|
||||
);
|
||||
let suffix = |signed: Option<bool>, ty: TypeSuffix| {
|
||||
Term::Marker("integer_suffix", SV::Suffix(signed, Some(ty)))
|
||||
};
|
||||
let types = |signed: Option<bool>| {
|
||||
alt(vec![
|
||||
seq(vec![chs('b', 'B'), suffix(signed, TypeSuffix::Byte)]),
|
||||
seq(vec![chs('s', 'S'), suffix(signed, TypeSuffix::Short)]),
|
||||
seq(vec![chs('i', 'I'), suffix(signed, TypeSuffix::Int)]),
|
||||
seq(vec![chs('l', 'L'), suffix(signed, TypeSuffix::Long)]),
|
||||
])
|
||||
};
|
||||
g.put_term(
|
||||
"integer_suffix",
|
||||
alt(vec![
|
||||
seq(vec![chs('u', 'U'), types(Some(false))]),
|
||||
seq(vec![chs('s', 'S'), types(Some(true))]),
|
||||
seq(vec![chs('b', 'B'), suffix(None, TypeSuffix::Byte)]),
|
||||
seq(vec![chs('s', 'S'), suffix(None, TypeSuffix::Short)]),
|
||||
seq(vec![chs('i', 'I'), suffix(None, TypeSuffix::Int)]),
|
||||
seq(vec![chs('l', 'L'), suffix(None, TypeSuffix::Long)]),
|
||||
]),
|
||||
|s| s.scope.get("integer_suffix"),
|
||||
);
|
||||
g.put_custom("binary_numeral", |s| {
|
||||
number_run(s, |c| matches!(c, '0' | '1' | '_'), "snbt.parser.expected_binary_numeral")
|
||||
});
|
||||
g.put_custom("decimal_numeral", |s| {
|
||||
number_run(
|
||||
s,
|
||||
|c| c.is_ascii_digit() || c == '_',
|
||||
"snbt.parser.expected_decimal_numeral",
|
||||
)
|
||||
});
|
||||
g.put_custom("hex_numeral", |s| {
|
||||
number_run(
|
||||
s,
|
||||
|c| c.is_ascii_hexdigit() || c == '_',
|
||||
"snbt.parser.expected_hex_numeral",
|
||||
)
|
||||
});
|
||||
let sign = g.named("sign");
|
||||
let hex_numeral = g.named("hex_numeral");
|
||||
let binary_numeral = g.named("binary_numeral");
|
||||
let decimal = g.named("decimal_numeral");
|
||||
let decimal2 = g.named("decimal_numeral");
|
||||
let isuffix = g.named("integer_suffix");
|
||||
g.put_term(
|
||||
"integer_literal",
|
||||
seq(vec![
|
||||
opt(sign),
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
ch('0'),
|
||||
Term::Cut,
|
||||
alt(vec![
|
||||
seq(vec![chs('x', 'X'), Term::Cut, hex_numeral]),
|
||||
seq(vec![chs('b', 'B'), binary_numeral]),
|
||||
seq(vec![
|
||||
decimal,
|
||||
Term::Cut,
|
||||
Term::Fail(delayed("snbt.parser.leading_zero_not_allowed")),
|
||||
]),
|
||||
Term::Marker("decimal_numeral", SV::Str("0".into())),
|
||||
]),
|
||||
]),
|
||||
decimal2,
|
||||
]),
|
||||
opt(isuffix),
|
||||
]),
|
||||
|s| {
|
||||
let (signed, ty) = match s.scope.get("integer_suffix") {
|
||||
Some(SV::Suffix(a, b)) => (a, b),
|
||||
_ => (None, None),
|
||||
};
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
let (base, digits) = if let Some(d) = get_str(s, "decimal_numeral") {
|
||||
(Base::Decimal, d)
|
||||
} else if let Some(h) = get_str(s, "hex_numeral") {
|
||||
(Base::Hex, h)
|
||||
} else {
|
||||
(Base::Binary, get_str(s, "binary_numeral").unwrap_or_default())
|
||||
};
|
||||
Some(SV::Int(IntLit {
|
||||
minus,
|
||||
base,
|
||||
digits,
|
||||
signed,
|
||||
ty,
|
||||
}))
|
||||
},
|
||||
);
|
||||
g.put_term(
|
||||
"float_type_suffix",
|
||||
alt(vec![
|
||||
seq(vec![chs('f', 'F'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float))]),
|
||||
seq(vec![chs('d', 'D'), Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double))]),
|
||||
]),
|
||||
|s| s.scope.get("float_type_suffix"),
|
||||
);
|
||||
let sign = g.named("sign");
|
||||
let decimal = g.named("decimal_numeral");
|
||||
g.put_term(
|
||||
"float_exponent_part",
|
||||
seq(vec![chs('e', 'E'), opt(sign), decimal]),
|
||||
|s| {
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
Some(SV::Exp(minus, get_str(s, "decimal_numeral").unwrap_or_default()))
|
||||
},
|
||||
);
|
||||
let sign = g.named("sign");
|
||||
let mut whole = || g.named_as("decimal_numeral", "float_whole_part");
|
||||
let (w1, w2, w3) = (whole(), whole(), whole());
|
||||
let f1 = g.named_as("decimal_numeral", "float_fraction_part");
|
||||
let f2 = g.named_as("decimal_numeral", "float_fraction_part");
|
||||
let mut exp = || g.named("float_exponent_part");
|
||||
let (e1, e2, e3, e4) = (exp(), exp(), exp(), exp());
|
||||
let mut fs = || g.named("float_type_suffix");
|
||||
let (s1, s2, s3, s4) = (fs(), fs(), fs(), fs());
|
||||
g.put_term(
|
||||
"float_literal",
|
||||
seq(vec![
|
||||
opt(sign),
|
||||
alt(vec![
|
||||
seq(vec![w1, ch('.'), Term::Cut, opt(f1), opt(e1), opt(s1)]),
|
||||
seq(vec![ch('.'), Term::Cut, f2, opt(e2), opt(s2)]),
|
||||
seq(vec![w2, e3, Term::Cut, opt(s3)]),
|
||||
seq(vec![w3, opt(e4), s4]),
|
||||
]),
|
||||
]),
|
||||
|s| {
|
||||
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
|
||||
let mut text = String::new();
|
||||
if minus {
|
||||
text.push('-');
|
||||
}
|
||||
if let Some(w) = get_str(s, "float_whole_part") {
|
||||
text.extend(w.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
if let Some(f) = get_str(s, "float_fraction_part") {
|
||||
text.push('.');
|
||||
text.extend(f.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
if let Some(SV::Exp(m, d)) = s.scope.get("float_exponent_part") {
|
||||
text.push('e');
|
||||
if m {
|
||||
text.push('-');
|
||||
}
|
||||
text.extend(d.chars().filter(|c| *c != '_'));
|
||||
}
|
||||
let ty = match s.scope.get("float_type_suffix") {
|
||||
Some(SV::Type(t)) => Some(t),
|
||||
_ => None,
|
||||
};
|
||||
float_tag(&text, ty, s).map(SV::Tag)
|
||||
},
|
||||
);
|
||||
for (name, n) in [("string_hex_2", 2), ("string_hex_4", 4), ("string_hex_8", 8)] {
|
||||
g.put_custom(name, move |s| {
|
||||
greedy(
|
||||
s,
|
||||
hex,
|
||||
n,
|
||||
n,
|
||||
Reason::Delayed("snbt.parser.expected_hex_escape", vec![n.to_string()]),
|
||||
)
|
||||
});
|
||||
}
|
||||
g.put_custom("string_unicode_name", |s| {
|
||||
greedy(
|
||||
s,
|
||||
|c| c.is_ascii_alphanumeric() || c == '-' || c == ' ',
|
||||
1,
|
||||
usize::MAX,
|
||||
delayed("snbt.parser.invalid_character_name"),
|
||||
)
|
||||
});
|
||||
let esc = |c: char, v: &str| {
|
||||
seq(vec![
|
||||
ch(c),
|
||||
Term::Marker("string_escape_sequence", SV::Str(v.into())),
|
||||
])
|
||||
};
|
||||
let h2 = g.named("string_hex_2");
|
||||
let h4 = g.named("string_hex_4");
|
||||
let h8 = g.named("string_hex_8");
|
||||
let un = g.named("string_unicode_name");
|
||||
g.put_term(
|
||||
"string_escape_sequence",
|
||||
alt(vec![
|
||||
esc('b', "\u{8}"),
|
||||
esc('s', " "),
|
||||
esc('t', "\t"),
|
||||
esc('n', "\n"),
|
||||
esc('f', "\u{c}"),
|
||||
esc('r', "\r"),
|
||||
esc('\\', "\\"),
|
||||
esc('\'', "'"),
|
||||
esc('"', "\""),
|
||||
seq(vec![ch('x'), h2]),
|
||||
seq(vec![ch('u'), h4]),
|
||||
seq(vec![ch('U'), h8]),
|
||||
seq(vec![ch('N'), ch('{'), un, ch('}')]),
|
||||
]),
|
||||
|s| {
|
||||
if let Some(SV::Str(plain)) = s.scope.get_any(&["string_escape_sequence"]) {
|
||||
return Some(SV::Str(plain));
|
||||
}
|
||||
if let Some(SV::Str(h)) = s.scope.get_any(&["string_hex_2", "string_hex_4", "string_hex_8"])
|
||||
{
|
||||
let cp = u32::from_str_radix(&h, 16).unwrap_or(u32::MAX);
|
||||
if cp > 0x10ffff {
|
||||
s.store_at_mark(Reason::Delayed(
|
||||
"snbt.parser.invalid_codepoint",
|
||||
vec![format!("U+{cp:08X}")],
|
||||
));
|
||||
return None;
|
||||
}
|
||||
return Some(SV::Str(char::from_u32(cp).unwrap_or('\u{fffd}').to_string()));
|
||||
}
|
||||
// Character.codePointOf: Unicode names are not tabulated here.
|
||||
s.store_at_mark(delayed("snbt.parser.invalid_character_name"));
|
||||
None
|
||||
},
|
||||
);
|
||||
g.put_custom("string_plain_contents", |s| {
|
||||
greedy(
|
||||
s,
|
||||
|c| !matches!(c, '"' | '\'' | '\\'),
|
||||
1,
|
||||
usize::MAX,
|
||||
delayed("snbt.parser.invalid_string_contents"),
|
||||
)
|
||||
});
|
||||
for (chunk, contents, other) in [
|
||||
(
|
||||
"single_quoted_string_chunk",
|
||||
"single_quoted_string_contents",
|
||||
'"',
|
||||
),
|
||||
(
|
||||
"double_quoted_string_chunk",
|
||||
"double_quoted_string_contents",
|
||||
'\'',
|
||||
),
|
||||
] {
|
||||
let plain = g.named_as("string_plain_contents", "string_contents");
|
||||
let escape = g.named_as("string_escape_sequence", "string_contents");
|
||||
g.put_term(
|
||||
chunk,
|
||||
alt(vec![
|
||||
plain,
|
||||
seq(vec![ch('\\'), escape]),
|
||||
seq(vec![
|
||||
ch(other),
|
||||
Term::Marker("string_contents", SV::Str(other.to_string())),
|
||||
]),
|
||||
]),
|
||||
|s| s.scope.get("string_contents"),
|
||||
);
|
||||
let rule = g.id(chunk);
|
||||
g.put_term(
|
||||
contents,
|
||||
Term::Repeated {
|
||||
rule,
|
||||
list: "string_chunks",
|
||||
min: 0,
|
||||
},
|
||||
|s| {
|
||||
let mut out = String::new();
|
||||
for v in get_list(s, "string_chunks") {
|
||||
if let SV::Str(x) = v {
|
||||
out.push_str(&x);
|
||||
}
|
||||
}
|
||||
Some(SV::Str(out))
|
||||
},
|
||||
);
|
||||
}
|
||||
let dq = g.named_as("double_quoted_string_contents", "string_contents");
|
||||
let sq = g.named_as("single_quoted_string_contents", "string_contents");
|
||||
g.put_term(
|
||||
"quoted_string_literal",
|
||||
alt(vec![
|
||||
seq(vec![ch('"'), Term::Cut, opt(dq), ch('"')]),
|
||||
seq(vec![ch('\''), opt(sq), ch('\'')]),
|
||||
]),
|
||||
|s| s.scope.get("string_contents"),
|
||||
);
|
||||
g.put_custom("unquoted_string", |s| {
|
||||
let mut r = s.reader();
|
||||
r.skip_whitespace();
|
||||
s.set_reader(&r);
|
||||
let cursor = s.cursor;
|
||||
let v = r.read_unquoted_string();
|
||||
s.set_reader(&r);
|
||||
if v.is_empty() {
|
||||
s.store(
|
||||
cursor,
|
||||
Sugg::Empty,
|
||||
delayed("snbt.parser.expected_unquoted_string"),
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(SV::Str(v.to_owned()))
|
||||
});
|
||||
let literal = g.id("literal");
|
||||
g.put_term(
|
||||
"arguments",
|
||||
Term::RepeatedSep {
|
||||
rule: literal,
|
||||
list: "arguments",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("arguments"),
|
||||
);
|
||||
let uq = g.named("unquoted_string");
|
||||
let args = g.named("arguments");
|
||||
g.put_term(
|
||||
"unquoted_string_or_builtin",
|
||||
seq(vec![uq, opt(seq(vec![ch('('), args, ch(')')]))]),
|
||||
|s| {
|
||||
let contents = get_str(s, "unquoted_string").unwrap_or_default();
|
||||
let first = contents.chars().next();
|
||||
if first.is_some_and(|c| !can_start_number(c)) {
|
||||
if let Some(SV::List(arguments)) = s.scope.get("arguments") {
|
||||
return builtin(&contents, arguments, s);
|
||||
}
|
||||
if contents.eq_ignore_ascii_case("true") {
|
||||
return Some(SV::Tag(Tag::Byte(1)));
|
||||
}
|
||||
if contents.eq_ignore_ascii_case("false") {
|
||||
return Some(SV::Tag(Tag::Byte(0)));
|
||||
}
|
||||
return Some(SV::Tag(Tag::String(JavaString::from(contents.as_str()))));
|
||||
}
|
||||
let ids = ["false", "true", "bool", "uuid"].map(String::from).to_vec();
|
||||
s.store(
|
||||
s.cursor,
|
||||
Sugg::Values(Rc::new(ids)),
|
||||
delayed("snbt.parser.invalid_unquoted_start"),
|
||||
);
|
||||
None
|
||||
},
|
||||
);
|
||||
let qs = g.named("quoted_string_literal");
|
||||
let uq = g.named("unquoted_string");
|
||||
g.put_term("map_key", alt(vec![qs, uq]), |s| {
|
||||
s.scope.get_any(&["quoted_string_literal", "unquoted_string"])
|
||||
});
|
||||
let key = g.named("map_key");
|
||||
let lit = g.named("literal");
|
||||
g.put_term("map_entry", seq(vec![key, ch(':'), lit]), |s| {
|
||||
let key = get_str(s, "map_key").unwrap_or_default();
|
||||
if key.is_empty() {
|
||||
s.store_at_mark(delayed("snbt.parser.empty_key"));
|
||||
return None;
|
||||
}
|
||||
let value = get_tag(s, "literal")?;
|
||||
Some(SV::Entry(key, value))
|
||||
});
|
||||
let entry = g.id("map_entry");
|
||||
g.put_term(
|
||||
"map_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: entry,
|
||||
list: "map_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("map_entries"),
|
||||
);
|
||||
let entries = g.named("map_entries");
|
||||
g.put_term("map_literal", seq(vec![ch('{'), entries, ch('}')]), |s| {
|
||||
let mut map = Compound::new();
|
||||
for e in get_list(s, "map_entries") {
|
||||
if let SV::Entry(k, v) = e {
|
||||
map.insert(JavaString::from(k.as_str()), v);
|
||||
}
|
||||
}
|
||||
Some(SV::Tag(Tag::Compound(map)))
|
||||
});
|
||||
g.put_term(
|
||||
"list_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: literal,
|
||||
list: "list_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("list_entries"),
|
||||
);
|
||||
g.put_term(
|
||||
"array_prefix",
|
||||
alt(vec![
|
||||
seq(vec![ch('B'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte))]),
|
||||
seq(vec![ch('L'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long))]),
|
||||
seq(vec![ch('I'), Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int))]),
|
||||
]),
|
||||
|s| s.scope.get("array_prefix"),
|
||||
);
|
||||
let int_lit = g.id("integer_literal");
|
||||
g.put_term(
|
||||
"int_array_entries",
|
||||
Term::RepeatedSep {
|
||||
rule: int_lit,
|
||||
list: "int_array_entries",
|
||||
sep: Box::new(ch(',')),
|
||||
min: 0,
|
||||
trailing: true,
|
||||
},
|
||||
|s| s.scope.get("int_array_entries"),
|
||||
);
|
||||
let prefix = g.named("array_prefix");
|
||||
let ia = g.named("int_array_entries");
|
||||
let le = g.named("list_entries");
|
||||
g.put_term(
|
||||
"list_literal",
|
||||
seq(vec![
|
||||
ch('['),
|
||||
alt(vec![seq(vec![prefix, ch(';'), ia]), le]),
|
||||
ch(']'),
|
||||
]),
|
||||
|s| {
|
||||
if let Some(SV::Prefix(p)) = s.scope.get("array_prefix") {
|
||||
let entries = get_list(s, "int_array_entries");
|
||||
return array(p, entries, s).map(SV::Tag);
|
||||
}
|
||||
let items: Vec<Tag> = get_list(s, "list_entries")
|
||||
.into_iter()
|
||||
.filter_map(|v| match v {
|
||||
SV::Tag(t) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Some(SV::Tag(Tag::List(items)))
|
||||
},
|
||||
);
|
||||
let float_lit = g.named_as("float_literal", "literal");
|
||||
let int_named = g.named("integer_literal");
|
||||
let quoted = g.named("quoted_string_literal");
|
||||
let map = g.named_as("map_literal", "literal");
|
||||
let list = g.named_as("list_literal", "literal");
|
||||
let builtin_term = g.named_as("unquoted_string_or_builtin", "literal");
|
||||
g.put_term(
|
||||
"literal",
|
||||
alt(vec![
|
||||
seq(vec![
|
||||
look(Term::Chars {
|
||||
values: Vec::new(),
|
||||
accept: Some(can_start_number),
|
||||
}),
|
||||
alt(vec![float_lit, int_named]),
|
||||
]),
|
||||
seq(vec![look(chs('"', '\'')), Term::Cut, quoted]),
|
||||
seq(vec![look(ch('{')), Term::Cut, map]),
|
||||
seq(vec![look(ch('[')), Term::Cut, list]),
|
||||
builtin_term,
|
||||
]),
|
||||
|s| {
|
||||
if let Some(q) = get_str(s, "quoted_string_literal") {
|
||||
return Some(SV::Tag(Tag::String(JavaString::from(q.as_str()))));
|
||||
}
|
||||
if let Some(SV::Int(i)) = s.scope.get("integer_literal") {
|
||||
let ty = i.ty.unwrap_or(TypeSuffix::Int);
|
||||
return i.create(ty, s).map(SV::Tag);
|
||||
}
|
||||
s.scope.get("literal")
|
||||
},
|
||||
);
|
||||
g.top = literal;
|
||||
g
|
||||
}
|
||||
|
||||
fn array(p: ArrayPrefix, entries: Vec<SV>, s: &mut State<SV>) -> Option<Tag> {
|
||||
let (default, allowed): (TypeSuffix, &[TypeSuffix]) = match p {
|
||||
ArrayPrefix::Byte => (TypeSuffix::Byte, &[]),
|
||||
ArrayPrefix::Int => (TypeSuffix::Int, &[TypeSuffix::Byte, TypeSuffix::Short]),
|
||||
ArrayPrefix::Long => (
|
||||
TypeSuffix::Long,
|
||||
&[TypeSuffix::Byte, TypeSuffix::Short, TypeSuffix::Int],
|
||||
),
|
||||
};
|
||||
let mut values: Vec<i64> = Vec::new();
|
||||
for e in entries {
|
||||
let SV::Int(lit) = e else { continue };
|
||||
let ty = match lit.ty {
|
||||
None => default,
|
||||
Some(t) if t == default || allowed.contains(&t) => t,
|
||||
Some(_) => {
|
||||
s.store_at_mark(delayed("snbt.parser.invalid_array_element_type"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let v = match lit.create(ty, s)? {
|
||||
Tag::Byte(v) => i64::from(v),
|
||||
Tag::Short(v) => i64::from(v),
|
||||
Tag::Int(v) => i64::from(v),
|
||||
Tag::Long(v) => v,
|
||||
_ => 0,
|
||||
};
|
||||
values.push(v);
|
||||
}
|
||||
Some(match p {
|
||||
ArrayPrefix::Byte => Tag::ByteArray(values.iter().map(|v| *v as i8 as u8).collect()),
|
||||
ArrayPrefix::Int => Tag::IntArray(values.iter().map(|v| *v as i32).collect()),
|
||||
ArrayPrefix::Long => Tag::LongArray(values),
|
||||
})
|
||||
}
|
||||
|
||||
fn builtin(id: &str, arguments: Vec<SV>, s: &mut State<SV>) -> Option<SV> {
|
||||
let args: Vec<Tag> = arguments
|
||||
.into_iter()
|
||||
.filter_map(|v| match v {
|
||||
SV::Tag(t) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
match (id, args.len()) {
|
||||
("bool", 1) => {
|
||||
let b = match &args[0] {
|
||||
Tag::Byte(v) => Some(*v != 0),
|
||||
Tag::Short(v) => Some(*v != 0),
|
||||
Tag::Int(v) => Some(*v != 0),
|
||||
Tag::Long(v) => Some(*v != 0),
|
||||
Tag::Float(v) => Some(f32::from_bits(*v) != 0.0),
|
||||
Tag::Double(v) => Some(f64::from_bits(*v) != 0.0),
|
||||
_ => None,
|
||||
};
|
||||
match b {
|
||||
Some(b) => Some(SV::Tag(Tag::Byte(i8::from(b)))),
|
||||
None => {
|
||||
s.store_at_mark(delayed("snbt.parser.expected_number_or_boolean"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
("uuid", 1) => {
|
||||
let parsed = match &args[0] {
|
||||
Tag::String(text) => super::selector::java_uuid(&text.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
match parsed {
|
||||
Some(u) => Some(SV::Tag(Tag::IntArray(vec![
|
||||
(u >> 96) as u32 as i32,
|
||||
(u >> 64) as u32 as i32,
|
||||
(u >> 32) as u32 as i32,
|
||||
u as u32 as i32,
|
||||
]))),
|
||||
None => {
|
||||
s.store_at_mark(delayed("snbt.parser.expected_string_uuid"));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
s.store_at_mark(Reason::Delayed(
|
||||
"snbt.parser.no_such_operation",
|
||||
vec![format!("{id}/{}", args.len())],
|
||||
));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GRAMMAR: Grammar<SV> = grammar();
|
||||
}
|
||||
|
||||
/// TagParser.parseAsArgument: one SNBT value at the reader's cursor.
|
||||
pub fn parse_tag_argument(reader: &mut Reader) -> CmdResult<Tag> {
|
||||
GRAMMAR.with(|g| match g.parse_for_commands(reader)? {
|
||||
SV::Tag(t) => Ok(t),
|
||||
_ => Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)),
|
||||
})
|
||||
}
|
||||
/// TagParser.parseCompoundAsArgument.
|
||||
pub fn parse_compound_argument(reader: &mut Reader) -> CmdResult<Compound> {
|
||||
match parse_tag_argument(reader)? {
|
||||
Tag::Compound(c) => Ok(c),
|
||||
_ => Err(CommandError::tr_at(
|
||||
"argument.nbt.expected.compound",
|
||||
&[],
|
||||
reader,
|
||||
)),
|
||||
}
|
||||
}
|
||||
/// TagParser.parseFully.
|
||||
pub fn parse_fully(text: &str) -> CmdResult<Tag> {
|
||||
let mut reader = Reader::new(text);
|
||||
let tag = parse_tag_argument(&mut reader)?;
|
||||
reader.skip_whitespace();
|
||||
if reader.can_read() {
|
||||
return Err(CommandError::tr_at("argument.nbt.trailing", &[], &reader));
|
||||
}
|
||||
Ok(tag)
|
||||
}
|
||||
/// The grammar's completion suggestions (ParserBasedArgument.listSuggestions).
|
||||
pub fn suggest(builder: &mut SuggestionsBuilder) {
|
||||
GRAMMAR.with(|g| g.parse_for_suggestions(builder));
|
||||
}
|
||||
/// Parse with an outer state (TagParseRule inside another grammar).
|
||||
pub fn rule_in<V: super::packrat::Value>(
|
||||
state: &mut State<V>,
|
||||
wrap: impl Fn(Tag) -> V,
|
||||
) -> Option<V> {
|
||||
let mut r = state.reader();
|
||||
r.skip_whitespace();
|
||||
state.set_reader(&r);
|
||||
let mark = state.cursor;
|
||||
let mut reader = state.reader();
|
||||
match parse_tag_argument(&mut reader) {
|
||||
Ok(t) => {
|
||||
state.set_reader(&reader);
|
||||
Some(wrap(t))
|
||||
}
|
||||
Err(e) => {
|
||||
state.store(mark, Sugg::Empty, Reason::Error(e));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _rule_kind(_: Rule<SV>) {}
|
||||
@@ -27,6 +27,34 @@ fn reg() -> Registries {
|
||||
r.players = vec!["Player".into()];
|
||||
r.dimensions = vec!["minecraft:overworld".into()];
|
||||
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
|
||||
// The registry elements the commands below name (vanilla checks them while parsing).
|
||||
let mut registry = |name: &str, ids: &[&str]| {
|
||||
r.by_registry.insert(
|
||||
name.into(),
|
||||
RegistryIds {
|
||||
ids: ids.iter().map(|s| (*s).to_owned()).collect(),
|
||||
tags: Vec::new(),
|
||||
},
|
||||
);
|
||||
};
|
||||
registry("minecraft:worldgen/biome", &["minecraft:desert", "minecraft:plains"]);
|
||||
registry("minecraft:damage_type", &["minecraft:fall", "minecraft:magic"]);
|
||||
registry("minecraft:attribute", &["minecraft:max_health", "minecraft:scale"]);
|
||||
registry("minecraft:item_modifier", &["a:b"]);
|
||||
registry("minecraft:predicate", &["a:b"]);
|
||||
registry(
|
||||
"minecraft:loot_table",
|
||||
&[
|
||||
"minecraft:chests/simple_dungeon",
|
||||
"minecraft:chests/x",
|
||||
"minecraft:gameplay/fishing",
|
||||
],
|
||||
);
|
||||
registry(
|
||||
"minecraft:entity_type",
|
||||
&["minecraft:pig", "minecraft:player", "minecraft:zombie"],
|
||||
);
|
||||
registry("minecraft:item", &["minecraft:diamond", "minecraft:diamond_sword", "minecraft:stone"]);
|
||||
r
|
||||
}
|
||||
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
|
||||
@@ -127,7 +155,8 @@ fn vanilla_error_messages() {
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
let e = run("gamemode creatve").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
|
||||
assert_eq!(e.cursor, 9);
|
||||
// GameModeArgument reports the error after the word.
|
||||
assert_eq!(e.cursor, 16);
|
||||
let e = run("give @s minecraft:dirt").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.item.id.invalid");
|
||||
let e = run("give @s diamond 0").unwrap_err();
|
||||
@@ -161,7 +190,11 @@ fn suggestions_like_vanilla() {
|
||||
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
|
||||
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]);
|
||||
// BlockStateParser suggests every value of the property, unfiltered.
|
||||
assert_eq!(
|
||||
suggestions("setblock 0 0 0 oak_stairs[facing=n"),
|
||||
["north", "south"]
|
||||
);
|
||||
assert_eq!(
|
||||
suggestions("tp "),
|
||||
[
|
||||
@@ -400,10 +433,10 @@ fn world_command_trees() {
|
||||
("stopsound @s music minecraft:music.game", "stopsound"),
|
||||
("particle minecraft:smoke", "particle"),
|
||||
(
|
||||
"particle minecraft:dust 1 0 0 2 ~ ~ ~ 0.1 0.1 0.1 0 10 force @a",
|
||||
"particle minecraft:dust{color:[1.0,0.0,0.0],scale:2.0} ~ ~ ~ 0.1 0.1 0.1 0 10 force @a",
|
||||
"particle",
|
||||
),
|
||||
("particle minecraft:block minecraft:stone ~ ~ ~", "particle"),
|
||||
("particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~", "particle"),
|
||||
("attribute @s minecraft:max_health get 2", "attribute.get"),
|
||||
(
|
||||
"attribute @s minecraft:max_health base set 40",
|
||||
|
||||
@@ -29,7 +29,45 @@ fn providers(
|
||||
then(d, a);
|
||||
}
|
||||
|
||||
/// LootContextSources.addContextSources: `default`, `block <computePos>`
|
||||
/// and `entity <computeTarget>`, each completed by `then`.
|
||||
pub fn context_sources(
|
||||
d: &mut Dispatcher,
|
||||
node: usize,
|
||||
then: &mut dyn FnMut(&mut Dispatcher, usize),
|
||||
) {
|
||||
let default = d.literal(node, "default");
|
||||
then(d, default);
|
||||
let block = d.literal(node, "block");
|
||||
let pos = d.argument(block, "computePos", ArgType::BlockPos);
|
||||
then(d, pos);
|
||||
let entity = d.literal(node, "entity");
|
||||
let target = d.argument(entity, "computeTarget", ENTITY);
|
||||
then(d, target);
|
||||
}
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// compute (default | block <pos> | entity <target>) (float <provider> [<scale>] | integer <provider>)
|
||||
let compute = d.literal(root, "compute");
|
||||
d.requires(compute, GAMEMASTERS);
|
||||
context_sources(d, compute, &mut |d, node| {
|
||||
let f = d.literal(node, "float");
|
||||
let p = d.argument(f, "provider", ArgType::ResourceOrId("minecraft:context_float_provider"));
|
||||
d.executes(p, "compute");
|
||||
let scale = d.argument(
|
||||
p,
|
||||
"scale",
|
||||
ArgType::Float {
|
||||
min: f32::MIN,
|
||||
max: f32::MAX,
|
||||
},
|
||||
);
|
||||
d.executes(scale, "compute");
|
||||
let i = d.literal(node, "integer");
|
||||
let p = d.argument(i, "provider", ArgType::ResourceOrId("minecraft:context_int_provider"));
|
||||
d.executes(p, "compute");
|
||||
});
|
||||
|
||||
let data = d.literal(root, "data");
|
||||
d.requires(data, GAMEMASTERS);
|
||||
|
||||
@@ -97,6 +135,17 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let end = d.argument(start, "end", int());
|
||||
d.executes(end, "data.modify");
|
||||
});
|
||||
let compute = d.literal(op, "compute");
|
||||
context_sources(d, compute, &mut |d, node| {
|
||||
for (kind, registry) in [
|
||||
("float", "minecraft:context_float_provider"),
|
||||
("integer", "minecraft:context_int_provider"),
|
||||
] {
|
||||
let k = d.literal(node, kind);
|
||||
let p = d.argument(k, "provider", ArgType::ResourceOrId(registry));
|
||||
d.executes(p, "data.modify");
|
||||
}
|
||||
});
|
||||
let value = d.literal(op, "value");
|
||||
let v = d.argument(value, "value", ArgType::NbtTag);
|
||||
d.executes(v, "data.modify");
|
||||
|
||||
@@ -7,11 +7,12 @@ use super::{
|
||||
vanilla::{ENTITIES, GAMEMASTERS},
|
||||
};
|
||||
|
||||
/// HeightmapTypeArgument: the types kept after world generation.
|
||||
pub const HEIGHTMAPS: &[&str] = &[
|
||||
"world_surface",
|
||||
"ocean_floor",
|
||||
"motion_blocking",
|
||||
"motion_blocking_no_leaves",
|
||||
"ocean_floor",
|
||||
];
|
||||
pub const RELATIONS: [&str; 8] = [
|
||||
"owner",
|
||||
@@ -47,7 +48,7 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let t = d.argument(as_, "targets", ENTITIES);
|
||||
d.redirect(t, ex);
|
||||
let over = d.literal(positioned, "over");
|
||||
let hm = d.argument(over, "heightmap", ArgType::Enum(HEIGHTMAPS));
|
||||
let hm = d.argument(over, "heightmap", ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid"));
|
||||
d.redirect(hm, ex);
|
||||
let rotated = d.literal(ex, "rotated");
|
||||
let rot = d.argument(rotated, "rot", ArgType::Rotation);
|
||||
@@ -73,6 +74,7 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
d.redirect(dim, ex);
|
||||
let summon = d.literal(ex, "summon");
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.suggests(e, super::Suggests::SummonableEntities);
|
||||
d.redirect(e, ex);
|
||||
let on = d.literal(ex, "on");
|
||||
for r in RELATIONS {
|
||||
@@ -139,7 +141,7 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
|
||||
let biome = d.literal(m, "biome");
|
||||
let pos = d.argument(biome, "pos", ArgType::BlockPos);
|
||||
let b = d.argument(pos, "biome", ArgType::Resource(Resource::Biome));
|
||||
let b = d.argument(pos, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
|
||||
conditional(d, b, ex);
|
||||
|
||||
let loaded = d.literal(m, "loaded");
|
||||
@@ -177,7 +179,7 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
conditional(d, targets, ex);
|
||||
|
||||
let predicate = d.literal(m, "predicate");
|
||||
let p = d.argument(predicate, "predicate", ArgType::Id("predicates"));
|
||||
let p = d.argument(predicate, "predicate", ArgType::ResourceOrId("minecraft:predicate"));
|
||||
conditional(d, p, ex);
|
||||
|
||||
let stopwatch = d.literal(m, "stopwatch");
|
||||
@@ -187,7 +189,9 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
|
||||
let function = d.literal(m, "function");
|
||||
let name = d.argument(function, "name", ArgType::Function);
|
||||
conditional(d, name, ex);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
// ExecuteIfFunctionCustomModifier: a fork only (not a test command).
|
||||
d.redirect(name, ex);
|
||||
|
||||
let data = d.literal(m, "data");
|
||||
for provider in ["entity", "block", "storage"] {
|
||||
@@ -225,7 +229,7 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
|
||||
} else {
|
||||
d.argument(p, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(a, "slots", ArgType::Slots);
|
||||
let slots = d.argument(a, "slots", ArgType::SlotSource);
|
||||
if kind == "items" {
|
||||
let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate);
|
||||
conditional(d, item, ex);
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Commands Horizon parses but does not run (multiplayer, profiling and
|
||||
//! server-only features): `/dialog`, `/kick`, `/posteffect`, `/fetchprofile`,
|
||||
//! `/spectate`, `/publish`, `/unpublish`, `/waypoint`, `/debug`, `/jfr` and
|
||||
//! the `/test` root.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::ArgType,
|
||||
vanilla::{ENTITY, GAMEMASTERS, PLAYER, PLAYERS},
|
||||
};
|
||||
|
||||
const ADMINS: u8 = 3;
|
||||
const OWNERS: u8 = 4;
|
||||
|
||||
pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// DialogCommand
|
||||
let dialog = d.literal(root, "dialog");
|
||||
d.requires(dialog, GAMEMASTERS);
|
||||
let show = d.literal(dialog, "show");
|
||||
let t = d.argument(show, "targets", PLAYERS);
|
||||
let dl = d.argument(t, "dialog", ArgType::ResourceOrId("minecraft:dialog"));
|
||||
d.executes(dl, "dialog.show");
|
||||
let clear = d.literal(dialog, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "dialog.clear");
|
||||
|
||||
// KickCommand
|
||||
let kick = d.literal(root, "kick");
|
||||
d.requires(kick, ADMINS);
|
||||
let t = d.argument(kick, "targets", PLAYERS);
|
||||
d.executes(t, "kick");
|
||||
let reason = d.argument(t, "reason", ArgType::Message);
|
||||
d.executes(reason, "kick");
|
||||
|
||||
// PostEffectCommand
|
||||
let pe = d.literal(root, "posteffect");
|
||||
d.requires(pe, GAMEMASTERS);
|
||||
let add = d.literal(pe, "add");
|
||||
let t = d.argument(add, "targets", PLAYERS);
|
||||
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
|
||||
d.executes(id, "posteffect.add");
|
||||
let clear = d.literal(pe, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "posteffect.clear");
|
||||
let list = d.literal(pe, "list");
|
||||
let t = d.argument(list, "target", PLAYER);
|
||||
d.executes(t, "posteffect.list");
|
||||
let remove = d.literal(pe, "remove");
|
||||
let t = d.argument(remove, "targets", PLAYERS);
|
||||
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
|
||||
d.executes(id, "posteffect.remove");
|
||||
|
||||
// FetchProfileCommand
|
||||
let fp = d.literal(root, "fetchprofile");
|
||||
d.requires(fp, GAMEMASTERS);
|
||||
let name = d.literal(fp, "name");
|
||||
let n = d.argument(name, "name", ArgType::Greedy);
|
||||
d.executes(n, "fetchprofile");
|
||||
let id = d.literal(fp, "id");
|
||||
let u = d.argument(id, "id", ArgType::Uuid);
|
||||
d.executes(u, "fetchprofile");
|
||||
let entity = d.literal(fp, "entity");
|
||||
let e = d.argument(entity, "entity", ENTITY);
|
||||
d.executes(e, "fetchprofile");
|
||||
|
||||
// SpectateCommand
|
||||
let spectate = d.literal(root, "spectate");
|
||||
d.requires(spectate, GAMEMASTERS);
|
||||
d.executes(spectate, "spectate");
|
||||
let target = d.argument(spectate, "target", ENTITY);
|
||||
d.executes(target, "spectate");
|
||||
let player = d.argument(target, "player", PLAYER);
|
||||
d.executes(player, "spectate");
|
||||
|
||||
// PublishCommand / UnpublishCommand
|
||||
let publish = d.literal(root, "publish");
|
||||
d.requires(publish, OWNERS);
|
||||
d.executes(publish, "publish");
|
||||
let allow = d.argument(publish, "allowCommands", ArgType::Bool);
|
||||
d.executes(allow, "publish");
|
||||
let port = d.argument(allow, "port", ArgType::Integer { min: 0, max: 65535 });
|
||||
d.executes(port, "publish");
|
||||
let unpublish = d.literal(root, "unpublish");
|
||||
d.requires(unpublish, OWNERS);
|
||||
d.executes(unpublish, "unpublish");
|
||||
|
||||
// WaypointCommand
|
||||
let wp = d.literal(root, "waypoint");
|
||||
d.requires(wp, GAMEMASTERS);
|
||||
let list = d.literal(wp, "list");
|
||||
d.executes(list, "waypoint.list");
|
||||
let modify = d.literal(wp, "modify");
|
||||
let w = d.argument(modify, "waypoint", ENTITY);
|
||||
let color = d.literal(w, "color");
|
||||
let c = d.argument(color, "color", ArgType::TeamColor);
|
||||
d.executes(c, "waypoint.modify");
|
||||
let hex = d.literal(color, "hex");
|
||||
let h = d.argument(hex, "color", ArgType::HexColor);
|
||||
d.executes(h, "waypoint.modify");
|
||||
let reset = d.literal(color, "reset");
|
||||
d.executes(reset, "waypoint.modify");
|
||||
let style = d.literal(w, "style");
|
||||
let reset = d.literal(style, "reset");
|
||||
d.executes(reset, "waypoint.modify");
|
||||
let set = d.literal(style, "set");
|
||||
let st = d.argument(set, "style", ArgType::Id("none"));
|
||||
d.executes(st, "waypoint.modify");
|
||||
|
||||
// DebugCommand
|
||||
let debug = d.literal(root, "debug");
|
||||
d.requires(debug, ADMINS);
|
||||
for name in ["start", "stop"] {
|
||||
let l = d.literal(debug, name);
|
||||
d.executes(l, "debug");
|
||||
}
|
||||
let function = d.literal(debug, "function");
|
||||
d.requires(function, ADMINS);
|
||||
let n = d.argument(function, "name", ArgType::Function);
|
||||
d.suggests(n, super::Suggests::Functions);
|
||||
d.executes(n, "debug");
|
||||
|
||||
// JfrCommand (registered when the JVM profiler is available)
|
||||
let jfr = d.literal(root, "jfr");
|
||||
d.requires(jfr, OWNERS);
|
||||
for name in ["start", "stop"] {
|
||||
let l = d.literal(jfr, name);
|
||||
d.executes(l, "jfr");
|
||||
}
|
||||
|
||||
// TestCommand (game tests; only its root is modelled)
|
||||
let test = d.literal(root, "test");
|
||||
d.requires(test, GAMEMASTERS);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
d.requires(schedule, GAMEMASTERS);
|
||||
let f = d.literal(schedule, "function");
|
||||
let name = d.argument(f, "function", ArgType::Function);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
let time = d.argument(name, "time", ArgType::Time { min: 0 });
|
||||
d.executes(time, "schedule.function");
|
||||
for mode in ["append", "replace"] {
|
||||
@@ -92,17 +93,20 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
max: 10000.0,
|
||||
},
|
||||
);
|
||||
d.suggests(r, super::Suggests::Fixed(&["20"]));
|
||||
d.executes(r, "tick.rate");
|
||||
let step = d.literal(tick, "step");
|
||||
d.executes(step, "tick.step");
|
||||
let stop = d.literal(step, "stop");
|
||||
d.executes(stop, "tick.step.stop");
|
||||
let t = d.argument(step, "time", ArgType::Time { min: 1 });
|
||||
d.suggests(t, super::Suggests::Fixed(&["1t", "1s"]));
|
||||
d.executes(t, "tick.step");
|
||||
let sprint = d.literal(tick, "sprint");
|
||||
let stop = d.literal(sprint, "stop");
|
||||
d.executes(stop, "tick.sprint.stop");
|
||||
let t = d.argument(sprint, "time", ArgType::Time { min: 1 });
|
||||
d.suggests(t, super::Suggests::Fixed(&["60s", "1d", "3d"]));
|
||||
d.executes(t, "tick.sprint");
|
||||
let unfreeze = d.literal(tick, "unfreeze");
|
||||
d.executes(unfreeze, "tick.unfreeze");
|
||||
@@ -142,6 +146,11 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let other = d.argument(l, "existing", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(other, "datapack.enable");
|
||||
}
|
||||
let create = d.literal(datapack, "create");
|
||||
d.requires(create, 4);
|
||||
let id = d.argument(create, "id", ArgType::Str);
|
||||
let description = d.argument(id, "description", ArgType::Component);
|
||||
d.executes(description, "datapack.create");
|
||||
let disable = d.literal(datapack, "disable");
|
||||
let name = d.argument(disable, "name", ArgType::Name("datapacks_enabled"));
|
||||
d.executes(name, "datapack.disable");
|
||||
@@ -159,8 +168,8 @@ fn item(d: &mut Dispatcher, root: usize) {
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slot = d.argument(target, "slot", ArgType::Slot);
|
||||
let modifier = d.argument(slot, "modifier", ArgType::Id("item_modifiers"));
|
||||
let slot = d.argument(target, "slot", ArgType::SlotSource);
|
||||
let modifier = d.argument(slot, "modifier", ArgType::ResourceOrId("minecraft:item_modifier"));
|
||||
d.executes(modifier, "item.modify");
|
||||
}
|
||||
for mode in ["replace", "fill", "override"] {
|
||||
@@ -172,7 +181,7 @@ fn item(d: &mut Dispatcher, root: usize) {
|
||||
} else {
|
||||
d.argument(p, "targetPos", ArgType::BlockPos)
|
||||
};
|
||||
let slots = d.argument(target, "slots", ArgType::Slots);
|
||||
let slots = d.argument(target, "slots", ArgType::SlotSource);
|
||||
let with = d.literal(slots, "with");
|
||||
let it = d.argument(with, "item", ArgType::Item);
|
||||
d.executes(it, "item");
|
||||
@@ -186,8 +195,14 @@ fn item(d: &mut Dispatcher, root: usize) {
|
||||
} else {
|
||||
d.argument(s, "sourcePos", ArgType::BlockPos)
|
||||
};
|
||||
let source_slots = d.argument(source, "sourceSlots", ArgType::Slots);
|
||||
let source_slots = d.argument(source, "sourceSlots", ArgType::SlotSource);
|
||||
d.executes(source_slots, "item");
|
||||
let modifier = d.argument(
|
||||
source_slots,
|
||||
"modifier",
|
||||
ArgType::ResourceOrId("minecraft:item_modifier"),
|
||||
);
|
||||
d.executes(modifier, "item");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +260,7 @@ fn function(d: &mut Dispatcher, root: usize) {
|
||||
let f = d.literal(root, "function");
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let name = d.argument(f, "name", ArgType::Function);
|
||||
d.suggests(name, super::Suggests::Functions);
|
||||
d.executes(name, "function");
|
||||
let args = d.argument(name, "arguments", ArgType::Nbt);
|
||||
d.executes(args, "function");
|
||||
|
||||
@@ -15,7 +15,7 @@ fn number_formats(d: &mut Dispatcher, top: usize, id: &'static str) {
|
||||
let contents = d.argument(fixed, "contents", ArgType::Component);
|
||||
d.executes(contents, id);
|
||||
let styled = d.literal(top, "styled");
|
||||
let style = d.argument(styled, "style", ArgType::Component);
|
||||
let style = d.argument(styled, "style", ArgType::Style);
|
||||
d.executes(style, id);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// trigger <objective> [add|set <value>]
|
||||
let trigger = d.literal(root, "trigger");
|
||||
let objective = d.argument(trigger, "objective", ArgType::Objective);
|
||||
d.suggests(objective, super::Suggests::Triggers);
|
||||
d.executes(objective, "trigger");
|
||||
for mode in ["add", "set"] {
|
||||
let m = d.literal(objective, mode);
|
||||
@@ -114,6 +115,7 @@ fn scoreboard(d: &mut Dispatcher, root: usize) {
|
||||
let enable = d.literal(players, "enable");
|
||||
let t = d.argument(enable, "targets", HOLDERS);
|
||||
let o = d.argument(t, "objective", ArgType::Objective);
|
||||
d.suggests(o, super::Suggests::EnableTriggers);
|
||||
d.executes(o, "scoreboard.players.enable");
|
||||
let display = d.literal(players, "display");
|
||||
let name = d.literal(display, "name");
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! `/fillbiome`, `/worldborder`.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, Resource, integer},
|
||||
args::{ArgType, integer},
|
||||
vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS},
|
||||
};
|
||||
use crate::settings::SOUND_SOURCES;
|
||||
@@ -55,6 +55,23 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
// place template <template> [<pos> [<rotation> [<mirror> [<integrity> [<seed> [strict]]]]]]
|
||||
let place = d.literal(root, "place");
|
||||
d.requires(place, GAMEMASTERS);
|
||||
let feature = d.literal(place, "feature");
|
||||
let f = d.argument(feature, "feature", ArgType::ResourceOrId("minecraft:worldgen/feature"));
|
||||
d.executes(f, "place.feature");
|
||||
let pos = d.argument(f, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place.feature");
|
||||
let jigsaw = d.literal(place, "jigsaw");
|
||||
let pool = d.argument(jigsaw, "pool", ArgType::ResKey("minecraft:worldgen/template_pool"));
|
||||
let target = d.argument(pool, "target", ArgType::Id("none"));
|
||||
let depth = d.argument(target, "max_depth", ArgType::Integer { min: 1, max: 20 });
|
||||
d.executes(depth, "place.jigsaw");
|
||||
let position = d.argument(depth, "position", ArgType::BlockPos);
|
||||
d.executes(position, "place.jigsaw");
|
||||
let structure = d.literal(place, "structure");
|
||||
let st = d.argument(structure, "structure", ArgType::ResKey("minecraft:worldgen/structure"));
|
||||
d.executes(st, "place.structure");
|
||||
let pos = d.argument(st, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "place.structure");
|
||||
let template = d.literal(place, "template");
|
||||
let id = d.argument(template, "template", ArgType::Id("templates"));
|
||||
d.executes(id, "place");
|
||||
@@ -63,13 +80,16 @@ pub fn register(d: &mut Dispatcher, root: usize) {
|
||||
let rotation = d.argument(
|
||||
pos,
|
||||
"rotation",
|
||||
ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"]),
|
||||
ArgType::StrEnum(
|
||||
&["none", "clockwise_90", "180", "counterclockwise_90"],
|
||||
"argument.enum.invalid",
|
||||
),
|
||||
);
|
||||
d.executes(rotation, "place");
|
||||
let mirror = d.argument(
|
||||
rotation,
|
||||
"mirror",
|
||||
ArgType::Enum(&["none", "left_right", "front_back"]),
|
||||
ArgType::StrEnum(&["none", "left_right", "front_back"], "argument.enum.invalid"),
|
||||
);
|
||||
d.executes(mirror, "place");
|
||||
let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 });
|
||||
@@ -91,7 +111,7 @@ fn recipe(d: &mut Dispatcher, root: usize) {
|
||||
for (word, id) in [("give", "recipe.give"), ("take", "recipe.take")] {
|
||||
let w = d.literal(recipe, word);
|
||||
let t = d.argument(w, "targets", PLAYERS);
|
||||
let r = d.argument(t, "recipe", ArgType::Id("recipes"));
|
||||
let r = d.argument(t, "recipe", ArgType::ResKey("minecraft:recipe"));
|
||||
d.executes(r, id);
|
||||
let all = d.literal(t, "*");
|
||||
d.executes(all, id);
|
||||
@@ -104,7 +124,7 @@ fn damage(d: &mut Dispatcher, root: usize) {
|
||||
let target = d.argument(damage, "target", ENTITY);
|
||||
let amount = d.argument(target, "amount", float(0.0));
|
||||
d.executes(amount, "damage");
|
||||
let ty = d.argument(amount, "damageType", ArgType::Id("damage_types"));
|
||||
let ty = d.argument(amount, "damageType", ArgType::Res("minecraft:damage_type"));
|
||||
d.executes(ty, "damage");
|
||||
let at = d.literal(ty, "at");
|
||||
let loc = d.argument(at, "location", ArgType::Vec3 { center: true });
|
||||
@@ -140,7 +160,7 @@ fn rotate_swing(d: &mut Dispatcher, root: usize) {
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(targets, hand);
|
||||
d.executes(h, "swing");
|
||||
let animation = d.argument(h, "animation", ArgType::Enum(&["none", "whack", "stab"]));
|
||||
let animation = d.argument(h, "animation", ArgType::StrEnum(&["none", "whack", "stab"], "argument.swing_animation.invalid"));
|
||||
d.executes(animation, "swing");
|
||||
let duration = d.argument(animation, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(duration, "swing");
|
||||
@@ -203,7 +223,7 @@ fn attribute(d: &mut Dispatcher, root: usize) {
|
||||
let attribute = d.literal(root, "attribute");
|
||||
d.requires(attribute, GAMEMASTERS);
|
||||
let target = d.argument(attribute, "target", ENTITY);
|
||||
let attr = d.argument(target, "attribute", ArgType::Id("attributes"));
|
||||
let attr = d.argument(target, "attribute", ArgType::Res("minecraft:attribute"));
|
||||
let get = d.literal(attr, "get");
|
||||
d.executes(get, "attribute.get");
|
||||
let scale = d.argument(get, "scale", double());
|
||||
@@ -262,10 +282,10 @@ fn fillbiome(d: &mut Dispatcher, root: usize) {
|
||||
d.requires(f, GAMEMASTERS);
|
||||
let from = d.argument(f, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let biome = d.argument(to, "biome", ArgType::Resource(Resource::Biome));
|
||||
let biome = d.argument(to, "biome", ArgType::Res("minecraft:worldgen/biome"));
|
||||
d.executes(biome, "fillbiome");
|
||||
let replace = d.literal(biome, "replace");
|
||||
let filter = d.argument(replace, "filter", ArgType::Resource(Resource::Biome));
|
||||
let filter = d.argument(replace, "filter", ArgType::ResOrTag("minecraft:worldgen/biome"));
|
||||
d.executes(filter, "fillbiome");
|
||||
}
|
||||
|
||||
@@ -273,8 +293,8 @@ fn worldborder(d: &mut Dispatcher, root: usize) {
|
||||
let w = d.literal(root, "worldborder");
|
||||
d.requires(w, GAMEMASTERS);
|
||||
let dist = || ArgType::Double {
|
||||
min: -5.999_997e7,
|
||||
max: 5.999_997e7,
|
||||
min: -5.999_996_8e7,
|
||||
max: 5.999_996_8e7,
|
||||
};
|
||||
for word in ["add", "set"] {
|
||||
let l = d.literal(w, word);
|
||||
@@ -337,17 +357,17 @@ fn loot(d: &mut Dispatcher, root: usize) {
|
||||
// Sources.
|
||||
for t in targets {
|
||||
let fish = d.literal(t, "fish");
|
||||
let table = d.argument(fish, "loot_table", ArgType::Id("loot_tables"));
|
||||
let table = d.argument(fish, "loot_table", ArgType::ResourceOrId("minecraft:loot_table"));
|
||||
let pos = d.argument(table, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "loot.fish");
|
||||
for hand in ["mainhand", "offhand"] {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.fish");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::ItemPredicate);
|
||||
let tool = d.argument(pos, "tool", ArgType::Item);
|
||||
d.executes(tool, "loot.fish");
|
||||
let l = d.literal(t, "loot");
|
||||
let lt = d.argument(l, "loot_table", ArgType::Id("loot_tables"));
|
||||
let lt = d.argument(l, "loot_table", ArgType::ResourceOrId("minecraft:loot_table"));
|
||||
d.executes(lt, "loot.loot");
|
||||
let kill = d.literal(t, "kill");
|
||||
let target = d.argument(kill, "target", ENTITY);
|
||||
@@ -359,7 +379,7 @@ fn loot(d: &mut Dispatcher, root: usize) {
|
||||
let h = d.literal(pos, hand);
|
||||
d.executes(h, "loot.mine");
|
||||
}
|
||||
let tool = d.argument(pos, "tool", ArgType::ItemPredicate);
|
||||
let tool = d.argument(pos, "tool", ArgType::Item);
|
||||
d.executes(tool, "loot.mine");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,11 @@ pub const ENTITY: ArgType = ArgType::Entity {
|
||||
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
|
||||
|
||||
pub fn build() -> Dispatcher {
|
||||
build_with(true)
|
||||
}
|
||||
/// The tree Commands registers; `dev` adds the commands vanilla only
|
||||
/// registers in development builds (raid, warden_spawn_tracker).
|
||||
pub fn build_with(dev: bool) -> Dispatcher {
|
||||
let mut d = Dispatcher::new();
|
||||
let root = 0;
|
||||
|
||||
@@ -111,27 +116,29 @@ pub fn build() -> Dispatcher {
|
||||
d.executes(dur, "weather");
|
||||
}
|
||||
|
||||
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
|
||||
let raid = d.literal(root, "raid");
|
||||
d.requires(raid, 3);
|
||||
let start = d.literal(raid, "start");
|
||||
let level = d.argument(start, "omenlvl", integer(0));
|
||||
d.executes(level, "raid.start");
|
||||
for (name, id) in [
|
||||
("stop", "raid.stop"),
|
||||
("check", "raid.check"),
|
||||
("spawnleader", "raid.spawnleader"),
|
||||
("glow", "raid.glow"),
|
||||
] {
|
||||
let n = d.literal(raid, name);
|
||||
d.executes(n, id);
|
||||
if dev {
|
||||
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
|
||||
let raid = d.literal(root, "raid");
|
||||
d.requires(raid, 3);
|
||||
let start = d.literal(raid, "start");
|
||||
let level = d.argument(start, "omenlvl", integer(0));
|
||||
d.executes(level, "raid.start");
|
||||
for (name, id) in [
|
||||
("stop", "raid.stop"),
|
||||
("check", "raid.check"),
|
||||
("spawnleader", "raid.spawnleader"),
|
||||
("glow", "raid.glow"),
|
||||
] {
|
||||
let n = d.literal(raid, name);
|
||||
d.executes(n, id);
|
||||
}
|
||||
let sound = d.literal(raid, "sound");
|
||||
let kind = d.argument(sound, "type", ArgType::Greedy);
|
||||
d.executes(kind, "raid.sound");
|
||||
let setomen = d.literal(raid, "setomen");
|
||||
let level = d.argument(setomen, "level", integer(0));
|
||||
d.executes(level, "raid.setomen");
|
||||
}
|
||||
let sound = d.literal(raid, "sound");
|
||||
let kind = d.argument(sound, "type", ArgType::Greedy);
|
||||
d.executes(kind, "raid.sound");
|
||||
let setomen = d.literal(raid, "setomen");
|
||||
let level = d.argument(setomen, "level", integer(0));
|
||||
d.executes(level, "raid.setomen");
|
||||
|
||||
// kill [<targets>]
|
||||
let kill = d.literal(root, "kill");
|
||||
@@ -183,6 +190,7 @@ pub fn build() -> Dispatcher {
|
||||
let summon = d.literal(root, "summon");
|
||||
d.requires(summon, GAMEMASTERS);
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.suggests(e, super::Suggests::SummonableEntities);
|
||||
d.executes(e, "summon");
|
||||
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "summon");
|
||||
@@ -266,15 +274,18 @@ pub fn build() -> Dispatcher {
|
||||
|
||||
// difficulty [<difficulty>]
|
||||
let diff = d.literal(root, "difficulty");
|
||||
d.requires(diff, GAMEMASTERS);
|
||||
d.executes(diff, "difficulty");
|
||||
for name in DIFFICULTIES {
|
||||
let l = d.literal(diff, name);
|
||||
d.requires(l, GAMEMASTERS);
|
||||
d.executes(l, "difficulty");
|
||||
}
|
||||
|
||||
// seed and version: everyone in the integrated server.
|
||||
let seed = d.literal(root, "seed");
|
||||
d.executes(seed, "seed");
|
||||
let version = d.literal(root, "version");
|
||||
d.executes(version, "version");
|
||||
|
||||
// spawnpoint [<targets>] [<pos>] [<rotation>]
|
||||
let sp = d.literal(root, "spawnpoint");
|
||||
@@ -311,20 +322,25 @@ pub fn build() -> Dispatcher {
|
||||
let locate = d.literal(root, "locate");
|
||||
d.requires(locate, GAMEMASTERS);
|
||||
let s = d.literal(locate, "structure");
|
||||
let a = d.argument(s, "structure", ArgType::Resource(Resource::Structure));
|
||||
let a = d.argument(s, "structure", ArgType::ResOrTagKey("minecraft:worldgen/structure"));
|
||||
d.executes(a, "locate.structure");
|
||||
let b = d.literal(locate, "biome");
|
||||
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
|
||||
let a = d.argument(b, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
|
||||
d.executes(a, "locate.biome");
|
||||
let p = d.literal(locate, "poi");
|
||||
let a = d.argument(p, "poi", ArgType::ResOrTag("minecraft:point_of_interest_type"));
|
||||
d.executes(a, "locate.poi");
|
||||
|
||||
// warden_spawn_tracker (clear | set <warning_level>)
|
||||
let tracker = d.literal(root, "warden_spawn_tracker");
|
||||
d.requires(tracker, GAMEMASTERS);
|
||||
let clear = d.literal(tracker, "clear");
|
||||
d.executes(clear, "warden_spawn_tracker.clear");
|
||||
let set = d.literal(tracker, "set");
|
||||
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
|
||||
d.executes(level, "warden_spawn_tracker.set");
|
||||
if dev {
|
||||
// warden_spawn_tracker (clear | set <warning_level>)
|
||||
let tracker = d.literal(root, "warden_spawn_tracker");
|
||||
d.requires(tracker, GAMEMASTERS);
|
||||
let clear = d.literal(tracker, "clear");
|
||||
d.executes(clear, "warden_spawn_tracker.clear");
|
||||
let set = d.literal(tracker, "set");
|
||||
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
|
||||
d.executes(level, "warden_spawn_tracker.set");
|
||||
}
|
||||
|
||||
// say / me / msg / list
|
||||
let say = d.literal(root, "say");
|
||||
@@ -378,6 +394,7 @@ pub fn build() -> Dispatcher {
|
||||
super::tree_execute::register(&mut d, root);
|
||||
super::tree_misc::register(&mut d, root);
|
||||
super::tree_world::register(&mut d, root);
|
||||
super::tree_extra::register(&mut d, root);
|
||||
d
|
||||
}
|
||||
|
||||
@@ -391,10 +408,11 @@ fn advancement(d: &mut Dispatcher, root: usize) {
|
||||
let t = d.argument(a, "targets", PLAYERS);
|
||||
for mode in ["only", "from", "until", "through"] {
|
||||
let m = d.literal(t, mode);
|
||||
let id = d.argument(m, "advancement", ArgType::Id("advancements"));
|
||||
let id = d.argument(m, "advancement", ArgType::ResKey("minecraft:advancement"));
|
||||
d.executes(id, "advancement");
|
||||
if mode == "only" {
|
||||
let c = d.argument(id, "criterion", ArgType::Greedy);
|
||||
d.suggests(c, super::Suggests::AdvancementCriteria);
|
||||
d.executes(c, "advancement");
|
||||
}
|
||||
}
|
||||
@@ -409,6 +427,7 @@ fn clock_nodes(d: &mut Dispatcher, node: usize) {
|
||||
let t = d.argument(set, "time", ArgType::Time { min: 0 });
|
||||
d.executes(t, "time.set");
|
||||
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
|
||||
d.suggests(marker, super::Suggests::TimeMarkers);
|
||||
d.executes(marker, "time.set.marker");
|
||||
let add = d.literal(node, "add");
|
||||
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
|
||||
@@ -483,5 +502,10 @@ pub fn dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(build)
|
||||
}
|
||||
/// The tree of a release integrated server (no development commands).
|
||||
pub fn release_dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(|| build_with(false))
|
||||
}
|
||||
#[allow(unused)]
|
||||
const _: (u8, u8) = (ALL, GAMEMASTERS);
|
||||
|
||||
@@ -10,6 +10,7 @@ use horizon_client::{
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::attribute_map::ValueKind;
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
fn num(n: impl std::fmt::Display) -> Text {
|
||||
Text::literal(n.to_string())
|
||||
@@ -386,18 +387,79 @@ impl Game<'_> {
|
||||
let Some(Arg::Str(spec)) = ctx.get("name").cloned() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut words = spec.split(' ');
|
||||
let name = words.next().unwrap_or("");
|
||||
// ParticleArgument: `id` then optional SNBT options (`dust{color:[1,0,0],scale:2}`).
|
||||
let (name, options_text) = match spec.find('{') {
|
||||
Some(i) => (&spec[..i], &spec[i..]),
|
||||
None => (spec.as_str(), ""),
|
||||
};
|
||||
let ty = ParticleType::from_name(name).ok_or_else(|| err("particle.notFound", &[&name]))?;
|
||||
let rest: Vec<&str> = words.collect();
|
||||
let float = |i: usize, d: f32| rest.get(i).and_then(|w| w.parse::<f32>().ok()).unwrap_or(d);
|
||||
let opts = match horizon_client::command::snbt::parse_fully(options_text) {
|
||||
Ok(Tag::Compound(c)) if !options_text.is_empty() => Some(c),
|
||||
_ => None,
|
||||
};
|
||||
let field = |key: &str| opts.as_ref().and_then(|c| c.get(&key.into()).cloned());
|
||||
let number = |t: &Tag| -> Option<f32> {
|
||||
Some(match t {
|
||||
Tag::Byte(v) => f32::from(*v),
|
||||
Tag::Short(v) => f32::from(*v),
|
||||
Tag::Int(v) => *v as f32,
|
||||
Tag::Long(v) => *v as f32,
|
||||
Tag::Float(v) => f32::from_bits(*v),
|
||||
Tag::Double(v) => f64::from_bits(*v) as f32,
|
||||
_ => return None,
|
||||
})
|
||||
};
|
||||
let string = |t: &Tag| match t {
|
||||
Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
// ExtraCodecs.RGB_COLOR_CODEC: an int or a list of three floats.
|
||||
let rgb = match field("color") {
|
||||
Some(Tag::List(l)) if l.len() >= 3 => [
|
||||
number(&l[0]).unwrap_or(1.0),
|
||||
number(&l[1]).unwrap_or(0.0),
|
||||
number(&l[2]).unwrap_or(0.0),
|
||||
],
|
||||
Some(Tag::Int(v)) => [
|
||||
((v >> 16) & 255) as f32 / 255.0,
|
||||
((v >> 8) & 255) as f32 / 255.0,
|
||||
(v & 255) as f32 / 255.0,
|
||||
],
|
||||
_ => [1.0, 0.0, 0.0],
|
||||
};
|
||||
let options = match ty {
|
||||
ParticleType::Dust => ParticleOptions::dust(
|
||||
[float(0, 1.0), float(1, 0.0), float(2, 0.0)],
|
||||
float(3, 1.0).clamp(0.01, 4.0),
|
||||
rgb,
|
||||
field("scale")
|
||||
.as_ref()
|
||||
.and_then(number)
|
||||
.unwrap_or(1.0)
|
||||
.clamp(0.01, 4.0),
|
||||
),
|
||||
ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => {
|
||||
let mut reader = horizon_client::command::Reader::new(rest.join(" ").leak());
|
||||
// BlockParticleOption: a block id, or {Name, Properties}.
|
||||
let text = match field("block_state") {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
Some(Tag::Compound(c)) => {
|
||||
let name = c.get(&"Name".into()).and_then(string).unwrap_or_default();
|
||||
let props: Vec<String> = match c.get(&"Properties".into()) {
|
||||
Some(Tag::Compound(p)) => p
|
||||
.iter()
|
||||
.filter_map(|(k, v)| {
|
||||
string(v).map(|v| format!("{}={v}", k.to_string_lossy()))
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if props.is_empty() {
|
||||
name
|
||||
} else {
|
||||
format!("{name}[{}]", props.join(","))
|
||||
}
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
let mut reader = horizon_client::command::Reader::new(&text);
|
||||
let block = horizon_client::command::args::ArgType::BlockState
|
||||
.parse(&mut reader, &self.ui.registries);
|
||||
match block {
|
||||
|
||||
@@ -99,6 +99,22 @@ impl Game<'_> {
|
||||
let board = &self.score.board;
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.objectives = board.objectives.iter().map(|o| o.name.clone()).collect();
|
||||
// Trigger objectives: the locks `/trigger` and `scoreboard players enable` complete from.
|
||||
reg.trigger_scores.clear();
|
||||
for o in board.objectives.iter().filter(|o| o.criteria == "trigger") {
|
||||
let locks = board
|
||||
.scores
|
||||
.iter()
|
||||
.filter_map(|(holder, s)| s.get(&o.name).map(|s| (holder.clone(), s.locked)))
|
||||
.collect();
|
||||
reg.trigger_scores.insert(o.name.clone(), locks);
|
||||
}
|
||||
reg.trigger_objectives = reg
|
||||
.trigger_scores
|
||||
.iter()
|
||||
.filter(|(_, locks)| locks.get(PLAYER_NAME) == Some(&false))
|
||||
.map(|(o, _)| o.clone())
|
||||
.collect();
|
||||
reg.teams = board.teams.iter().map(|t| t.name.clone()).collect();
|
||||
reg.tracked = board.tracked();
|
||||
reg.storages = self.score.storage.keys();
|
||||
|
||||
@@ -75,7 +75,10 @@ public final class VanillaCommandParseOracle {
|
||||
final RegistryAccess access;
|
||||
final HolderLookup.Provider lookup;
|
||||
Src(MinecraftServer server, PermissionSet perms, RegistryAccess access, HolderLookup.Provider lookup) {
|
||||
super(CommandSource.NULL, Vec3.ZERO, Vec2.ZERO, null, perms, Component.literal("Player"), server);
|
||||
this(server, null, perms, access, lookup);
|
||||
}
|
||||
Src(MinecraftServer server, net.minecraft.server.level.ServerLevel level, PermissionSet perms, RegistryAccess access, HolderLookup.Provider lookup) {
|
||||
super(CommandSource.NULL, Vec3.ZERO, Vec2.ZERO, level, perms, Component.literal("Player"), server);
|
||||
this.access = access;
|
||||
this.lookup = lookup;
|
||||
}
|
||||
@@ -122,6 +125,10 @@ public final class VanillaCommandParseOracle {
|
||||
var dims = RegistryDataLoader.load(resources, java.util.stream.Stream.concat(context.stream(), world.listRegistries()).toList(), RegistryDataLoader.DIMENSION_REGISTRIES, Runnable::run).join();
|
||||
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world, dims);
|
||||
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
|
||||
// The data pack managers (advancements, functions, recipes) a running server holds.
|
||||
var managers = net.minecraft.server.ReloadableServerResources.loadResources(
|
||||
resources, worldLayers, staticTags, FeatureFlags.VANILLA_SET, Commands.CommandSelection.INTEGRATED,
|
||||
LevelBasedPermissionSet.GAMEMASTER, Runnable::run, Runnable::run).join();
|
||||
HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags();
|
||||
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
@@ -129,7 +136,7 @@ public final class VanillaCommandParseOracle {
|
||||
RegistryAccess access = loaded.layers().compositeAccess();
|
||||
|
||||
if (args[0].equals("registries")) {
|
||||
exportRegistries(out, access, lookup);
|
||||
exportRegistries(out, access, lookup, repo, resources, managers);
|
||||
return;
|
||||
}
|
||||
FeatureFlagSet features = FeatureFlags.VANILLA_SET;
|
||||
@@ -142,6 +149,35 @@ public final class VanillaCommandParseOracle {
|
||||
return;
|
||||
}
|
||||
MinecraftServer server = (MinecraftServer) unsafe.allocateInstance(DedicatedServer.class);
|
||||
// The minimal state of a freshly created world that suggestion providers read:
|
||||
// empty command storage, stopwatches, boss bars, random sequences and
|
||||
// scheduled functions, the world clocks, the vanilla data pack (repository,
|
||||
// advancements, functions, structure templates) and an overworld level.
|
||||
put(server, MinecraftServer.class, "registries", loaded.layers());
|
||||
Class<?> reloadable = Class.forName("net.minecraft.server.MinecraftServer$ReloadableResources");
|
||||
var reloadableCtor = reloadable.getDeclaredConstructor(net.minecraft.server.packs.resources.CloseableResourceManager.class, net.minecraft.server.ReloadableServerResources.class);
|
||||
reloadableCtor.setAccessible(true);
|
||||
put(server, MinecraftServer.class, "resources", reloadableCtor.newInstance(resources, managers));
|
||||
put(server, MinecraftServer.class, "functionManager", new net.minecraft.server.ServerFunctionManager(server, managers.getFunctionLibrary()));
|
||||
put(server, MinecraftServer.class, "packRepository", repo);
|
||||
put(server, MinecraftServer.class, "commandStorage", new net.minecraft.world.level.storage.CommandStorage(null));
|
||||
var stopwatchesCtor = net.minecraft.world.Stopwatches.class.getDeclaredConstructor();
|
||||
stopwatchesCtor.setAccessible(true);
|
||||
put(server, MinecraftServer.class, "stopwatches", stopwatchesCtor.newInstance());
|
||||
put(server, MinecraftServer.class, "customBossEvents", new net.minecraft.server.bossevents.CustomBossEvents());
|
||||
put(server, MinecraftServer.class, "randomSequences", new net.minecraft.world.RandomSequences());
|
||||
put(server, MinecraftServer.class, "scheduledEvents", new net.minecraft.world.level.timers.TimerQueue<MinecraftServer>());
|
||||
var clocks = net.minecraft.world.clock.ServerClockManager.TYPE.constructor().get();
|
||||
clocks.init(server);
|
||||
put(server, MinecraftServer.class, "clockManager", clocks);
|
||||
var templates = (net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager) unsafe.allocateInstance(
|
||||
net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager.class);
|
||||
put(templates, net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager.class, "sources", List.of(templateSource(lookup, resources)));
|
||||
put(server, MinecraftServer.class, "structureTemplateManager", templates);
|
||||
var level = (net.minecraft.server.level.ServerLevel) unsafe.allocateInstance(net.minecraft.server.level.ServerLevel.class);
|
||||
put(level, Level.class, "dimensionTypeRegistration",
|
||||
access.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD));
|
||||
put(level, net.minecraft.server.level.ServerLevel.class, "server", server);
|
||||
PlayerList playerList = (PlayerList) unsafe.allocateInstance(net.minecraft.server.dedicated.DedicatedPlayerList.class);
|
||||
put(playerList, PlayerList.class, "players", new ArrayList<>());
|
||||
put(server, MinecraftServer.class, "playerList", playerList);
|
||||
@@ -155,7 +191,7 @@ public final class VanillaCommandParseOracle {
|
||||
for (String tracked : TRACKED)
|
||||
scoreboard.getOrCreatePlayerScore(net.minecraft.world.scores.ScoreHolder.forNameOnly(tracked), scoreboard.getObjective("kills"));
|
||||
PermissionSet perms = LevelBasedPermissionSet.forLevel(PermissionLevel.byId(Integer.parseInt(args[3])));
|
||||
Src source = new Src(server, perms, access, lookup);
|
||||
Src source = new Src(server, level, perms, access, lookup);
|
||||
|
||||
List<String> lines = Files.readAllLines(Path.of(args[2]), StandardCharsets.UTF_8);
|
||||
java.io.BufferedWriter sb = Files.newBufferedWriter(out.resolve("vanilla.jsonl"));
|
||||
@@ -226,8 +262,72 @@ public final class VanillaCommandParseOracle {
|
||||
sb.close();
|
||||
}
|
||||
|
||||
static void exportRegistries(Path out, RegistryAccess access, HolderLookup.Provider lookup) throws Exception {
|
||||
static net.minecraft.world.level.levelgen.structure.templatesystem.loader.ResourceManagerTemplateSource templateSource(HolderLookup.Provider lookup, MultiPackResourceManager resources) {
|
||||
return new net.minecraft.world.level.levelgen.structure.templatesystem.loader.ResourceManagerTemplateSource(
|
||||
net.minecraft.util.datafix.DataFixers.getDataFixer(), lookup.lookupOrThrow(Registries.BLOCK), resources,
|
||||
new net.minecraft.resources.FileToIdConverter("structure", ".nbt"));
|
||||
}
|
||||
|
||||
static void exportRegistries(Path out, RegistryAccess access, HolderLookup.Provider lookup, net.minecraft.server.packs.repository.PackRepository repo, MultiPackResourceManager resources, net.minecraft.server.ReloadableServerResources managers) throws Exception {
|
||||
JsonObject o = new JsonObject();
|
||||
Set<String> learnable = new TreeSet<>();
|
||||
lookup.lookupOrThrow(Registries.RECIPE).listElements().filter(h -> !h.value().isSpecial()).forEach(h -> learnable.add(h.key().identifier().toString()));
|
||||
JsonArray learnableArr = new JsonArray();
|
||||
learnable.forEach(learnableArr::add);
|
||||
o.add("learnable_recipes", learnableArr);
|
||||
JsonObject criteria = new JsonObject();
|
||||
managers.getAdvancements().getAllAdvancements().stream()
|
||||
.sorted(java.util.Comparator.comparing(a -> a.id().toString()))
|
||||
.forEach(a -> {
|
||||
JsonArray names = new JsonArray();
|
||||
new TreeSet<>(a.value().criteria().keySet()).forEach(names::add);
|
||||
criteria.add(a.id().toString(), names);
|
||||
});
|
||||
o.add("advancement_criteria", criteria);
|
||||
JsonArray blockEntities = new JsonArray();
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
if (FeatureFlags.VANILLA_SET.isSubsetOf(block.requiredFeatures()) && block.defaultBlockState().hasBlockEntity())
|
||||
blockEntities.add(BuiltInRegistries.BLOCK.getKey(block).toString());
|
||||
}
|
||||
o.add("block_entities", blockEntities);
|
||||
Set<String> persistent = new TreeSet<>();
|
||||
for (var entry : BuiltInRegistries.DATA_COMPONENT_TYPE.entrySet())
|
||||
if (!entry.getValue().isTransient()) persistent.add(entry.getKey().identifier().toString());
|
||||
JsonArray persistentArr = new JsonArray();
|
||||
persistent.forEach(persistentArr::add);
|
||||
o.add("persistent_components", persistentArr);
|
||||
JsonObject blockTagMembers = new JsonObject();
|
||||
lookup.lookupOrThrow(Registries.BLOCK).listTags().sorted(java.util.Comparator.comparing(t -> t.key().location().toString())).forEach(tag -> {
|
||||
JsonArray members = new JsonArray();
|
||||
tag.forEach(holder -> members.add(holder.unwrapKey().orElseThrow().identifier().toString()));
|
||||
blockTagMembers.add(tag.key().location().toString(), members);
|
||||
});
|
||||
o.add("block_tag_members", blockTagMembers);
|
||||
JsonArray selected = new JsonArray();
|
||||
repo.getSelectedIds().forEach(selected::add);
|
||||
o.add("datapacks_selected", selected);
|
||||
JsonArray available = new JsonArray();
|
||||
repo.getAvailableIds().forEach(available::add);
|
||||
o.add("datapacks_available", available);
|
||||
JsonArray enableable = new JsonArray();
|
||||
repo.getAvailablePacks().stream().filter(p -> p.getRequestedFeatures().isSubsetOf(FeatureFlags.VANILLA_SET))
|
||||
.forEach(p -> enableable.add(p.getId()));
|
||||
o.add("datapacks_enableable", enableable);
|
||||
// ServerClockManager.commandTimeMarkersForClock, from the timelines' markers.
|
||||
java.util.Map<String, Set<String>> markers = new java.util.TreeMap<>();
|
||||
access.lookupOrThrow(Registries.WORLD_CLOCK).listElementIds().forEach(k -> markers.put(k.identifier().toString(), new TreeSet<>()));
|
||||
access.lookupOrThrow(Registries.TIMELINE).listElements().forEach(t -> t.value().registerTimeMarkers((key, marker) -> {
|
||||
if (marker.showInCommands())
|
||||
markers.computeIfAbsent(marker.clock().unwrapKey().orElseThrow().identifier().toString(), x -> new TreeSet<>()).add(key.identifier().toString());
|
||||
}));
|
||||
JsonObject markerObj = new JsonObject();
|
||||
markers.forEach((clock, ids) -> { JsonArray a = new JsonArray(); ids.forEach(a::add); markerObj.add(clock, a); });
|
||||
o.add("clock_time_markers", markerObj);
|
||||
Set<String> templates = new TreeSet<>();
|
||||
templateSource(lookup, resources).list().forEach(id -> templates.add(id.toString()));
|
||||
JsonArray templateArr = new JsonArray();
|
||||
templates.forEach(templateArr::add);
|
||||
o.add("templates", templateArr);
|
||||
JsonArray items = new JsonArray();
|
||||
for (var item : BuiltInRegistries.ITEM) {
|
||||
if (FeatureFlags.VANILLA_SET.isSubsetOf(item.requiredFeatures()))
|
||||
|
||||
Reference in New Issue
Block a user