1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PeacefulBit\Slate\Core; |
4
|
|
|
|
5
|
|
|
use PeacefulBit\Slate\Exceptions\EvaluatorException; |
6
|
|
|
use PeacefulBit\Slate\Parser\Parser; |
7
|
|
|
use PeacefulBit\Slate\Parser\Tokenizer; |
8
|
|
|
|
9
|
|
|
class Evaluator |
10
|
|
|
{ |
11
|
|
|
private static $moduleExports = [ |
12
|
|
|
'\PeacefulBit\Slate\Core\Modules\Logic\export', |
13
|
|
|
'\PeacefulBit\Slate\Core\Modules\Math\export', |
14
|
|
|
'\PeacefulBit\Slate\Core\Modules\Relation\export', |
15
|
|
|
'\PeacefulBit\Slate\Core\Modules\Stdio\export', |
16
|
|
|
'\PeacefulBit\Slate\Core\Modules\Strings\export', |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $modules; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array $userModules |
26
|
|
|
*/ |
27
|
|
|
public function __construct(array $userModules = []) |
28
|
|
|
{ |
29
|
|
|
$this->loadModules($userModules); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function loadModules(array $modules) |
33
|
|
|
{ |
34
|
|
|
$this->modules = array_merge_recursive($modules, ...array_map(function ($export) { |
35
|
|
|
return $export(); |
36
|
|
|
}, self::$moduleExports)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param string $code |
41
|
|
|
* @return mixed |
42
|
|
|
*/ |
43
|
|
|
public function evaluate(string $code) |
44
|
|
|
{ |
45
|
|
|
$tokenizer = new Tokenizer(); |
46
|
|
|
$tokens = $tokenizer->tokenize($code); |
47
|
|
|
|
48
|
|
|
$parser = new Parser(); |
49
|
|
|
$ast = $parser->parse($tokens); |
50
|
|
|
|
51
|
|
|
$frame = new Frame($this, $this->modules); |
52
|
|
|
|
53
|
|
|
// Import functions from @ module |
54
|
|
|
$frame->importModule('@'); |
55
|
|
|
|
56
|
|
|
return $frame->valueOf($ast); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $code |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
|
|
public function __invoke(string $code) |
64
|
|
|
{ |
65
|
|
|
return $this->evaluate($code); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param $name |
70
|
|
|
* @return mixed |
71
|
|
|
* @throws EvaluatorException |
72
|
|
|
*/ |
73
|
|
|
public function getModule($name) |
74
|
|
|
{ |
75
|
|
|
if (!array_key_exists($name, $this->modules)) { |
76
|
|
|
throw new EvaluatorException("Module \"$name\" not found"); |
77
|
|
|
} |
78
|
|
|
return $this->modules[$name]; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|