无意中发现朋友圈有人在看书《两周自制脚本语言》。我觉得写一个脚本语言会很好,这样我可以进一步了解语言本身。于是乎,我买了它,看着它。写的还是挺通俗易懂的,但是不方便的是使用的语言是Java。PHP是最好的语言!为什么要使用Java。这几天也在网上查了一些资料,觉得这个不错。https://github.com/rspivak/ls...,但同样,本教程未使用PHP。正如作者所说,你选择的语言由你决定,解释器不依赖于语言特性。所以,我用PHP重写了part1,在接下来的几天里,我将用PHP重写所有部分。把代码写在这里,方便自己搜索,也希望有对解释器感兴趣的朋友一起学习。type=$type;$this->value=$value;}publicfunction__get($name){return$this->{$name};}publicfunction__toString(){return'type:'.$this->type.'值:'.$this->value;}}classInterpreter{private$current_char;私人$current_token;私人$文本;私人$pos=0;公共函数__construct($text){$this->text=trim($text);}publicfunctionerror(){thrownew\Exception('Lexereroor');}publicfunctionget_next_token(){$text=$this->text;if($this->pos>strlen($text)-1){returnnewToken('EOF',null);}}$this->current_char=$text[$this->pos];如果(is_numeric($this->current_char)){$token=newToken('INTEGER',intval($this->current_char));$this->pos++;返回$令牌;}if($this->current_char=="+"){$token=newToken('PLUS',$this->current_char);$this->pos++;返回$令牌;}$this->error();}publicfunctioneat($token_type){if($this->current_token->type==$token_type){$this->current_token=$this->get_next_token();}else{$this->error();}}publicfunctionexpr(){$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;返回$结果;}}do{fwrite(STDOUT,'xav>');;$输入=fgets(标准输入);$Interpreter=新解释器($input);echo$Interpreter->expr();取消设置($解释器);}而(真);目前只支持一位整数加法
