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
/// Token type for indentation-based parsing
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Token {
// Keywords
Import,
From,
Def,
If,
Elif,
Else,
For,
While,
Return,
Pass,
In,
Global,
As,
At,
Asat,
And,
Or,
Not,
Unless,
Match,
Case,
Const,
Define,
Create,
End,
To,
By,
Underscore,
// Literals
Number(String), // Store as string to avoid f64 Eq/Hash issues
String(String),
True_,
False_,
None_,
// Identifiers
Ident(String),
// Symbols
LParen,
RParen,
LBracket,
RBracket,
LBrace,
RBrace,
Colon,
SemiColon,
Comma,
Dot,
Equals,
Plus,
Minus,
Star,
Slash,
Percent,
Caret,
// Comparison
EqEq,
NotEq,
Lt,
LtEq,
Gt,
GtEq,
// Special
MinecraftCommand(String),
Newline,
Indent,
Dedent,
Eof,
}
impl std::fmt::Display for Token {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Token::Ident(s) => write!(f, "{}", s),
Token::String(s) => write!(
f,
"{}",
serde_json::to_string(s).unwrap_or_else(|_| format!("\"{}\"", s))
),
Token::Number(n) => write!(f, "{}", n),
Token::MinecraftCommand(s) => write!(f, "/{}", s),
Token::Dot => write!(f, "."),
Token::Colon => write!(f, ":"),
Token::SemiColon => write!(f, ";"),
Token::Comma => write!(f, ","),
Token::LParen => write!(f, "("),
Token::RParen => write!(f, ")"),
Token::LBracket => write!(f, "["),
Token::RBracket => write!(f, "]"),
Token::LBrace => write!(f, "{{"),
Token::RBrace => write!(f, "}}"),
Token::Plus => write!(f, "+"),
Token::Minus => write!(f, "-"),
Token::Star => write!(f, "*"),
Token::Slash => write!(f, "/"),
Token::Percent => write!(f, "%"),
Token::Caret => write!(f, "^"),
Token::Equals => write!(f, "="),
Token::EqEq => write!(f, "=="),
Token::NotEq => write!(f, "!="),
Token::Lt => write!(f, "<"),
Token::LtEq => write!(f, "<="),
Token::Gt => write!(f, ">"),
Token::GtEq => write!(f, ">="),
// Keywords - must be lowercase for Minecraft compatibility
Token::If => write!(f, "if"),
Token::Unless => write!(f, "unless"),
Token::As => write!(f, "as"),
Token::At => write!(f, "at"),
Token::And => write!(f, "and"),
Token::Or => write!(f, "or"),
Token::Not => write!(f, "not"),
Token::In => write!(f, "in"),
Token::For => write!(f, "for"),
Token::While => write!(f, "while"),
Token::Elif => write!(f, "elif"),
Token::Else => write!(f, "else"),
Token::Def => write!(f, "def"),
Token::Return => write!(f, "return"),
Token::Pass => write!(f, "pass"),
Token::Global => write!(f, "global"),
Token::Import => write!(f, "import"),
Token::From => write!(f, "from"),
Token::Asat => write!(f, "asat"),
Token::Match => write!(f, "match"),
Token::Case => write!(f, "case"),
Token::Const => write!(f, "const"),
Token::Define => write!(f, "define"),
Token::Create => write!(f, "create"),
Token::End => write!(f, "end"),
Token::To => write!(f, "to"),
Token::By => write!(f, "by"),
Token::Underscore => write!(f, "_"),
Token::True_ => write!(f, "True"),
Token::False_ => write!(f, "False"),
Token::None_ => write!(f, "None"),
_ => write!(f, "{:?}", self),
}
}
}
/// Manual tokenizer that handles indentation
pub fn tokenize(source: &str) -> Result<Vec<Token>, String> {
let mut tokens = Vec::new();
let mut indent_stack: Vec<usize> = vec![0];
let mut paren_depth = 0;
for (line_idx, line) in source.lines().enumerate() {
// Skip empty lines and comments
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
// Only handle indentation if we are not inside parentheses/brackets/braces
if paren_depth == 0 {
// Calculate indentation
let indent_level = line.len() - line.trim_start().len();
let current_indent = *indent_stack.last().unwrap();
// Handle indentation changes
if indent_level > current_indent {
indent_stack.push(indent_level);
tokens.push(Token::Indent);
} else if indent_level < current_indent {
while indent_stack.len() > 1 && *indent_stack.last().unwrap() > indent_level {
indent_stack.pop();
tokens.push(Token::Dedent);
}
if *indent_stack.last().unwrap() != indent_level {
return Err(format!("Indentation error at line {}", line_idx + 1));
}
}
}
// Tokenize the line content
let line_content = line.trim();
tokenize_line(line_content, &mut tokens, &mut paren_depth)?;
// Only emit Newline if not inside parentheses/brackets/braces
if paren_depth == 0 {
tokens.push(Token::Newline);
}
}
// Add remaining dedents
while indent_stack.len() > 1 {
indent_stack.pop();
tokens.push(Token::Dedent);
}
tokens.push(Token::Eof);
Ok(tokens)
}
/// Check if the minus sign should be treated as a binary operator
/// based on the previous token context
fn should_be_binary_minus(tokens: &[Token]) -> bool {
// If previous token is one of these, minus is a binary operator:
// Number, Ident, RParen, RBracket, True_, False_, None_
if let Some(last_token) = tokens.last() {
matches!(
last_token,
Token::Number(_)
| Token::Ident(_)
| Token::RParen
| Token::RBracket
| Token::True_
| Token::False_
| Token::None_
)
} else {
// At start of line or after operators/keywords, it's unary
false
}
}
/// Check if the caret should be treated as a power operator
/// based on the previous token context
fn should_be_power_operator(tokens: &[Token]) -> bool {
// Similar to should_be_binary_minus - if previous token can be an operand,
// then ^ is the power operator, not a coordinate marker
if let Some(last_token) = tokens.last() {
matches!(
last_token,
Token::Number(_)
| Token::Ident(_)
| Token::RParen
| Token::RBracket
| Token::True_
| Token::False_
| Token::None_
)
} else {
false
}
}
/// Tokenize a single line
fn tokenize_line(line: &str, tokens: &mut Vec<Token>, paren_depth: &mut i32) -> Result<(), String> {
let mut chars = line.chars().peekable();
while let Some(&ch) = chars.peek() {
match ch {
' ' | '\t' => {
chars.next();
}
'/' => {
// Check if this is a Minecraft command (starts with / followed by letter)
// or a division operator
chars.next();
if let Some(&next_ch) = chars.peek() {
// Minecraft command only if followed immediately by a letter (no space)
if next_ch.is_alphabetic() {
// Minecraft command - consume rest of line
let mut cmd: String = chars.collect();
cmd = strip_minecraft_inline_comment(&cmd).to_string();
cmd = cmd.trim_end().to_string();
tokens.push(Token::MinecraftCommand(cmd));
break;
} else {
// Division operator or other use
tokens.push(Token::Slash);
}
} else {
// End of line after /, treat as Slash
tokens.push(Token::Slash);
}
}
'"' | '\'' => {
// String literal
let quote = chars.next().unwrap();
let mut s = String::new();
let mut escaped = false;
for ch in chars.by_ref() {
if escaped {
s.push(ch);
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == quote {
break;
} else {
s.push(ch);
}
}
tokens.push(Token::String(s));
}
'0'..='9' => {
// Number
let mut num = String::new();
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() {
num.push(chars.next().unwrap());
} else if ch == '.' {
// Check if this is a range operator (..)
let mut temp_chars = chars.clone();
temp_chars.next(); // skip first dot
if let Some(&next_ch) = temp_chars.peek() {
if next_ch == '.' {
// This is "..", stop parsing number
break;
}
}
// Single dot, part of decimal number
num.push(chars.next().unwrap());
} else {
break;
}
}
// Validate that the number can be parsed
if num.parse::<f64>().is_err() {
return Err(format!(
"Invalid number literal: '{}' at line {}",
num, line
));
}
tokens.push(Token::Number(num));
}
'a'..='z' | 'A'..='Z' | '_' => {
// Identifier or keyword (may include namespace like minecraft:stone)
let mut ident = String::new();
while let Some(&ch) = chars.peek() {
if ch.is_alphanumeric() || ch == '_' {
ident.push(chars.next().unwrap());
} else if ch == ':' {
// Check if this is a namespace separator (followed by identifier)
let mut temp_chars = chars.clone();
temp_chars.next(); // skip the colon
if let Some(&next_ch) = temp_chars.peek() {
if next_ch.is_alphabetic() || next_ch == '_' {
// This is a namespace separator
ident.push(chars.next().unwrap()); // add the colon
continue;
}
}
// Not a namespace separator, stop here
break;
} else {
break;
}
}
let token = match ident.as_str() {
"import" => Token::Import,
"from" => Token::From,
"def" => Token::Def,
"if" => Token::If,
"elif" => Token::Elif,
"else" => Token::Else,
"for" => Token::For,
"while" => Token::While,
"return" => Token::Return,
"pass" => Token::Pass,
"in" => Token::In,
"global" => Token::Global,
"as" => Token::As,
"at" => Token::At,
"asat" => Token::Asat,
"and" => Token::And,
"or" => Token::Or,
"not" => Token::Not,
"unless" => Token::Unless,
"match" => Token::Match,
"case" => Token::Case,
"const" => Token::Const,
"define" => Token::Define,
"create" => Token::Create,
"end" => Token::End,
"to" => Token::To,
"by" => Token::By,
"_" => Token::Underscore,
"True" => Token::True_,
"False" => Token::False_,
"None" => Token::None_,
_ => Token::Ident(ident),
};
tokens.push(token);
}
'@' => {
// Selector (e.g., @a, @p, @s, @e[...], @Player)
let mut selector = String::new();
selector.push(chars.next().unwrap()); // @
// Collect all alphanumeric characters (for @Player, @Boss, etc.)
while let Some(&ch) = chars.peek() {
if ch.is_alphanumeric() || ch == '_' {
selector.push(chars.next().unwrap());
} else {
break;
}
}
// Handle selector arguments
if chars.peek() == Some(&'[') {
let mut bracket_depth = 0;
while let Some(ch) = chars.peek() {
selector.push(*ch);
if *ch == '[' {
bracket_depth += 1;
} else if *ch == ']' {
bracket_depth -= 1;
chars.next();
if bracket_depth == 0 {
break;
}
continue;
}
chars.next();
}
}
tokens.push(Token::Ident(selector));
}
'~' => {
// Coordinate marker
let mut coord = String::new();
coord.push(chars.next().unwrap());
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() || ch == '.' || ch == '-' {
coord.push(chars.next().unwrap());
} else {
break;
}
}
tokens.push(Token::Ident(coord));
}
'^' => {
chars.next();
// Context-aware: check if it's a coordinate (^number) or power operator (^)
// If previous token suggests binary operator context, it's power operator
if should_be_power_operator(tokens) {
// It's a power operator
tokens.push(Token::Caret);
} else if let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() || ch == '.' || ch == '-' {
// It's a coordinate marker (in execute commands)
let mut coord = String::from("^");
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() || ch == '.' || ch == '-' {
coord.push(chars.next().unwrap());
} else {
break;
}
}
tokens.push(Token::Ident(coord));
} else {
// It's a power operator
tokens.push(Token::Caret);
}
} else {
// End of input, it's a power operator
tokens.push(Token::Caret);
}
}
'=' => {
chars.next();
if chars.peek() == Some(&'=') {
chars.next();
tokens.push(Token::EqEq);
} else {
tokens.push(Token::Equals);
}
}
'!' => {
chars.next();
if chars.peek() == Some(&'=') {
chars.next();
tokens.push(Token::NotEq);
} else {
return Err("Unexpected '!' character".to_string());
}
}
'<' => {
chars.next();
if chars.peek() == Some(&'=') {
chars.next();
tokens.push(Token::LtEq);
} else {
tokens.push(Token::Lt);
}
}
'>' => {
chars.next();
if chars.peek() == Some(&'=') {
chars.next();
tokens.push(Token::GtEq);
} else {
tokens.push(Token::Gt);
}
}
'(' => {
chars.next();
tokens.push(Token::LParen);
*paren_depth += 1;
}
')' => {
chars.next();
tokens.push(Token::RParen);
*paren_depth -= 1;
}
'[' => {
chars.next();
tokens.push(Token::LBracket);
*paren_depth += 1;
}
']' => {
chars.next();
tokens.push(Token::RBracket);
*paren_depth -= 1;
}
':' => {
chars.next();
tokens.push(Token::Colon);
}
';' => {
chars.next();
tokens.push(Token::SemiColon);
}
',' => {
chars.next();
tokens.push(Token::Comma);
}
'.' => {
chars.next();
tokens.push(Token::Dot);
}
'+' => {
chars.next();
tokens.push(Token::Plus);
}
'-' => {
chars.next();
// Context-aware parsing: check if this should be binary minus or unary negative
if let Some(&next_ch) = chars.peek() {
// Only treat as negative number if:
// 1. Next char is a digit
// 2. Previous token suggests unary context (not a binary operator context)
if next_ch.is_ascii_digit() && !should_be_binary_minus(tokens) {
let mut num = String::from("-");
while let Some(&ch) = chars.peek() {
if ch.is_ascii_digit() {
num.push(chars.next().unwrap());
} else if ch == '.' {
// Check if this is a range operator (..)
let mut temp_chars = chars.clone();
temp_chars.next(); // skip first dot
if let Some(&next_ch) = temp_chars.peek() {
if next_ch == '.' {
// This is "..", stop parsing number
break;
}
}
// Single dot, part of decimal number
num.push(chars.next().unwrap());
} else {
break;
}
}
// Validate that the number can be parsed
if num.parse::<f64>().is_err() {
return Err(format!(
"Invalid number literal: '{}' at line {}",
num, line
));
}
tokens.push(Token::Number(num));
} else {
// Binary minus operator
tokens.push(Token::Minus);
}
} else {
tokens.push(Token::Minus);
}
}
'*' => {
chars.next();
tokens.push(Token::Star);
}
'%' => {
chars.next();
tokens.push(Token::Percent);
}
'{' => {
chars.next();
tokens.push(Token::LBrace);
*paren_depth += 1;
}
'}' => {
chars.next();
tokens.push(Token::RBrace);
*paren_depth -= 1;
}
'#' => {
// Comment - ignore rest of line
break;
}
_ => {
return Err(format!("Unexpected character: {}", ch));
}
}
}
Ok(())
}
fn strip_minecraft_inline_comment(command: &str) -> &str {
let mut quote: Option<char> = None;
let mut escaped = false;
let chars: Vec<(usize, char)> = command.char_indices().collect();
for (position, (index, ch)) in chars.iter().enumerate() {
if escaped {
escaped = false;
continue;
}
if *ch == '\\' {
escaped = true;
continue;
}
if let Some(active_quote) = quote {
if *ch == active_quote {
quote = None;
}
continue;
}
if *ch == '"' || *ch == '\'' {
quote = Some(*ch);
continue;
}
if *ch == '#' {
let prev_is_space = position == 0
|| chars
.get(position.wrapping_sub(1))
.map(|(_, c)| c.is_whitespace())
.unwrap_or(false);
let next_is_space_or_end = chars
.get(position + 1)
.map(|(_, c)| c.is_whitespace())
.unwrap_or(true);
if prev_is_space && next_is_space_or_end {
return command[..*index].trim_end();
}
}
}
command
}