Skip to content

Commit

Permalink
ObjectPool for bool and null
Browse files Browse the repository at this point in the history
  • Loading branch information
KennedyTedesco committed Dec 15, 2024
1 parent f718190 commit dc70d4d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Lang/Evaluator/Evaluator.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,23 @@
use MonkeyLang\Lang\Evaluator\Builtin\EvalPushFunction;
use MonkeyLang\Lang\Evaluator\Builtin\EvalPutsFunction;
use MonkeyLang\Lang\Evaluator\Builtin\EvalSliceFunction;
use MonkeyLang\Lang\Object\BooleanObject;
use MonkeyLang\Lang\Object\ErrorObject;
use MonkeyLang\Lang\Object\FloatObject;
use MonkeyLang\Lang\Object\FunctionObject;
use MonkeyLang\Lang\Object\IntegerObject;
use MonkeyLang\Lang\Object\MonkeyObject;
use MonkeyLang\Lang\Object\NullObject;
use MonkeyLang\Lang\Object\StringObject;

use function call_user_func;

final class Evaluator
{
private ObjectPool $objectPool;

public function __construct()
{
$this->objectPool = new ObjectPool();

$this->registerBuiltinFunctions();
}

Expand All @@ -58,7 +60,7 @@ public function eval(Node $node, Environment $environment): MonkeyObject
$node instanceof IntegerLiteral => new IntegerObject($node->value),
$node instanceof FloatLiteral => new FloatObject($node->value),
$node instanceof StringLiteral => new StringObject($node->value),
$node instanceof BooleanLiteral => BooleanObject::from($node->value),
$node instanceof BooleanLiteral => $node->value ? $this->objectPool->true : $this->objectPool->false,
$node instanceof BlockStatement => new EvalBlockStatement($this, $environment)($node),
$node instanceof IfExpression => new EvalIfExpression($this, $environment)($node),
$node instanceof WhileExpression => new EvalWhileExpression($this, $environment)($node),
Expand All @@ -81,7 +83,7 @@ public function eval(Node $node, Environment $environment): MonkeyObject
$node instanceof AssignStatement => new EvalAssingStatement($this, $environment)($node),
$node instanceof IdentifierExpression => new EvalIdentifier($environment)($node),
$node instanceof PostfixExpression => new EvalPostfixExpression($environment)($node),
default => NullObject::instance(),
default => $this->objectPool->null,
};
}

Expand Down
18 changes: 18 additions & 0 deletions src/Lang/Evaluator/ObjectPool.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace MonkeyLang\Lang\Evaluator;

use MonkeyLang\Lang\Object\BooleanObject;
use MonkeyLang\Lang\Object\NullObject;

final class ObjectPool
{
public function __construct(
private(set) BooleanObject $true = new BooleanObject(true),
private(set) BooleanObject $false = new BooleanObject(false),
private(set) NullObject $null = new NullObject(null),
) {
}
}

0 comments on commit dc70d4d

Please sign in to comment.