aboutsummaryrefslogtreecommitdiff
path: root/azalea-brigadier/src/errors/command_syntax_error.rs
blob: a29c95ee1b9ab75b3e1bd2562d4439b410fd1f50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::{
    cmp,
    fmt::{self, Debug, Write},
};

use super::builtin_errors::BuiltInError;

#[derive(Clone, PartialEq)]
pub struct CommandSyntaxError {
    kind: BuiltInError,
    message: String,
    input: Option<String>,
    cursor: Option<usize>,
}

const CONTEXT_AMOUNT: usize = 10;

impl CommandSyntaxError {
    pub fn new(kind: BuiltInError, message: String, input: &str, cursor: usize) -> Self {
        Self {
            kind,
            message,
            input: Some(input.to_owned()),
            cursor: Some(cursor),
        }
    }

    pub fn create(kind: BuiltInError, message: String) -> Self {
        Self {
            kind,
            message,
            input: None,
            cursor: None,
        }
    }

    pub fn message(&self) -> String {
        let mut message = self.message.clone();
        let context = self.context();
        if let Some(context) = context {
            write!(
                message,
                " at position {}: {context}",
                self.cursor.unwrap_or(usize::MAX)
            )
            .unwrap();
        }
        message
    }

    pub fn raw_message(&self) -> &String {
        &self.message
    }

    pub fn context(&self) -> Option<String> {
        if let Some(input) = &self.input
            && let Some(cursor) = self.cursor
        {
            let mut builder = String::new();
            let cursor = cmp::min(input.len(), cursor);

            if cursor > CONTEXT_AMOUNT {
                builder.push_str("...");
            }

            builder.push_str(
                &input[(cmp::max(0, cursor as isize - CONTEXT_AMOUNT as isize) as usize)..cursor],
            );
            builder.push_str("<--[HERE]");

            return Some(builder);
        }
        None
    }

    pub fn kind(&self) -> &BuiltInError {
        &self.kind
    }

    pub fn input(&self) -> Option<&str> {
        self.input.as_deref()
    }

    pub fn cursor(&self) -> Option<usize> {
        self.cursor
    }
}

impl Debug for CommandSyntaxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message())
    }
}