|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of Railt package. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
declare(strict_types=1); |
|
9
|
|
|
|
|
10
|
|
|
namespace Railt\SDL\Frontend\Builder\Instruction; |
|
11
|
|
|
|
|
12
|
|
|
use Railt\Parser\Ast\RuleInterface; |
|
13
|
|
|
use Railt\SDL\Frontend\Builder\BaseBuilder; |
|
14
|
|
|
use Railt\SDL\Frontend\Context\ContextInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class VariableBuilder |
|
18
|
|
|
*/ |
|
19
|
|
|
class VariableBuilder extends BaseBuilder |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @var string[] |
|
23
|
|
|
*/ |
|
24
|
|
|
private const VARIABLE_DEFINITIONS = [ |
|
25
|
|
|
'ConstantDefinition', |
|
26
|
|
|
'VariableDefinition', |
|
27
|
|
|
]; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param RuleInterface $rule |
|
31
|
|
|
* @return bool |
|
32
|
|
|
*/ |
|
33
|
|
|
public function match(RuleInterface $rule): bool |
|
34
|
|
|
{ |
|
35
|
|
|
return \in_array($rule->getName(), self::VARIABLE_DEFINITIONS, true); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param ContextInterface $ctx |
|
40
|
|
|
* @param RuleInterface $rule |
|
41
|
|
|
* @return \Generator|mixed|void |
|
42
|
|
|
*/ |
|
43
|
|
|
public function reduce(ContextInterface $ctx, RuleInterface $rule) |
|
44
|
|
|
{ |
|
45
|
|
|
/** |
|
46
|
|
|
* @var bool $isConstant |
|
47
|
|
|
* @var mixed $value |
|
48
|
|
|
*/ |
|
49
|
|
|
[$isConstant, $value] = [$this->isConstant($rule), yield $this->getValue($rule)]; |
|
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
foreach ($rule->find('> #VariableName') as $name) { |
|
52
|
|
|
$variable = $name->first('> :T_VARIABLE')->getValue(1); |
|
53
|
|
|
|
|
54
|
|
|
$record = $ctx->declare($variable)->set($value); |
|
55
|
|
|
|
|
56
|
|
|
$isConstant ? $record->lock() : $record->unlock(); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @param RuleInterface $rule |
|
62
|
|
|
* @return mixed |
|
63
|
|
|
*/ |
|
64
|
|
|
private function getValue(RuleInterface $rule) |
|
65
|
|
|
{ |
|
66
|
|
|
return $rule->first('> #VariableValue')->getChild(0); |
|
|
|
|
|
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @param RuleInterface $rule |
|
71
|
|
|
* @return bool |
|
72
|
|
|
*/ |
|
73
|
|
|
private function isConstant(RuleInterface $rule): bool |
|
74
|
|
|
{ |
|
75
|
|
|
return $rule->getName() === 'ConstantDefinition'; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.