From f1c49009abc5e63721d6983005779b5d6437bd78 Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Sat, 5 Dec 2020 17:38:42 +0700 Subject: [PATCH] add shortcuts for quasiquote and unquote --- src/Reader.php | 21 +++++++++++++++------ src/Tokenizer.php | 2 +- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/Reader.php b/src/Reader.php index feaca86..4ae9ae5 100644 --- a/src/Reader.php +++ b/src/Reader.php @@ -16,12 +16,11 @@ class Reader private function readForm(array $tokens, int &$index) { if ($tokens[$index] == "'") { - $index++; - $contents = [new Symbol('quote')]; - if ($index < count($tokens) && !in_array($tokens[$index], [')', ']', '}'])) { - $contents[] = $this->readForm($tokens, $index); - } - return new MList($contents); + return $this->readSpecialForm($tokens, $index, 'quote'); + } elseif ($tokens[$index] == "`") { + return $this->readSpecialForm($tokens, $index, 'quasiquote'); + } elseif ($tokens[$index] == "~") { + return $this->readSpecialForm($tokens, $index, 'unquote'); } elseif ($tokens[$index] == '(') { return $this->readList($tokens, $index); } elseif ($tokens[$index] == '[') { @@ -33,6 +32,16 @@ class Reader } } + private function readSpecialForm(array $tokens, int &$index, string $symbol) + { + $index++; + $contents = [new Symbol($symbol)]; + if ($index < count($tokens) && !in_array($tokens[$index], [')', ']', '}'])) { + $contents[] = $this->readForm($tokens, $index); + } + return new MList($contents); + } + private function readList(array $tokens, int &$index): MList { return new MList($this->readCollection($tokens, $index, ')')); diff --git a/src/Tokenizer.php b/src/Tokenizer.php index 6b97d9c..2ae2ba4 100644 --- a/src/Tokenizer.php +++ b/src/Tokenizer.php @@ -69,7 +69,7 @@ class Tokenizer $addCurrent(); $tokens[] = $c; $parens[$parenIndexes[$c]]--; - } elseif ($c == "'") { + } elseif ($c == "'" || $c == "`" || $c == "~") { // Other special characters $addCurrent(); $tokens[] = $c;