mirror of
https://github.com/PluralKit/PluralKit.git
synced 2026-02-07 06:17:55 +00:00
feat(commands): add cs codegen to statically use params and flags in bot code, remove Any
This commit is contained in:
parent
0c012e98b5
commit
07e8a4851a
20 changed files with 297 additions and 417 deletions
|
|
@ -26,7 +26,7 @@ impl Command {
|
|||
for (idx, token) in tokens.iter().enumerate().rev() {
|
||||
match token {
|
||||
// we want flags to go before any parameters
|
||||
Token::Parameter(_, _) | Token::Any(_) => {
|
||||
Token::Parameter(_) => {
|
||||
parse_flags_before = idx;
|
||||
was_parameter = true;
|
||||
}
|
||||
|
|
@ -62,7 +62,7 @@ impl Command {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn value_flag(mut self, name: impl Into<SmolStr>, value: impl Parameter + 'static) -> Self {
|
||||
pub fn value_flag(mut self, name: impl Into<SmolStr>, value: ParameterKind) -> Self {
|
||||
self.flags.push(Flag::new(name).with_value(value));
|
||||
self
|
||||
}
|
||||
|
|
@ -95,7 +95,27 @@ impl Display for Command {
|
|||
// (and something like &dyn Trait would require everything to be referenced which doesnt look nice anyway)
|
||||
#[macro_export]
|
||||
macro_rules! command {
|
||||
([$($v:expr),+], $cb:expr$(,)*) => {
|
||||
$crate::command::Command::new([$($crate::token::Token::from($v)),*], $cb)
|
||||
([$($v:expr),+] => $cb:expr$(,)*) => {
|
||||
$crate::command::Command::new($crate::tokens!($($v),+), $cb)
|
||||
};
|
||||
($tokens:expr => $cb:expr$(,)*) => {
|
||||
$crate::command::Command::new($tokens.clone(), $cb)
|
||||
};
|
||||
($tokens:expr, $($v:expr),+ => $cb:expr$(,)*) => {
|
||||
$crate::command::Command::new($crate::concat_tokens!($tokens.clone(), [$($v),+]), $cb)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! tokens {
|
||||
($($v:expr),+$(,)*) => {
|
||||
[$($crate::token::Token::from($v)),+]
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! concat_tokens {
|
||||
($tokens:expr, [$($v:expr),+]$(,)*) => {
|
||||
$tokens.clone().into_iter().chain($crate::tokens!($($v),+).into_iter()).collect::<Vec<_>>()
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use std::{fmt::Display, sync::Arc};
|
||||
use std::fmt::Display;
|
||||
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::parameter::{Parameter, ParameterValue};
|
||||
use crate::parameter::{ParameterKind, ParameterValue};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FlagValueMatchError {
|
||||
|
|
@ -13,7 +13,7 @@ pub enum FlagValueMatchError {
|
|||
#[derive(Debug, Clone)]
|
||||
pub struct Flag {
|
||||
name: SmolStr,
|
||||
value: Option<Arc<dyn Parameter>>,
|
||||
value: Option<ParameterKind>,
|
||||
}
|
||||
|
||||
impl Display for Flag {
|
||||
|
|
@ -42,8 +42,8 @@ impl Flag {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn with_value(mut self, param: impl Parameter + 'static) -> Self {
|
||||
self.value = Some(Arc::new(param));
|
||||
pub fn with_value(mut self, param: ParameterKind) -> Self {
|
||||
self.value = Some(param);
|
||||
self
|
||||
}
|
||||
|
||||
|
|
@ -51,13 +51,17 @@ impl Flag {
|
|||
&self.name
|
||||
}
|
||||
|
||||
pub fn value_kind(&self) -> Option<ParameterKind> {
|
||||
self.value
|
||||
}
|
||||
|
||||
pub fn try_match(&self, input_name: &str, input_value: Option<&str>) -> TryMatchFlagResult {
|
||||
// if not matching flag then skip anymore matching
|
||||
if self.name != input_name {
|
||||
return None;
|
||||
}
|
||||
// get token to try matching with, if flag doesn't have one then that means it is matched (it is without any value)
|
||||
let Some(value) = self.value.as_deref() else {
|
||||
let Some(value) = self.value.as_ref() else {
|
||||
return Some(Ok(None));
|
||||
};
|
||||
// check if we have a non-empty flag value, we return error if not (because flag requested a value)
|
||||
|
|
|
|||
|
|
@ -77,21 +77,6 @@ pub fn parse_command(
|
|||
TokenMatchError::MissingParameter { name } => {
|
||||
format!("Expected parameter `{name}` in command `{prefix}{input} {token}`.")
|
||||
}
|
||||
TokenMatchError::MissingAny { tokens } => {
|
||||
let mut msg = format!("Expected one of ");
|
||||
for (idx, token) in tokens.iter().enumerate() {
|
||||
write!(&mut msg, "`{token}`").expect("oom");
|
||||
if idx < tokens.len() - 1 {
|
||||
if tokens.len() > 2 && idx == tokens.len() - 2 {
|
||||
msg.push_str(" or ");
|
||||
} else {
|
||||
msg.push_str(", ");
|
||||
}
|
||||
}
|
||||
}
|
||||
write!(&mut msg, " in command `{prefix}{input} {token}`.").expect("oom");
|
||||
msg
|
||||
}
|
||||
TokenMatchError::ParameterMatchError { input: raw, msg } => {
|
||||
format!("Parameter `{raw}` in command `{prefix}{input}` could not be parsed: {msg}.")
|
||||
}
|
||||
|
|
@ -254,12 +239,9 @@ fn next_token<'a>(
|
|||
// iterate over tokens and run try_match
|
||||
for token in possible_tokens {
|
||||
let is_match_remaining_token =
|
||||
|token: &Token| matches!(token, Token::Parameter(_, param) if param.remainder());
|
||||
|token: &Token| matches!(token, Token::Parameter(param) if param.kind().remainder());
|
||||
// check if this is a token that matches the rest of the input
|
||||
let match_remaining = is_match_remaining_token(token)
|
||||
// check for Any here if it has a "match remainder" token in it
|
||||
// if there is a "match remainder" token in a command there shouldn't be a command descending from that
|
||||
|| matches!(token, Token::Any(ref tokens) if tokens.iter().any(is_match_remaining_token));
|
||||
let match_remaining = is_match_remaining_token(token);
|
||||
// either use matched param or rest of the input if matching remaining
|
||||
let input_to_match = matched.as_ref().map(|v| {
|
||||
match_remaining
|
||||
|
|
|
|||
|
|
@ -2,89 +2,108 @@ use std::{fmt::Debug, str::FromStr};
|
|||
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::token::ParamName;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ParameterValue {
|
||||
OpaqueString(String),
|
||||
MemberRef(String),
|
||||
SystemRef(String),
|
||||
MemberPrivacyTarget(String),
|
||||
PrivacyLevel(String),
|
||||
OpaqueString(String),
|
||||
Toggle(bool),
|
||||
}
|
||||
|
||||
pub trait Parameter: Debug + Send + Sync {
|
||||
fn remainder(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn default_name(&self) -> ParamName;
|
||||
fn format(&self, f: &mut std::fmt::Formatter, name: &str) -> std::fmt::Result;
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr>;
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Parameter {
|
||||
name: SmolStr,
|
||||
kind: ParameterKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct OpaqueString(bool);
|
||||
|
||||
impl OpaqueString {
|
||||
pub const SINGLE: Self = Self(false);
|
||||
pub const REMAINDER: Self = Self(true);
|
||||
}
|
||||
|
||||
impl Parameter for OpaqueString {
|
||||
fn remainder(&self) -> bool {
|
||||
self.0
|
||||
impl Parameter {
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn default_name(&self) -> ParamName {
|
||||
"string"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, name: &str) -> std::fmt::Result {
|
||||
write!(f, "[{name}]")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Ok(ParameterValue::OpaqueString(input.into()))
|
||||
pub fn kind(&self) -> ParameterKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct MemberRef;
|
||||
|
||||
impl Parameter for MemberRef {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"member"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "<target member>")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Ok(ParameterValue::MemberRef(input.into()))
|
||||
impl From<ParameterKind> for Parameter {
|
||||
fn from(value: ParameterKind) -> Self {
|
||||
Parameter {
|
||||
name: value.default_name().into(),
|
||||
kind: value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct SystemRef;
|
||||
|
||||
impl Parameter for SystemRef {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"system"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "<target system>")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Ok(ParameterValue::SystemRef(input.into()))
|
||||
impl From<(&str, ParameterKind)> for Parameter {
|
||||
fn from((name, kind): (&str, ParameterKind)) -> Self {
|
||||
Parameter {
|
||||
name: name.into(),
|
||||
kind,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct MemberPrivacyTarget;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum ParameterKind {
|
||||
OpaqueString,
|
||||
OpaqueStringRemainder,
|
||||
MemberRef,
|
||||
SystemRef,
|
||||
MemberPrivacyTarget,
|
||||
PrivacyLevel,
|
||||
Toggle,
|
||||
}
|
||||
|
||||
impl ParameterKind {
|
||||
pub(crate) fn default_name(&self) -> &str {
|
||||
match self {
|
||||
ParameterKind::OpaqueString => "string",
|
||||
ParameterKind::OpaqueStringRemainder => "string",
|
||||
ParameterKind::MemberRef => "target",
|
||||
ParameterKind::SystemRef => "target",
|
||||
ParameterKind::MemberPrivacyTarget => "member_privacy_target",
|
||||
ParameterKind::PrivacyLevel => "privacy_level",
|
||||
ParameterKind::Toggle => "toggle",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remainder(&self) -> bool {
|
||||
matches!(self, ParameterKind::OpaqueStringRemainder)
|
||||
}
|
||||
|
||||
pub(crate) fn format(&self, f: &mut std::fmt::Formatter, param_name: &str) -> std::fmt::Result {
|
||||
match self {
|
||||
ParameterKind::OpaqueString | ParameterKind::OpaqueStringRemainder => {
|
||||
write!(f, "[{param_name}]")
|
||||
}
|
||||
ParameterKind::MemberRef => write!(f, "<target member>"),
|
||||
ParameterKind::SystemRef => write!(f, "<target system>"),
|
||||
ParameterKind::MemberPrivacyTarget => write!(f, "<privacy target>"),
|
||||
ParameterKind::PrivacyLevel => write!(f, "[privacy level]"),
|
||||
ParameterKind::Toggle => write!(f, "on/off"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
match self {
|
||||
ParameterKind::OpaqueString | ParameterKind::OpaqueStringRemainder => {
|
||||
Ok(ParameterValue::OpaqueString(input.into()))
|
||||
}
|
||||
ParameterKind::MemberRef => Ok(ParameterValue::MemberRef(input.into())),
|
||||
ParameterKind::SystemRef => Ok(ParameterValue::SystemRef(input.into())),
|
||||
ParameterKind::MemberPrivacyTarget => MemberPrivacyTargetKind::from_str(input)
|
||||
.map(|target| ParameterValue::MemberPrivacyTarget(target.as_ref().into())),
|
||||
ParameterKind::PrivacyLevel => PrivacyLevelKind::from_str(input)
|
||||
.map(|level| ParameterValue::PrivacyLevel(level.as_ref().into())),
|
||||
ParameterKind::Toggle => {
|
||||
Toggle::from_str(input).map(|t| ParameterValue::Toggle(t.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum MemberPrivacyTargetKind {
|
||||
Visibility,
|
||||
|
|
@ -135,24 +154,6 @@ impl FromStr for MemberPrivacyTargetKind {
|
|||
}
|
||||
}
|
||||
|
||||
impl Parameter for MemberPrivacyTarget {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"member_privacy_target"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "<privacy target>")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
MemberPrivacyTargetKind::from_str(input)
|
||||
.map(|target| ParameterValue::MemberPrivacyTarget(target.as_ref().into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct PrivacyLevel;
|
||||
|
||||
pub enum PrivacyLevelKind {
|
||||
Public,
|
||||
Private,
|
||||
|
|
@ -179,140 +180,34 @@ impl FromStr for PrivacyLevelKind {
|
|||
}
|
||||
}
|
||||
|
||||
impl Parameter for PrivacyLevel {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"privacy_level"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "[privacy level]")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
PrivacyLevelKind::from_str(input)
|
||||
.map(|level| ParameterValue::PrivacyLevel(level.as_ref().into()))
|
||||
}
|
||||
}
|
||||
pub const ENABLE: [&str; 5] = ["on", "yes", "true", "enable", "enabled"];
|
||||
pub const DISABLE: [&str; 5] = ["off", "no", "false", "disable", "disabled"];
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct Reset;
|
||||
|
||||
impl AsRef<str> for Reset {
|
||||
fn as_ref(&self) -> &str {
|
||||
"reset"
|
||||
}
|
||||
pub enum Toggle {
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
|
||||
impl FromStr for Reset {
|
||||
impl FromStr for Toggle {
|
||||
type Err = SmolStr;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"reset" | "clear" | "default" => Ok(Self),
|
||||
_ => Err("not reset".into()),
|
||||
ref s if ENABLE.contains(s) => Ok(Self::On),
|
||||
ref s if DISABLE.contains(s) => Ok(Self::Off),
|
||||
_ => Err("invalid toggle, must be on/off".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameter for Reset {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"reset"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "reset")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Self::from_str(input).map(|_| ParameterValue::Toggle(true))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct Toggle;
|
||||
|
||||
impl Parameter for Toggle {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"toggle"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "on/off")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Enable::from_str(input)
|
||||
.map(Into::<bool>::into)
|
||||
.or_else(|_| Disable::from_str(input).map(Into::<bool>::into))
|
||||
.map(ParameterValue::Toggle)
|
||||
.map_err(|_| "invalid toggle".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct Enable;
|
||||
|
||||
impl FromStr for Enable {
|
||||
type Err = SmolStr;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"on" | "yes" | "true" | "enable" | "enabled" => Ok(Self),
|
||||
_ => Err("invalid enable".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameter for Enable {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"enable"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "on")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Self::from_str(input).map(|e| ParameterValue::Toggle(e.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<bool> for Enable {
|
||||
impl Into<bool> for Toggle {
|
||||
fn into(self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
|
||||
pub struct Disable;
|
||||
|
||||
impl FromStr for Disable {
|
||||
type Err = SmolStr;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"off" | "no" | "false" | "disable" | "disabled" => Ok(Self),
|
||||
_ => Err("invalid disable".into()),
|
||||
match self {
|
||||
Toggle::On => true,
|
||||
Toggle::Off => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<bool> for Disable {
|
||||
fn into(self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameter for Disable {
|
||||
fn default_name(&self) -> ParamName {
|
||||
"disable"
|
||||
}
|
||||
|
||||
fn format(&self, f: &mut std::fmt::Formatter, _: &str) -> std::fmt::Result {
|
||||
write!(f, "off")
|
||||
}
|
||||
|
||||
fn match_value(&self, input: &str) -> Result<ParameterValue, SmolStr> {
|
||||
Self::from_str(input).map(|e| ParameterValue::Toggle(e.into()))
|
||||
}
|
||||
}
|
||||
pub const RESET: [&str; 3] = ["reset", "clear", "default"];
|
||||
|
|
|
|||
|
|
@ -1,76 +1,35 @@
|
|||
use std::{
|
||||
fmt::{Debug, Display},
|
||||
hash::Hash,
|
||||
ops::Not,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use smol_str::SmolStr;
|
||||
|
||||
use crate::parameter::{Parameter, ParameterValue};
|
||||
use crate::parameter::{Parameter, ParameterKind, ParameterValue};
|
||||
|
||||
pub type ParamName = &'static str;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Token {
|
||||
/// Token used to represent a finished command (i.e. no more parameters required)
|
||||
// todo: this is likely not the right way to represent this
|
||||
Empty,
|
||||
|
||||
/// multi-token matching
|
||||
/// todo: FullString tokens don't work properly in this (they don't get passed the rest of the input)
|
||||
Any(Vec<Token>),
|
||||
|
||||
/// A bot-defined command / subcommand (usually) (eg. "member" in `pk;member MyName`)
|
||||
Value(Vec<SmolStr>),
|
||||
|
||||
/// A parameter that must be provided a value
|
||||
Parameter(ParamName, Arc<dyn Parameter>),
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! any {
|
||||
($($t:expr),+) => {
|
||||
$crate::token::Token::Any(vec![$($crate::token::Token::from($t)),+])
|
||||
};
|
||||
}
|
||||
|
||||
impl PartialEq for Token {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Any(l0), Self::Any(r0)) => l0 == r0,
|
||||
(Self::Value(l0), Self::Value(r0)) => l0 == r0,
|
||||
(Self::Parameter(l0, _), Self::Parameter(r0, _)) => l0 == r0,
|
||||
(Self::Empty, Self::Empty) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Eq for Token {}
|
||||
|
||||
impl Hash for Token {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
core::mem::discriminant(self).hash(state);
|
||||
match self {
|
||||
Token::Empty => {}
|
||||
Token::Any(vec) => vec.hash(state),
|
||||
Token::Value(vec) => vec.hash(state),
|
||||
Token::Parameter(name, _) => name.hash(state),
|
||||
}
|
||||
}
|
||||
Parameter(Parameter),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TokenMatchError {
|
||||
ParameterMatchError { input: SmolStr, msg: SmolStr },
|
||||
MissingParameter { name: ParamName },
|
||||
MissingAny { tokens: Vec<Token> },
|
||||
MissingParameter { name: SmolStr },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct TokenMatchValue {
|
||||
pub raw: SmolStr,
|
||||
pub param: Option<(ParamName, ParameterValue)>,
|
||||
pub param: Option<(SmolStr, ParameterValue)>,
|
||||
}
|
||||
|
||||
impl TokenMatchValue {
|
||||
|
|
@ -83,12 +42,12 @@ impl TokenMatchValue {
|
|||
|
||||
fn new_match_param(
|
||||
raw: impl Into<SmolStr>,
|
||||
param_name: ParamName,
|
||||
param_name: impl Into<SmolStr>,
|
||||
param: ParameterValue,
|
||||
) -> TryMatchResult {
|
||||
Some(Ok(Some(Self {
|
||||
raw: raw.into(),
|
||||
param: Some((param_name, param)),
|
||||
param: Some((param_name.into(), param)),
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
|
@ -113,14 +72,9 @@ impl Token {
|
|||
// empty token
|
||||
Self::Empty => Some(Ok(None)),
|
||||
// missing paramaters
|
||||
Self::Parameter(name, _) => {
|
||||
Some(Err(TokenMatchError::MissingParameter { name }))
|
||||
}
|
||||
Self::Any(tokens) => tokens.is_empty().then_some(None).unwrap_or_else(|| {
|
||||
Some(Err(TokenMatchError::MissingAny {
|
||||
tokens: tokens.clone(),
|
||||
}))
|
||||
}),
|
||||
Self::Parameter(param) => Some(Err(TokenMatchError::MissingParameter {
|
||||
name: param.name().into(),
|
||||
})),
|
||||
// everything else doesnt match if no input anyway
|
||||
Self::Value(_) => None,
|
||||
// don't add a _ match here!
|
||||
|
|
@ -132,18 +86,13 @@ impl Token {
|
|||
// try actually matching stuff
|
||||
match self {
|
||||
Self::Empty => None,
|
||||
Self::Any(tokens) => tokens
|
||||
.iter()
|
||||
.map(|t| t.try_match(Some(input)))
|
||||
.find(|r| !matches!(r, None))
|
||||
.unwrap_or(None),
|
||||
Self::Value(values) => values
|
||||
.iter()
|
||||
.any(|v| v.eq(input))
|
||||
.then(|| TokenMatchValue::new_match(input))
|
||||
.unwrap_or(None),
|
||||
Self::Parameter(name, param) => match param.match_value(input) {
|
||||
Ok(matched) => TokenMatchValue::new_match_param(input, name, matched),
|
||||
Self::Parameter(param) => match param.kind().match_value(input) {
|
||||
Ok(matched) => TokenMatchValue::new_match_param(input, param.name(), matched),
|
||||
Err(err) => Some(Err(TokenMatchError::ParameterMatchError {
|
||||
input: input.into(),
|
||||
msg: err,
|
||||
|
|
@ -157,19 +106,9 @@ impl Display for Token {
|
|||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Token::Empty => write!(f, ""),
|
||||
Token::Any(vec) => {
|
||||
write!(f, "(")?;
|
||||
for (i, token) in vec.iter().enumerate() {
|
||||
if i != 0 {
|
||||
write!(f, "|")?;
|
||||
}
|
||||
write!(f, "{}", token)?;
|
||||
}
|
||||
write!(f, ")")
|
||||
}
|
||||
Token::Value(vec) if vec.is_empty().not() => write!(f, "{}", vec.first().unwrap()),
|
||||
Token::Value(_) => Ok(()), // if value token has no values (lol), don't print anything
|
||||
Token::Parameter(name, param) => param.format(f, name),
|
||||
Token::Parameter(param) => param.kind().format(f, param.name()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -186,14 +125,20 @@ impl<const L: usize> From<[&str; L]> for Token {
|
|||
}
|
||||
}
|
||||
|
||||
impl<P: Parameter + 'static> From<P> for Token {
|
||||
fn from(value: P) -> Self {
|
||||
Token::Parameter(value.default_name(), Arc::new(value))
|
||||
impl From<Parameter> for Token {
|
||||
fn from(value: Parameter) -> Self {
|
||||
Token::Parameter(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Parameter + 'static> From<(ParamName, P)> for Token {
|
||||
fn from(value: (ParamName, P)) -> Self {
|
||||
Token::Parameter(value.0, Arc::new(value.1))
|
||||
impl From<ParameterKind> for Token {
|
||||
fn from(value: ParameterKind) -> Self {
|
||||
Token::from(Parameter::from(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<(&str, ParameterKind)> for Token {
|
||||
fn from(value: (&str, ParameterKind)) -> Self {
|
||||
Token::from(Parameter::from(value))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,15 +38,15 @@ impl TreeBranch {
|
|||
);
|
||||
}
|
||||
|
||||
pub(super) fn command(&self) -> Option<Command> {
|
||||
pub fn command(&self) -> Option<Command> {
|
||||
self.current_command.clone()
|
||||
}
|
||||
|
||||
pub(super) fn possible_tokens(&self) -> impl Iterator<Item = &Token> {
|
||||
pub fn possible_tokens(&self) -> impl Iterator<Item = &Token> {
|
||||
self.branches.keys()
|
||||
}
|
||||
|
||||
pub(super) fn possible_commands(&self, max_depth: usize) -> impl Iterator<Item = &Command> {
|
||||
pub fn possible_commands(&self, max_depth: usize) -> impl Iterator<Item = &Command> {
|
||||
// dusk: i am too lazy to write an iterator for this without using recursion so we box everything
|
||||
fn box_iter<'a>(
|
||||
iter: impl Iterator<Item = &'a Command> + 'a,
|
||||
|
|
@ -69,7 +69,11 @@ impl TreeBranch {
|
|||
commands
|
||||
}
|
||||
|
||||
pub(super) fn get_branch(&self, token: &Token) -> Option<&TreeBranch> {
|
||||
pub fn get_branch(&self, token: &Token) -> Option<&Self> {
|
||||
self.branches.get(token)
|
||||
}
|
||||
|
||||
pub fn branches(&self) -> impl Iterator<Item = (&Token, &Self)> {
|
||||
self.branches.iter()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue