如何使用PHP來寫一個簡單的解釋器

不言
發布: 2023-04-03 06:16:01
原創
2240 人瀏覽過

這篇文章主要介紹了關於如何使用PHP來寫一個簡單的解釋器,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

偶然間在朋友圈發現有人在看一本《兩週自製腳本語言》,覺得寫個腳本語言挺不錯的,方便自己對語言本身進一步了解。於是乎,買了下來看了看,寫的挺通俗易懂,但是不便的是,採用的語言是Java,PHP才是最好的語言麼!為什麼要採用Java。

這幾日,我也在網路上搜尋了一些資料,發現這個不錯。 https://github.com/rspivak/ls...,不過同樣,該教程採用的也不是PHP。正如作者所言,選什麼語言由你,解釋者並不依賴語言特性。

於是乎,我用PHP重寫了part1的部分,並在以後幾日,將會採用PHP重寫所有部分。

在這裡寫出程式碼方便自己查找,同時也希望一些對解釋器有興趣的朋友一同學習。

<?php class Token{
    private $type;
    private $value;
    public function __construct($type,$value)
    {
        $this->type=$type;
        $this->value=$value;
    }
    
    public function __get($name)
    {
        return $this->{$name};
    }
    
    public function __toString()
    {
        return 'type:'.$this->type.' value:'.$this->value;
    }
}

class Interpreter{
    private $current_char ;
    private $current_token ;
    private $text;
    private $pos=0;
    public function __construct($text){
        $this->text=trim($text);
    }
    
    public function error()
    {
        throw('Error parsing input');
    }
    
    public function get_next_token()
    {
        $text=$this->text;
        if ($this->pos > strlen($text)-1){
            return new Token('EOF', null);
        }
        
        $this->current_char = $text[$this->pos];
        if (is_numeric($this->current_char)){
            $token=new Token('INTEGER',intval($this->current_char));
            $this->pos++;
            return $token;
        }
        
        if ($this->current_char=="+"){
            $token = new Token('PLUS', $this->current_char);
            $this->pos ++;
            return $token;
        }
        $this->error();
    }
    
    public function eat($token_type)
    {
        if ($this->current_token->type==$token_type){
            $this->current_token=$this->get_next_token();
        }else{
            $this->error();
        }
    }
    
    
    public function expr()
    {
        $this->current_token=$this->get_next_token();
        $left=$this->current_token;
        $this->eat('INTEGER');
        $op=$this->current_token;
        $this->eat('PLUS');
        $right=$this->current_token;
        $this->eat('INTEGER');
        $result=$left->value+$right->value;
        return $result;
    }
}

do{
    fwrite(STDOUT,'xav>');;
    $input=fgets(STDIN);
    $Interpreter=new Interpreter($input);
    echo $Interpreter->expr();
    unset($Interpreter);
    
}while(true);
登入後複製

如何使用PHP來寫一個簡單的解釋器

目前只支援個位元整數相加

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

thinkphp3.2.3怎麼使用think-phpunit來進行單元測試的介紹

以上是如何使用PHP來寫一個簡單的解釋器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!