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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use crate::ast::Expression;
use std::collections::{HashMap, HashSet};
/// Process Minecraft command strings with variable substitution
pub struct CommandProcessor<'a> {
pub namespace: String,
pub current_params: &'a [String],
pub scoreboard_variables: &'a HashSet<String>,
pub variables: &'a HashMap<String, Expression>,
pub variable_objectives: &'a HashMap<String, String>,
pub variable_storage_paths: &'a HashMap<String, String>,
pub selector_aliases: &'a HashMap<String, String>,
pub compile_time_constants: &'a HashMap<String, f64>,
}
impl<'a> CommandProcessor<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
namespace: String,
current_params: &'a [String],
scoreboard_variables: &'a HashSet<String>,
variables: &'a HashMap<String, Expression>,
variable_objectives: &'a HashMap<String, String>,
variable_storage_paths: &'a HashMap<String, String>,
selector_aliases: &'a HashMap<String, String>,
compile_time_constants: &'a HashMap<String, f64>,
) -> Self {
Self {
namespace,
current_params,
scoreboard_variables,
variables,
variable_objectives,
variable_storage_paths,
selector_aliases,
compile_time_constants,
}
}
fn is_param(&self, name: &str) -> bool {
self.current_params.contains(&name.to_string())
}
pub fn process_command_string(&self, cmd: &str) -> Result<String, String> {
// Handle both variable substitution and parameter substitution for Minecraft 1.21.8+ macros
// Properly handles nested braces by tracking nesting levels
// Special handling for tellraw/title commands with scoreboard variables
let mut result = cmd.to_string();
let mut has_macro_vars = false;
let mut replacements = Vec::new();
let mut scoreboard_vars_found = Vec::new();
// First pass: detect if command already contains $() macro syntax
if result.contains("$(") {
has_macro_vars = true;
}
let chars: Vec<char> = result.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i] == '{' {
// Check for double brace escape sequence {{var}}
if i + 1 < chars.len() && chars[i + 1] == '{' {
// This is an escaped brace sequence {{...}}
// Find the matching closing double braces
let mut j = i + 2;
let mut content = String::new();
while j < chars.len() {
if j + 1 < chars.len() && chars[j] == '}' && chars[j + 1] == '}' {
// Found closing double braces
replacements.push((i, j + 2, format!("{{{}}}", content)));
i = j + 2;
break;
}
content.push(chars[j]);
j += 1;
}
// If no closing double braces found, treat as regular brace
if j >= chars.len() {
i += 1;
}
continue;
}
// Regular single brace - find the matching closing brace by tracking nesting level
let mut depth = 1;
let mut j = i + 1;
let mut var_content = String::new();
while j < chars.len() && depth > 0 {
if chars[j] == '{' {
depth += 1;
var_content.push(chars[j]);
} else if chars[j] == '}' {
depth -= 1;
if depth > 0 {
var_content.push(chars[j]);
}
} else {
var_content.push(chars[j]);
}
j += 1;
}
if depth == 0 {
// Found matching brace
let var_name = var_content.trim();
// Check if it's a simple variable (no special characters)
let is_simple_var = !var_name.contains(':')
&& !var_name.contains(',')
&& !var_name.contains('{');
if is_simple_var {
// Try to convert simple variables
if self.is_param(var_name) {
// Function parameter - convert to macro
let replacement = format!("$({})", var_name);
replacements.push((i, j, replacement));
has_macro_vars = true;
i = j; // Skip past this replacement
} else if let Some(const_value) = self.compile_time_constants.get(var_name)
{
let replacement = self.format_constant(*const_value);
replacements.push((i, j, replacement));
i = j;
} else if self.scoreboard_variables.contains(var_name) {
// Scoreboard variable found - collect for special handling
scoreboard_vars_found.push((i, j, var_name.to_string()));
i = j; // Skip past this variable
} else if self.variable_storage_paths.contains_key(var_name) {
// Storage variable found - collect for special handling
scoreboard_vars_found.push((i, j, var_name.to_string()));
i = j; // Skip past this variable
} else if let Some(value) = self.variables.get(var_name) {
// Constant variable - inline the value
let replacement = match value {
Expression::Number(n) => n.to_string(),
Expression::String(s) => {
// Check if we're in a command that supports string literals
let cmd_trimmed = result.trim();
// Check if we're in a JSON context (look for "text": pattern)
let is_json_context = cmd_trimmed.contains("\"text\":")
|| cmd_trimmed.contains("'text':")
|| cmd_trimmed.contains("\"value\":")
|| cmd_trimmed.contains("'value':");
let is_safe_for_strings = (cmd_trimmed.starts_with("tellraw ")
|| cmd_trimmed.starts_with("title "))
&& is_json_context
|| cmd_trimmed.starts_with("data ");
if !is_safe_for_strings {
return Err(format!(
"Cannot use string variable '{}' in this command.\n\
Most Minecraft commands don't accept string literals.\n\n\
Solutions:\n\
1. If you want to display text, use the text directly:\n\
/say Hello (not /say {{message}})\n\
2. For dynamic text with parameters, use tellraw with JSON:\n\
/tellraw @a {{\"text\":\"...\"}}\n\
3. For NBT data operations, use data commands:\n\
/data modify block ~ ~ ~ CustomName set value '{{\"text\":\"...\"}}'",
var_name
));
}
// Check if we're already inside quotes by counting unescaped quotes before this position
let before_var = &result[..i];
let mut quote_count = 0;
let mut prev_was_backslash = false;
for ch in before_var.chars() {
if ch == '"' && !prev_was_backslash {
quote_count += 1;
}
prev_was_backslash = ch == '\\' && !prev_was_backslash;
}
let inside_quotes = quote_count % 2 == 1;
// Escape quotes, backslashes, and special characters
let escaped = s
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t");
// Only wrap in quotes if we're NOT already inside quotes
if inside_quotes {
escaped
} else {
format!("\"{}\"", escaped)
}
}
Expression::Boolean(b) => b.to_string(),
_ => format!("{{{}}}", var_name),
};
replacements.push((i, j, replacement));
i = j; // Skip past this replacement
} else {
i += 1; // Not found, continue searching inside
}
} else {
// Complex structure (NBT), continue searching inside
i += 1;
}
} else {
// No matching brace found, skip this character
i += 1;
}
} else {
i += 1;
}
}
// Apply replacements in reverse order to maintain indices
// Convert char indices to byte indices for UTF-8 safety
for (char_start, char_end, replacement) in replacements.into_iter().rev() {
// Convert character indices to byte indices
let byte_start = result
.char_indices()
.nth(char_start)
.map(|(i, _)| i)
.unwrap_or(0);
let byte_end = if char_end < chars.len() {
result
.char_indices()
.nth(char_end)
.map(|(i, _)| i)
.unwrap_or(result.len())
} else {
result.len()
};
result.replace_range(byte_start..byte_end, &replacement);
}
// Handle scoreboard variables - special processing for tellraw/title/say
if !scoreboard_vars_found.is_empty() {
result = self.handle_scoreboard_vars_in_command(&result, &scoreboard_vars_found)?;
}
if has_macro_vars && scoreboard_vars_found.is_empty() {
result = self.normalize_macro_text_component_command(&result)?;
}
// If the command has macro variables, prefix with $ for Minecraft 1.21.8+ macro system
if has_macro_vars && !result.starts_with('$') {
result = format!("${}", result);
}
// Replace selector aliases (@Name -> @a[...])
// Only replace outside of string literals to avoid breaking JSON text
for (alias_name, selector) in self.selector_aliases {
let pattern = format!("@{}", alias_name);
// Find all occurrences of the pattern
let mut new_result = String::new();
let mut last_end = 0;
while let Some(pos) = result[last_end..].find(&pattern) {
let abs_pos = last_end + pos;
// Check if this occurrence is inside a string literal
// Count quotes before this position to determine if we're in a string
let before = &result[..abs_pos];
let mut in_string = false;
let mut escape_next = false;
for ch in before.chars() {
if escape_next {
escape_next = false;
continue;
}
if ch == '\\' {
escape_next = true;
continue;
}
if ch == '"' {
in_string = !in_string;
}
}
// Only replace if not in a string
if !in_string {
new_result.push_str(&result[last_end..abs_pos]);
new_result.push_str(selector);
last_end = abs_pos + pattern.len();
} else {
// Keep the original @Name in strings
new_result.push_str(&result[last_end..abs_pos + pattern.len()]);
last_end = abs_pos + pattern.len();
}
}
// Add remaining part
new_result.push_str(&result[last_end..]);
result = new_result;
}
Ok(result)
}
fn normalize_macro_text_component_command(&self, cmd: &str) -> Result<String, String> {
let trimmed = cmd.trim();
if trimmed.starts_with("title ") {
let parts: Vec<&str> = trimmed.splitn(4, ' ').collect();
if parts.len() < 4 {
return Ok(cmd.to_string());
}
let message = parts[3].trim();
if Self::looks_like_text_component(message) {
return Ok(cmd.to_string());
}
return Ok(format!(
"{} {} {} {}",
parts[0],
parts[1],
parts[2],
Self::plain_text_component(message)
));
}
if trimmed.starts_with("tellraw ") {
let parts: Vec<&str> = trimmed.splitn(3, ' ').collect();
if parts.len() < 3 {
return Ok(cmd.to_string());
}
let message = parts[2].trim();
if Self::looks_like_text_component(message) {
return Ok(cmd.to_string());
}
return Ok(format!(
"{} {} {}",
parts[0],
parts[1],
Self::plain_text_component(message)
));
}
Ok(cmd.to_string())
}
fn looks_like_text_component(message: &str) -> bool {
message.starts_with('{') || message.starts_with('[') || message.starts_with('"')
}
fn plain_text_component(message: &str) -> String {
serde_json::json!({ "text": message }).to_string()
}
fn handle_scoreboard_vars_in_command(
&self,
cmd: &str,
vars: &[(usize, usize, String)],
) -> Result<String, String> {
let trimmed = cmd.trim();
// Check if it's a tellraw, title, or say command - we can auto-convert these
if trimmed.starts_with("tellraw ") || trimmed.starts_with("title ") {
return self.convert_to_tellraw_json(cmd, vars);
}
if let Some(say_message) = trimmed.strip_prefix("say ") {
// Auto-convert /say to /tellraw @a
let tellraw_cmd = format!("tellraw @a {}", say_message.trim());
return self.convert_to_tellraw_json(&tellraw_cmd, vars);
}
// Check if this command is using macro parameters (starts with $ or contains $(var))
// Macro parameters are allowed in any command, including say
let is_macro_command = trimmed.starts_with('$') || {
// Check if all variables are macro parameters (not scoreboard variables)
vars.iter()
.all(|(_, _, name)| self.current_params.contains(name))
};
if is_macro_command {
// This is a macro command - allow it to pass through
// The variables will be replaced with $(var) syntax
return Ok(cmd.to_string());
}
// For other commands with scoreboard variables, provide helpful error
let var_names: Vec<_> = vars.iter().map(|(_, _, name)| name.as_str()).collect();
Err(format!(
"Cannot interpolate scoreboard variable{} {} in '{}' command.\n\
Scoreboard variables cannot be displayed in this command.\n\n\
Note: /say and /tellraw commands are automatically converted to display scores.\n\
For other commands, use function parameters:\n\
def show_value(val):\n\
/command {{val}}\n\
show_value(your_variable)",
if var_names.len() > 1 { "s" } else { "" },
var_names.join(", "),
trimmed.split_whitespace().next().unwrap_or("unknown")
))
}
fn convert_to_tellraw_json(
&self,
cmd: &str,
vars: &[(usize, usize, String)],
) -> Result<String, String> {
// Parse the command to extract target selector and message
// For title commands: "title <selector> <action> <message>"
// For tellraw commands: "tellraw <selector> <message>"
// First, split to get command type
let first_parts: Vec<&str> = cmd.trim().splitn(2, ' ').collect();
if first_parts.is_empty() {
return Err("Empty command".to_string());
}
let command = first_parts[0];
// Handle title and tellraw differently due to different number of arguments
let (selector, action, mut message) = if command == "title" {
// Title: "title <selector> <action> <message>"
let parts: Vec<&str> = cmd.trim().splitn(4, ' ').collect();
if parts.len() < 4 {
return Err(
"Title command requires action (title/subtitle/actionbar). Format: /title <selector> <action> <text>".to_string()
);
}
(parts[1], Some(parts[2]), parts[3])
} else {
// Tellraw: "tellraw <selector> <message>"
let parts: Vec<&str> = cmd.trim().splitn(3, ' ').collect();
if parts.len() < 3 {
return Err("Invalid tellraw command format".to_string());
}
(parts[1], None, parts[2])
};
// Check if message is a JSON array
let message_trimmed = message.trim();
if message_trimmed.starts_with('[') {
// Message is a JSON array
if !vars.is_empty() {
// Variables in JSON arrays are not supported
return Err(format!(
"Cannot use variables inside JSON array text components.\n\
\n\
You wrote: {}\n\
\n\
Variables like {{{}}} cannot be automatically inserted into existing JSON arrays.\n\
\n\
Solution: Use Minecraft's score component syntax directly:\n\
/tellraw @a [{{\"text\":\"Score: \"}},{{\"score\":{{\"name\":\"{}\",\"objective\":\"temp\"}}}}]\n\
\n\
Or use a simple JSON object (not array) and let Cobble handle it:\n\
/tellraw @a {{\"text\":\"Score: {{{}}}\"}}\n\
\n\
This will automatically generate proper JSON with score components.",
cmd,
vars[0].2,
vars[0].2,
vars[0].2
));
} else {
// No variables - return JSON array as-is
if let Some(action_token) = action {
return Ok(format!(
"{} {} {} {}",
command, selector, action_token, message
));
} else {
return Ok(format!("{} {} {}", command, selector, message));
}
}
}
// If message is a JSON object, we need to handle it specially to preserve styling
// Example: {"text":"Hello {player}","color":"gold","bold":true}
if message_trimmed.starts_with('{') {
// Try to parse as JSON to preserve styling
if let Ok(json_obj) = serde_json::from_str::<serde_json::Value>(message_trimmed) {
if let Some(text_value) = json_obj.get("text").and_then(|v| v.as_str()) {
// Check if text contains variables
let has_vars = vars
.iter()
.any(|(_, _, name)| text_value.contains(&format!("{{{}}}", name)));
if has_vars {
// Split the text field and create an array with preserved styling
let mut json_components = Vec::new();
let mut remaining = text_value;
while !remaining.is_empty() {
let mut next_var_pos = None;
let mut next_var_name = String::new();
for (_, _, var_name) in vars {
let pattern = format!("{{{}}}", var_name);
if let Some(pos) = remaining.find(&pattern) {
if next_var_pos.is_none() || pos < next_var_pos.unwrap() {
next_var_pos = Some(pos);
next_var_name = var_name.clone();
}
}
}
if let Some(pos) = next_var_pos {
// Add text before variable with original styling
if pos > 0 {
let mut text_component = json_obj.clone();
text_component["text"] =
serde_json::Value::String(remaining[..pos].to_string());
json_components.push(text_component);
}
// Check if it's a storage variable
if let Some(storage_path) =
self.variable_storage_paths.get(&next_var_name)
{
let nbt_component = serde_json::json!({
"nbt": storage_path,
"storage": format!("{}:global", self.namespace)
});
json_components.push(nbt_component);
} else {
// Add score component
let objective = self
.variable_objectives
.get(&next_var_name)
.map(|s| s.as_str())
.unwrap_or("temp");
let score_component = serde_json::json!({
"score": {
"name": next_var_name,
"objective": objective
}
});
json_components.push(score_component);
}
// Move past this variable
let pattern = format!("{{{}}}", next_var_name);
remaining = &remaining[pos + pattern.len()..];
} else {
// No more variables, add remaining text with original styling
if !remaining.is_empty() {
let mut text_component = json_obj.clone();
text_component["text"] =
serde_json::Value::String(remaining.to_string());
json_components.push(text_component);
}
break;
}
}
// Build the final command with the JSON array
let json_array = serde_json::Value::Array(json_components);
let json_string =
serde_json::to_string(&json_array).unwrap_or_else(|_| "[]".to_string());
if let Some(action_token) = action {
return Ok(format!(
"{} {} {} {}",
command, selector, action_token, json_string
));
} else {
return Ok(format!("{} {} {}", command, selector, json_string));
}
}
// If no variables in text, return as-is
if let Some(action_token) = action {
return Ok(format!(
"{} {} {} {}",
command, selector, action_token, message
));
} else {
return Ok(format!("{} {} {}", command, selector, message));
}
}
}
// If JSON parsing failed or no text field, extract text the old way as fallback
if let Some(text_start) = message.find("\"text\":") {
let after_text = &message[text_start + 7..].trim_start();
if after_text.starts_with('"') {
let mut end_pos = 1;
let chars: Vec<char> = after_text.chars().collect();
let mut prev_backslash = false;
while end_pos < chars.len() {
if chars[end_pos] == '"' && !prev_backslash {
break;
}
prev_backslash = chars[end_pos] == '\\' && !prev_backslash;
end_pos += 1;
}
if end_pos < chars.len() {
message = &after_text[1..end_pos];
}
}
}
}
// Build JSON array by replacing {var} with score components (for non-JSON messages)
let mut json_components = Vec::new();
let mut remaining = message;
// Get unique variable names
let var_names: Vec<String> = vars.iter().map(|(_, _, name)| name.clone()).collect();
while !remaining.is_empty() {
// Find the next variable placeholder
let mut next_var_pos = None;
let mut next_var_name = String::new();
for var_name in &var_names {
let pattern = format!("{{{}}}", var_name);
if let Some(pos) = remaining.find(&pattern) {
if next_var_pos.is_none() || pos < next_var_pos.unwrap() {
next_var_pos = Some(pos);
next_var_name = var_name.clone();
}
}
}
if let Some(pos) = next_var_pos {
// Add text before variable
if pos > 0 {
let text_before = &remaining[..pos];
json_components.push(format!(
"{{\"text\":\"{}\"}}",
text_before
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t")
));
}
// Check if it's a storage variable
if let Some(storage_path) = self.variable_storage_paths.get(&next_var_name) {
json_components.push(format!(
"{{\"nbt\":\"{}\",\"storage\":\"{}:global\"}}",
storage_path, self.namespace
));
} else {
// Add score component - use variable name as the score holder (fake player)
let objective = self
.variable_objectives
.get(&next_var_name)
.map(|s| s.as_str())
.unwrap_or("temp");
json_components.push(format!(
"{{\"score\":{{\"name\":\"{}\",\"objective\":\"{}\"}}}}",
next_var_name, objective
));
}
// Move past this variable
let pattern = format!("{{{}}}", next_var_name);
remaining = &remaining[pos + pattern.len()..];
} else {
// No more variables, add remaining text
if !remaining.is_empty() {
json_components.push(format!(
"{{\"text\":\"{}\"}}",
remaining
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t")
));
}
break;
}
}
// Construct final command
if json_components.is_empty() {
json_components.push("{\"text\":\"\"}".to_string());
}
// Include action token for title commands
if let Some(action_token) = action {
Ok(format!(
"{} {} {} [{}]",
command,
selector,
action_token,
json_components.join(",")
))
} else {
Ok(format!(
"{} {} [{}]",
command,
selector,
json_components.join(",")
))
}
}
fn format_constant(&self, value: f64) -> String {
if (value - value.trunc()).abs() < f64::EPSILON {
format!("{}", value as i64)
} else {
value.to_string()
}
}
}