Skip to content

Commit 17388ef

Browse files
committed
Fix object literal interpretation
1 parent 5bc6f17 commit 17388ef

3 files changed

Lines changed: 9 additions & 6 deletions

File tree

src/AST/ObjectLiteral.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
namespace Codewithkyrian\Jinja\AST;
77

8+
use SplObjectStorage;
9+
810
/**
911
* Represents an object literal in the template.
1012
*/
@@ -13,9 +15,9 @@ class ObjectLiteral extends Literal
1315
public string $type = "ObjectLiteral";
1416

1517
/**
16-
* @param array<Expression, Expression> $value
18+
* @param SplObjectStorage $value
1719
*/
18-
public function __construct(array $value)
20+
public function __construct(SplObjectStorage $value)
1921
{
2022
parent::__construct($value);
2123
}

src/Core/Interpreter.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,12 @@ function evaluate(?Statement $statement, Environment $environment): RuntimeValue
9191
TupleLiteral::class => fn(TupleLiteral $s, Environment $environment) => new TupleValue(array_map(fn($x) => $this->evaluate($x, $environment), $s->value)),
9292
ObjectLiteral::class => function (ObjectLiteral $s, Environment $environment): ObjectValue {
9393
$mapping = [];
94-
foreach ($s->value as $key => $value) {
94+
foreach ($s->value as $key) {
9595
$evaluatedKey = $this->evaluate($key, $environment);
9696
if (!($evaluatedKey instanceof StringValue)) {
9797
throw new RuntimeException("Object keys must be strings");
9898
}
99-
$mapping[$evaluatedKey->value] = $this->evaluate($value, $environment);
99+
$mapping[$evaluatedKey->value] = $this->evaluate($s->value[$key], $environment);
100100
}
101101
return new ObjectValue($mapping);
102102
},

src/Core/Parser.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Codewithkyrian\Jinja\Core;
66

7+
use SplObjectStorage;
78
use Codewithkyrian\Jinja\AST\ArrayLiteral;
89
use Codewithkyrian\Jinja\AST\BinaryExpression;
910
use Codewithkyrian\Jinja\AST\BreakStatement;
@@ -762,12 +763,12 @@ private function parsePrimaryExpression(): Statement
762763
return new ArrayLiteral($values);
763764

764765
case TokenType::OpenCurlyBracket:
765-
$values = [];
766+
$values = new SplObjectStorage();
766767
while (!$this->is(TokenType::CloseCurlyBracket)) {
767768
$key = $this->parseExpression();
768769
$this->expect(TokenType::Colon, "Expected colon between key and value in object literal");
769770
$value = $this->parseExpression();
770-
$values[] = ['key' => $key, 'value' => $value]; // TODO: Use SPLObjectStorage
771+
$values->attach($key, $value);
771772
if ($this->is(TokenType::Comma)) {
772773
$this->current++; // consume comma
773774
}

0 commit comments

Comments
 (0)