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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
|
<?php
namespace Mnml\Parser;
use Mnml\Lexer\Token;
use Mnml\Lexer\TokenType;
class Parser
{
private array $tokens;
private int $position;
private array $errors;
private array $nodes;
/**
* @param Token[] $tokens
*/
public function __construct(array $tokens)
{
$this->tokens = $tokens;
$this->position = 0;
$this->errors = [];
$this->nodes = [];
}
public function parse(): array
{
$lastPosition = -1;
while ($this->position < count($this->tokens) - 1) {
$lastPosition = $this->position;
$currentToken = $this->getCurrentToken();
$currentStatement = null;
if ($currentToken->literal == "const") {
$currentStatement = $this->parseConst();
}
else if ($currentToken->literal == "if") {
$currentStatement = $this->parseIf();
}
else if ($currentToken->type == TokenType::Comment) {
$currentStatement = new CommentNode($currentToken);
$this->advance(1);
}
else {
$currentStatement = $this->parseFunctionCall();
}
$nextToken = $this->getCurrentToken();
if ($nextToken->literal == "=>") {
$this->advance(1);
$currentStatement = new PipeExpression($currentStatement, $this->parseExpression(shouldBeFunction: true));
}
// unknown token
if ($this->position == $lastPosition) {
$error = sprintf("Unknown token %s at position %d,%d" . PHP_EOL, $currentToken, $currentToken->line, $currentToken->column);
$this->errors[] = $error;
$this->advance(1);
echo $error;
}
$this->nodes[] = $currentStatement;
}
return $this->nodes;
}
public function printTree(): void
{
$tree = new Tree($this->nodes);
$this->printNodeRecursive($tree, 0);
}
private function printNodeRecursive(Node $node, int $level = 0): void
{
$properties = get_object_vars($node);
foreach ($properties as $propertyKey => $propertyValue) {
if ($propertyValue instanceof Node) {
echo sprintf(str_repeat("> ", $level) . "%s: %s" . PHP_EOL, $propertyKey, (new \ReflectionClass($propertyValue))->getShortName());
$this->printNodeRecursive($propertyValue, $level + 1);
}
else if (is_array($propertyValue)) {
$length = count($propertyValue);
echo sprintf(str_repeat("> ", $level) . "%s[%d]:" . PHP_EOL, $propertyKey, $length);
if ($length == 0) {
echo str_repeat("> ", $level + 1) . "_empty_" . PHP_EOL;
} else {
foreach ($propertyValue as $idx => $item) {
echo sprintf(str_repeat("> ", $level + 1) . "[%d]%s" . PHP_EOL, $idx + 1, (new \ReflectionClass($item))->getShortName());
$this->printNodeRecursive($item, $level + 2);
}
}
}
else {
if (! empty($propertyValue)) {
if ($propertyValue instanceof Token) {
echo sprintf(str_repeat("> ", $level) . "%s: %s - %d:%d" . PHP_EOL, $propertyKey, $propertyValue->literal, $propertyValue->line, $propertyValue->column);
} else {
echo sprintf(str_repeat("> ", $level) . "%s: %s" . PHP_EOL, $propertyKey, $propertyValue);
}
} else {
echo sprintf(str_repeat("> ", $level) . "%s: %s" . PHP_EOL, $propertyKey, "_empty_");
}
}
}
}
private function getCurrentToken(): Token
{
return $this->tokens[$this->position];
}
private function getNextToken(): ?Token
{
return $this->tokens[$this->position + 1] ?? null;
}
private function advance(int $steps): void
{
$lastToken = $this->getCurrentToken();
if ($this->position + $steps > count($this->tokens)) {
if (! empty($this->errors)) {
exit;
}
assert(
false,
"Parser Implementation Error: Can't advance. Position out of bounds."
);
}
$this->position += $steps;
}
private function stepBack(int $steps): void
{
$this->position -= $steps;
}
private function anticipateTokenAndSkip(array|string $tokenValues): void
{
if (is_string($tokenValues)) {
$tokenValues = [$tokenValues];
}
foreach ($tokenValues as $value) {
$currentToken = $this->getCurrentToken();
if ($currentToken->value != $value) {
$error = sprintf("Expected %s but got %s instead at %d:%d" . PHP_EOL, $value, $currentToken->value, $currentToken->line, $currentToken->column);
$this->errors[] = $error;
echo $error;
}
$this->advance(1);
}
}
private function parseConst(): Node
{
// skip const
$this->anticipateTokenAndSkip("const");
$identifier = $this->getCurrentToken();
$this->advance(1);
// skip :
$this->anticipateTokenAndSkip(":");
$type = $this->parseType();
// skip =
$this->anticipateTokenAndSkip("=");
$expression = $this->parseExpression(
shouldBeMap: $type instanceof MapTypeDeclaration,
shouldBeFunction: $type instanceof TypeDeclaration and $type->left->literal == "function",
);
return new ConstVariableDeclaration(
$identifier,
$type,
$expression,
);
}
private function parseType(): Node
{
$currentToken = $this->getCurrentToken();
$nextToken = $this->getNextToken();
if ($currentToken->literal == "[") {
return $this->parseArrayOrMapType();
}
else if (in_array($nextToken->literal, ["and", "or"])) {
$this->advance(2);
return new TypeDeclaration($currentToken, $nextToken, $this->parseType());
}
else {
$this->advance(1);
return new TypeDeclaration($currentToken);
}
}
private function parseArrayOrMapType(): Node
{
// skip first [
$this->anticipateTokenAndSkip("[");
$key = $this->parseType();
$currentToken = $this->getCurrentToken();
$nextToken = $this->getNextToken();
if ($currentToken->literal == "]" && $nextToken->literal == "[") {
// skip to first type
$this->advance(2);
$value = $this->parseType();
// skip last ]
$this->anticipateTokenAndSkip("]");
return new MapTypeDeclaration($key, $value);
} else {
// skip last ]
$this->anticipateTokenAndSkip("]");
return new ArrayTypeDeclaration($key);
}
}
private function parseExpression($shouldBeMap = false, $shouldBeFunction = false): Node|Token
{
$currentToken = $this->getCurrentToken();
$currentExpression = $currentToken;
if ($currentToken->literal == "[") {
$currentExpression = $this->parseArrayOrMap($shouldBeMap);
}
else if ($currentToken->type == TokenType::Identifier) {
$currentExpression = new IdentifierNode($currentToken);
$this->advance(1);
}
else if ($currentToken->type == TokenType::Number) {
$currentExpression = $this->parseNumber();
}
else if ($currentToken->type == TokenType::String) {
$currentExpression = new StringNode($currentToken);
$this->advance(1);
}
else if ($currentToken->literal == "(") {
#if ($shouldBeFunction) {
$currentExpression = $this->parseFunctionDefinition();
#}
# TODO: parse normal ()
}
else {
# TODO: error. unknown token
$this->advance(1);
}
$nextToken = $this->getCurrentToken();
if (in_array($nextToken->literal, ["+", "-", "*", "**", "/"])) {
$this->advance(1);
return new OperatorExpression($currentExpression, $nextToken, $this->parseExpression(shouldBeMap: $shouldBeMap));
}
else if (in_array($nextToken->literal, ["<", ">", "<=", ">=", "==", "!="])) {
$this->advance(1);
return new CompareExpression($currentExpression, $nextToken, $this->parseExpression(shouldBeMap: $shouldBeMap));
}
else if (in_array($nextToken->literal, ["and", "or"])) {
$this->advance(1);
return new Condition($currentExpression, $nextToken, $this->parseExpression(shouldBeMap: $shouldBeMap));
}
else if ($nextToken->literal == "=>") {
$this->advance(1);
return new PipeExpression($currentExpression, $this->parseExpression(shouldBeFunction: true));
}
else if ($currentToken->type == TokenType::Identifier and $nextToken->literal == "(") {
// step back to parse function call fully
$this->stepBack(1);
return $this->parseFunctionCall();
}
else {
return $currentExpression;
}
}
private function parseArrayOrMap($shouldBeMap = false): Node
{
$values = [];
// skip first [
if ($this->getCurrentToken()->literal == "[") {
$this->advance(1);
}
$tokenShouldBeComma = false;
while ($this->getCurrentToken()->literal != "]") {
$currentToken = $this->getCurrentToken();
// skip ,
if ($tokenShouldBeComma) {
if ($currentToken->literal == ",") {
$this->advance(1);
$tokenShouldBeComma = false;
continue;
}
// , missing => error
else {
$error = sprintf(
"Expected \",\" at position %d,%d - got %s instead" . PHP_EOL,
$currentToken->line,
$currentToken->column,
$currentToken->literal
);
$this->errors[] = $error;
echo $error;
break;
}
}
// nested array or map
if ($currentToken->literal == "[") {
$values[] = $this->parseArrayOrMap();
$tokenShouldBeComma = true;
}
// skip comments
else if ($currentToken->type == TokenType::Comment) {
$this->advance(1);
continue;
}
else {
$values[] = $this->parseArrayOrMapItem();
$tokenShouldBeComma = true;
}
}
// skip last ]
$this->advance(1);
if ((count($values) > 0 and $values[0] instanceof MapItemNode) or $shouldBeMap) {
return new MapNode($values);
} else {
return new ArrayNode($values);
}
}
private function parseArrayOrMapItem(): Node|Token
{
$key = $this->parseExpression();
// is map item
if ($this->getCurrentToken()->literal == "=") {
$this->advance(1);
$value = $this->parseExpression();
return new MapItemNode($key, $value);
}
// is array item
else {
return $key;
}
}
private function parseNumber(): Node
{
$currentToken = $this->getCurrentToken();
$value = $currentToken->value;
if (str_contains($value, ".")) {
$value = floatval($value);
} else {
$value = intval($value);
}
// step to next token
$this->advance(1);
return new NumberNode($currentToken, $value);
}
private function parseFunctionDefinition(): Node
{
$parameters = $this->parseFunctionDefinitionParameters();
// skip :
$this->anticipateTokenAndSkip(":");
$returnType = $this->parseType();
$body = $this->parseFunctionBody();
return new FunctionDefinition(
$parameters,
$returnType,
$body,
);
}
private function parseFunctionDefinitionParameters(): array
{
// skip first (
if ($this->getCurrentToken()->literal == "(") {
$this->advance(1);
}
$parameters = [];
while ($this->getCurrentToken()->literal != ")") {
// skip ,
if ($this->getCurrentToken()->literal == ",") {
$this->advance(1);
continue;
}
$identifier = $this->getCurrentToken();
$this->advance(1);
// skip :
$this->anticipateTokenAndSkip(":");
$type = $this->parseType();
// skip potential , instead default value
if ($this->getCurrentToken()->literal == ",") {
$this->advance(1);
}
// default value
$defaultValue = null;
if ($this->getCurrentToken()->literal == "=") {
$this->advance(1);
$defaultValue = $this->parseExpression();
}
$parameters[] = new FunctionDefinitionParameter(
$identifier,
$type,
$defaultValue,
);
}
// skip last )
$this->anticipateTokenAndSkip(")");
return $parameters;
}
private function parseFunctionBody(): array
{
// skip first {
$this->anticipateTokenAndSkip("{");
$body = [];
while ($this->getCurrentToken()->literal != "}") {
$currentToken = $this->getCurrentToken();
if ($currentToken->literal == "const") {
$body[] = $this->parseConst();
}
else if ($currentToken->literal == "return") {
$body[] = $this->parseFunctionReturn();
}
else if ($currentToken->literal == "if") {
$body[] = $this->parseIf();
}
// skip comments
else if ($currentToken->type == TokenType::Comment) {
$this->advance(1);
continue;
}
else {
$body[] = $this->parseFunctionCall();
}
}
// skip last }
$this->anticipateTokenAndSkip("}");
return $body;
}
private function parseFunctionReturn(): Node
{
// skip return
$this->anticipateTokenAndSkip("return");
return new FunctionReturn($this->parseExpression());
}
private function parseFunctionCall(): Node
{
$identifier = $this->getCurrentToken();
$this->advance(1);
// skip first (
$this->anticipateTokenAndSkip("(");
$parameters = $this->parseFunctionCallParameters();
return new FunctionCall(
$identifier,
$parameters,
);
}
private function parseFunctionCallParameters(): array
{
// skip first (
if ($this->getCurrentToken()->literal == "(") {
$this->advance(1);
}
$parameters = [];
while ($this->getCurrentToken()->literal != ")") {
// skip ,
if ($this->getCurrentToken()->literal == ",") {
$this->advance(1);
continue;
}
// if "=" then identifier is name
if ($this->getNextToken()->literal == "=") {
$identifier = $this->getCurrentToken();
$this->advance(2);
$value = $this->parseExpression();
$parameters[] = new FunctionCallParameter(
$identifier,
$value,
);
}
// else only value is provided
else {
$parameters[] = new FunctionCallParameter(
null,
$this->parseExpression(),
);
}
}
// skip last )
$this->anticipateTokenAndSkip(")");
return $parameters;
}
private function parseIf(): Node
{
$arms = [];
// parse first arm
$arms[] = $this->parseIfArm();
// parse remaining arms
while ($this->getCurrentToken()->literal == "else") {
$arms[] = $this->parseIfArm();
}
return new IfNode($arms);
}
private function parseIfArm(): Node
{
$isElseBlock = false;
if ($this->getCurrentToken()->literal == "if") {
$this->advance(1);
}
else if ($this->getCurrentToken()->literal == "else") {
if ($this->getNextToken()->literal == "if") {
$this->advance(2);
} else {
$isElseBlock = true;
$this->advance(1);
}
}
$condition = null;
if (! $isElseBlock) {
// skip first (
$this->anticipateTokenAndSkip("(");
$condition = $this->parseExpression();
// skip last )
$this->anticipateTokenAndSkip(")");
}
$body = $this->parseFunctionBody();
return new IfArm(
$condition,
$body,
);
}
}
class Node
{}
class Tree extends Node
{
/**
* @param Node[] $nodes
*/
public function __construct(
public array $nodes,
) {}
}
class ConstVariableDeclaration extends Node
{
public function __construct(
public Token $identifier,
public Node|Token $type,
public Node|Token $expression,
) {}
}
class TypeDeclaration extends Node
{
public function __construct(
public Token $left,
public ?Token $operator = null,
public Token|TypeDeclaration|null $right = null,
) {}
}
class ArrayTypeDeclaration extends Node
{
public function __construct(
public TypeDeclaration|ArrayTypeDeclaration $value,
) {}}
class MapTypeDeclaration extends Node
{
public function __construct(
public TypeDeclaration $key,
public TypeDeclaration|ArrayTypeDeclaration $value,
) {}
}
class ArrayNode extends Node
{
/**
* @param Array<Token|Node> $values
*/
public function __construct(
public array $values,
) {}
}
class MapNode extends Node
{
/**
* @param MapItemNode[] $values
*/
public function __construct(
public array $values,
) {}
}
class MapItemNode extends Node
{
public function __construct(
public Token|Node $key,
public Token|Node $value,
) {}
}
class OperatorExpression extends Node
{
public function __construct(
public Token|Node $left,
public Token $operator,
public Token|Node $right,
) {}
}
class CompareExpression extends Node
{
public function __construct(
public Token|Node $left,
public Token $operator,
public Token|Node $right,
) {}
}
class Condition extends Node
{
public function __construct(
public Token|Node $left,
public Token $operator,
public Token|Node $right,
) {}
}
class IdentifierNode extends Node
{
public function __construct(
public Token $token,
) {}
}
class NumberNode extends Node
{
public function __construct(
public Token $token,
public int|float $value,
) {}
}
class StringNode extends Node
{
public function __construct(
public Token $token,
) {}
}
class CommentNode extends Node
{
public function __construct(
public Token $token,
) {}
}
class FunctionDefinition extends Node
{
public function __construct(
/**
* @param FunctionDefinitionParameter[] $parameters
*/
public array $parameters,
public TypeDeclaration $returnType,
/**
* @param Node[] $body
*/
public array $body,
) {}
}
class FunctionDefinitionParameter extends Node
{
public function __construct(
public Token $identifier,
public TypeDeclaration $type,
public ?Node $defaultValue = null,
) {}
}
class FunctionReturn extends Node
{
public function __construct(
public Node|Token $returnValue,
) {}
}
class FunctionCall extends Node
{
public function __construct(
public Token $identifier,
/**
* @param FunctionCallParameter[] $parameters
*/
public array $parameters,
) {}
}
class FunctionCallParameter extends Node
{
public function __construct(
public ?Token $identifier,
public Node|Token $value,
) {}
}
class IfNode extends Node
{
public function __construct(
/**
* @param IfArm[] $arms
*/
public array $arms,
) {}
}
class IfArm extends Node
{
public function __construct(
public Condition|CompareExpression|null $condition,
public array $body,
) {}
}
class PipeExpression extends Node
{
public function __construct(
public Token|Node $left,
public Token|Node $right,
) {}
}
|