|
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\Value; |
|
11
|
|
|
|
|
12
|
|
|
use Railt\Parser\Ast\RuleInterface; |
|
13
|
|
|
use Railt\SDL\Frontend\AST\Value\AstValueInterface; |
|
14
|
|
|
use Railt\SDL\Frontend\Builder\BaseBuilder; |
|
15
|
|
|
use Railt\SDL\Frontend\Context\ContextInterface; |
|
16
|
|
|
use Railt\SDL\IR\SymbolTable\Value; |
|
17
|
|
|
use Railt\SDL\IR\Type; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Class ScalarValueBuilder |
|
21
|
|
|
*/ |
|
22
|
|
|
class ScalarValueBuilder extends BaseBuilder |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* @var string[] |
|
26
|
|
|
*/ |
|
27
|
|
|
private const SCALARS = [ |
|
28
|
|
|
'NumberValue', |
|
29
|
|
|
'StringValue', |
|
30
|
|
|
'NullValue', |
|
31
|
|
|
]; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param RuleInterface $rule |
|
35
|
|
|
* @return bool |
|
36
|
|
|
*/ |
|
37
|
|
|
public function match(RuleInterface $rule): bool |
|
38
|
|
|
{ |
|
39
|
|
|
return \in_array($rule->getName(), self::SCALARS, true); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param ContextInterface $ctx |
|
44
|
|
|
* @param RuleInterface|AstValueInterface $rule |
|
45
|
|
|
* @return mixed|Value |
|
46
|
|
|
*/ |
|
47
|
|
|
public function reduce(ContextInterface $ctx, RuleInterface $rule) |
|
48
|
|
|
{ |
|
49
|
|
|
\assert($rule instanceof AstValueInterface); |
|
50
|
|
|
|
|
51
|
|
|
switch ($rule->getName()) { |
|
52
|
|
|
case 'NumberValue': |
|
53
|
|
|
$value = $rule->toPrimitive(); |
|
54
|
|
|
return new Value($value, \is_int($value) ? Type::int() : Type::float()); |
|
|
|
|
|
|
55
|
|
|
|
|
56
|
|
|
case 'StringValue': |
|
57
|
|
|
return new Value($rule->toPrimitive(), Type::string()); |
|
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
case 'NullValue': |
|
60
|
|
|
return new Value(null, Type::null()); |
|
|
|
|
|
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.