From 2082f6238a54529bc0bbc987fd2528c32f59721e Mon Sep 17 00:00:00 2001 From: Adam Pippin Date: Fri, 19 Feb 2021 12:32:34 -0800 Subject: [PATCH] Add boolean literals to expression parser --- app/Cfnpp/Expression/Expression.php | 1 + app/Cfnpp/Expression/Token/BooleanLiteral.php | 75 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 app/Cfnpp/Expression/Token/BooleanLiteral.php diff --git a/app/Cfnpp/Expression/Expression.php b/app/Cfnpp/Expression/Expression.php index 1cb9791..4f2a7e2 100644 --- a/app/Cfnpp/Expression/Expression.php +++ b/app/Cfnpp/Expression/Expression.php @@ -20,6 +20,7 @@ class Expression * @var string[] */ public const TOKEN_TYPES = [ + Token\BooleanLiteral::class, Token\NumericLiteral::class, Token\OperatorUnary::class, Token\OperatorBinary::class, diff --git a/app/Cfnpp/Expression/Token/BooleanLiteral.php b/app/Cfnpp/Expression/Token/BooleanLiteral.php new file mode 100644 index 0000000..148ebf2 --- /dev/null +++ b/app/Cfnpp/Expression/Token/BooleanLiteral.php @@ -0,0 +1,75 @@ + + */ +class BooleanLiteral extends TokenLiteral +{ + /** + * Value of this literal. + * @var bool + */ + protected $value; + + /** + * New boolean literal. + * + * @param bool $value + */ + public function __construct(bool $value) + { + $this->value = $value; + } + + /** + * Get the value of this literal. + * + * @return bool + */ + public function getValue(): bool + { + return $this->value; + } + + public static function isToken(string $stream): bool + { + return + (strlen($stream) >= 4 && strtolower(substr($stream, 0, 4)) == 'true') || + (strlen($stream) >= 5 && strtolower(substr($stream, 0, 5)) == 'false'); + } + + public static function getToken(string &$stream): Token + { + if (strlen($stream) >= 4 && strtolower(substr($stream, 0, 4)) == 'true') + { + $stream = substr($stream, 4); + return new BooleanLiteral(true); + } + elseif (strlen($stream) >= 5 && strtolower(substr($stream, 0, 5)) == 'false') + { + $stream = substr($stream, 5); + return new BooleanLiteral(false); + } + throw new \Exception('Unparseable boolean'); + } + + /** + * Get the value of this token. + * + * @param ?\App\Util\GraphNode[] $arguments + * @return \App\Util\GraphNode|Token|scalar|null + */ + public function execute(?array $arguments = null) + { + return $this->getValue(); + } +}