《Let's Build A Simple Interpreter》之 Golang 版

  一直以来对编译器/解释器等都较有兴趣。我非科班出身,当初还在大学时,只是马马虎虎看完了《编译原理》之类教材,上机非常少,对龙书之类圣经也只是浅尝辄止而已。工作至今,基本已将编译原理相关知识忘记得差不多了,可能也就还对譬如预处理词法分析语法分析 AST 生成等基础性的概念还有点印象罢。

  约 1 年多前,我也有想法搞一套基于简化的 Pascal 语法的带类型的脚本语言“编译器”(PaxCompiler 之类可能太复杂了),并将此脚本语言编写的脚本与 Golang 交互起来。当然这只是我个人的业余兴趣而已,至于是否会付诸行动、能搞成怎样都是未知。而选择 Pascal 作为参考改编语言的原因,其一我比较喜欢它的语言设计,其二它曾是我某段时间内的工作语言所以感情成分使然,其三较之诸如 Python、Lua 我更喜欢带类型的脚本语言(TypeScript?我不太喜欢 JavaScript 的语法...),当然,Pascal 的语法形式也确实比较方便为之开发编译器/解释器。

  而短期内,个人恐怕没有太多精力去啃龙书之类,于是索性,看点基础资料且按此系列教程之类慢慢温习并从 tokenizer 开始一步步实现自己的 EcoPascal——即便最终,它只是个玩具脚本语言而已。

  近 2 天趁有空,粗略看了前文所述教程的前两章,并以 Golang 重写了这两章里的解释程序(代码写得有些粗放)。

  第一章:

package interpreter

import (
	"fmt"
)

// Token types
//
// EOF (end-of-file) token is used to indicate that
// there is no more input left for lexical analysis
type TokenType int

const (
	cTokenTypeOfNone TokenType = iota
	cTokenTypeOfInteger
	cTokenTypeOfPlusSign
	cTokenTypeOfEOF
)

type token struct {
	t TokenType   // token type: INTEGER, PLUS, or EOF
	v interface{} // token value: 0, 1, 2. 3, 4, 5, 6, 7, 8, 9, ‘+‘, or None
}

func newToken(t TokenType, v interface{}) token {
	return token{
		t: t,
		v: v,
	}
}

type Interpreter struct {
	text      []rune // client string input, e.g. "3+5"
	pos       int    // an index into text
	currToken token  // current token instance
}

func New() *Interpreter {
	return &Interpreter{
		text:      []rune(""),
		pos:       0,
		currToken: newToken(cTokenTypeOfNone, nil),
	}
}

func convToDigit(c rune) (int, bool) {
	if ‘0‘ <= c && c <= ‘9‘ {
		return int(c - ‘0‘), true
	}
	return 0, false
}

// Lexical analyzer (also known as scanner or tokenizer)
//
// This method is responsible for breaking a sentence apart into tokens.
// One token at a time.
func (self *Interpreter) getNextToken() token {
	text := self.text

	// is self.pos index past the end of the self.text ?
	// if so, then return EOF token because there is no more
	// input left to convert into tokens
	if self.pos > len(text)-1 {
		return newToken(cTokenTypeOfEOF, nil)
	}

	// get a character at the position self.pos and decide
	// what token to create based on the single character
	// var currChar interface{} = text[self.pos]
	currChar := text[self.pos]

	// if the character is a digit then convert it to
	// integer, create an INTEGER token, increment self.pos
	// index to point to the next character after the digit,
	// and return the INTEGER token
	if v, ok := convToDigit(text[self.pos]); ok {
		self.pos += 1
		return newToken(cTokenTypeOfInteger, v)
	}

	if currChar == ‘+‘ {
		self.pos += 1
		return newToken(cTokenTypeOfPlusSign, ‘+‘)
	}

	panic(fmt.Sprintf("Error parsing input1: %s", string(self.text)))
}

// compare the current token type with the passed token type
// and if they match then "eat" the current token
// and assign the next token to the self.currToken,
// otherwise raise an exception.
func (self *Interpreter) eat(tokenType TokenType) {
	if self.currToken.t == tokenType {
		self.currToken = self.getNextToken()
		return
	}

	panic(fmt.Sprintf("Error parsing input: %s", self.text))
}

// parse "INTEGER PLUS INTEGER"
func (self *Interpreter) Parse(s string) int {
	self.text = []rune(s)
	self.pos = 0

	// set current token to the first token taken from the input
	self.currToken = self.getNextToken()

	// we expect the current token to be a single-digit integer
	left := self.currToken
	self.eat(cTokenTypeOfInteger)

	// we expect the current token to be a ‘+‘ token
	// op := self.currToken
	self.eat(cTokenTypeOfPlusSign)

	// we expect the current token to be a single-digit integer
	right := self.currToken
	self.eat(cTokenTypeOfInteger)

	// after the above call the self.current_token is set to EOF token.
	// at this point INTEGER PLUS INTEGER sequence of tokens
	// has been successfully found and the method can just
	// return the result of adding two integers, thus
	// effectively interpreting client input
	return left.v.(int) + right.v.(int)
}

  第二章:

package interpreter

import (
	"fmt"

	"github.com/ecofast/rtl/sysutils"
)

// Token types
//
// EOF (end-of-file) token is used to indicate that
// there is no more input left for lexical analysis
type TokenType int

const (
	cTokenTypeOfNone TokenType = iota
	cTokenTypeOfInteger
	cTokenTypeOfPlusSign
	cTokenTypeOfMinusSign
	cTokenTypeOfEOF
)

type token struct {
	t TokenType   // token type: INTEGER, PLUS, MINUS, or EOF
	v interface{} // token value: non-negative integer value, ‘+‘, ‘-‘, or None
}

func newToken(t TokenType, v interface{}) token {
	return token{
		t: t,
		v: v,
	}
}

type Interpreter struct {
	text      []rune // client string input, e.g. "3 + 5", "12 - 5", etc
	pos       int    // an index into text
	currToken token  // current token instance
	currChar  rune
}

func New() *Interpreter {
	return &Interpreter{
		text:      []rune(""),
		pos:       0,
		currToken: newToken(cTokenTypeOfNone, nil),
		currChar:  0,
	}
}

func isDigit(c rune) bool {
	if ‘0‘ <= c && c <= ‘9‘ {
		return true
	}
	return false
}

func convToDigit(c rune) (int, bool) {
	if ‘0‘ <= c && c <= ‘9‘ {
		return int(c - ‘0‘), true
	}
	return 0, false
}

func isSpace(c rune) bool {
	if ‘ ‘ == c {
		return true
	}
	return false
}

// Advance the ‘pos‘ pointer and set the ‘currChar‘ variable
func (self *Interpreter) advance() {
	self.pos += 1
	if self.pos > len(self.text)-1 {
		self.currChar = 0
	} else {
		self.currChar = self.text[self.pos]
	}
}

func (self *Interpreter) skipWhiteSpace() {
	for self.currChar != 0 && isSpace(self.currChar) {
		self.advance()
	}
}

// Return a (multidigit) integer consumed from the input
func (self *Interpreter) integer() int {
	ret := ""
	for self.currChar != 0 && isDigit(self.currChar) {
		ret += string(self.currChar)
		self.advance()
	}
	return sysutils.StrToInt(ret)
}

// Lexical analyzer (also known as scanner or tokenizer)
//
// This method is responsible for breaking a sentence apart into tokens.
func (self *Interpreter) getNextToken() token {
	for self.currChar != 0 {
		if isSpace(self.currChar) {
			self.skipWhiteSpace()
			continue
		}

		if isDigit(self.currChar) {
			return newToken(cTokenTypeOfInteger, self.integer())
		}

		if self.currChar == ‘+‘ {
			self.advance()
			return newToken(cTokenTypeOfPlusSign, ‘+‘)
		}

		if self.currChar == ‘-‘ {
			self.advance()
			return newToken(cTokenTypeOfMinusSign, ‘-‘)
		}

		panic(fmt.Sprintf("Error parsing input1: %s", string(self.text)))
	}
	return newToken(cTokenTypeOfEOF, nil)
}

// compare the current token type with the passed token type
// and if they match then "eat" the current token
// and assign the next token to the self.currToken,
// otherwise raise an exception.
func (self *Interpreter) eat(tokenType TokenType) {
	if self.currToken.t == tokenType {
		self.currToken = self.getNextToken()
		return
	}

	panic(fmt.Sprintf("Error parsing input: %s", self.text))
}

// parse "INTEGER PLUS INTEGER" or "INTEGER MINUS INTEGER"
func (self *Interpreter) Parse(s string) int {
	self.text = []rune(s)
	self.pos = 0
	self.currChar = self.text[self.pos]

	// set current token to the first token taken from the input
	self.currToken = self.getNextToken()

	// we expect the current token to be an integer
	left := self.currToken
	self.eat(cTokenTypeOfInteger)

	// we expect the current token to be either a ‘+‘ or ‘-‘
	op := self.currToken
	if op.t == cTokenTypeOfPlusSign {
		self.eat(cTokenTypeOfPlusSign)
	} else {
		self.eat(cTokenTypeOfMinusSign)
	}

	// we expect the current token to be an integer
	right := self.currToken
	self.eat(cTokenTypeOfInteger)

	// after the above call the self.current_token is set to EOF token.
	// at this point either the INTEGER PLUS INTEGER or
	// the INTEGER MINUS INTEGER sequence of tokens
	// has been successfully found and the method can just
	// return the result of adding or subtracting two integers, thus
	// effectively interpreting client input
	if op.t == cTokenTypeOfPlusSign {
		return left.v.(int) + right.v.(int)
	}
	return left.v.(int) - right.v.(int)
}

  有了“核心”解释程序,使用起来就很简单了:

package main

import (
	"fmt"
	"part1/interpreter"
)

func main() {
	fmt.Println("Let‘s Build A Simple Interpreter - Part 1")

	parser := interpreter.New()
	s := ""
	for {
		if n, err := fmt.Scan(&s); n == 0 || err != nil {
			return
		}
		fmt.Println(parser.Parse(s))
	}
}

  

  本兴趣项目已托管至 Github,比较可能会不定期慢慢更新。

《Let's Build A Simple Interpreter》之 Golang 版

原文地址:https://www.cnblogs.com/ecofast/p/8476689.html

时间: 2024-08-27 07:53:51

《Let's Build A Simple Interpreter》之 Golang 版的相关文章

CI框架源码阅读笔记3 全局函数Common.php

从本篇开始,将深入CI框架的内部,一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说,全局函数具有最高的加载优先权,因此大多数的框架中BootStrap引导文件都会最先引入全局函数,以便于之后的处理工作). 打开Common.php中,第一行代码就非常诡异: if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 上一篇(CI框架源码阅读笔记2 一切的入口 index

IOS测试框架之:athrun的InstrumentDriver源码阅读笔记

athrun的InstrumentDriver源码阅读笔记 作者:唯一 athrun是淘宝的开源测试项目,InstrumentDriver是ios端的实现,之前在公司项目中用过这个框架,没有深入了解,现在回来记录下. 官方介绍:http://code.taobao.org/p/athrun/wiki/instrumentDriver/ 优点:这个框架是对UIAutomation的java实现,在代码提示.用例维护方面比UIAutomation强多了,借junit4的光,我们可以通过junit4的

Yii源码阅读笔记 - 日志组件

?使用 Yii框架为开发者提供两个静态方法进行日志记录: Yii::log($message, $level, $category);Yii::trace($message, $category); 两者的区别在于后者依赖于应用开启调试模式,即定义常量YII_DEBUG: defined('YII_DEBUG') or define('YII_DEBUG', true); Yii::log方法的调用需要指定message的level和category.category是格式为“xxx.yyy.z

源码阅读笔记 - 1 MSVC2015中的std::sort

大约寒假开始的时候我就已经把std::sort的源码阅读完毕并理解其中的做法了,到了寒假结尾,姑且把它写出来 这是我的第一篇源码阅读笔记,以后会发更多的,包括算法和库实现,源码会按照我自己的代码风格格式化,去掉或者展开用于条件编译或者debug检查的宏,依重要程度重新排序函数,但是不会改变命名方式(虽然MSVC的STL命名实在是我不能接受的那种),对于代码块的解释会在代码块前(上面)用注释标明. template<class _RanIt, class _Diff, class _Pr> in

CI框架源码阅读笔记5 基准测试 BenchMark.php

上一篇博客(CI框架源码阅读笔记4 引导文件CodeIgniter.php)中,我们已经看到:CI中核心流程的核心功能都是由不同的组件来完成的.这些组件类似于一个一个单独的模块,不同的模块完成不同的功能,各模块之间可以相互调用,共同构成了CI的核心骨架. 从本篇开始,将进一步去分析各组件的实现细节,深入CI核心的黑盒内部(研究之后,其实就应该是白盒了,仅仅对于应用来说,它应该算是黑盒),从而更好的去认识.把握这个框架. 按照惯例,在开始之前,我们贴上CI中不完全的核心组件图: 由于BenchMa

CI框架源码阅读笔记2 一切的入口 index.php

上一节(CI框架源码阅读笔记1 - 环境准备.基本术语和框架流程)中,我们提到了CI框架的基本流程,这里这次贴出流程图,以备参考: 作为CI框架的入口文件,源码阅读,自然由此开始.在源码阅读的过程中,我们并不会逐行进行解释,而只解释核心的功能和实现. 1.       设置应用程序环境 define('ENVIRONMENT', 'development'); 这里的development可以是任何你喜欢的环境名称(比如dev,再如test),相对应的,你要在下面的switch case代码块中

Apache Storm源码阅读笔记

欢迎转载,转载请注明出处. 楔子 自从建了Spark交流的QQ群之后,热情加入的同学不少,大家不仅对Spark很热衷对于Storm也是充满好奇.大家都提到一个问题就是有关storm内部实现机理的资料比较少,理解起来非常费劲. 尽管自己也陆续对storm的源码走读发表了一些博文,当时写的时候比较匆忙,有时候衔接的不是太好,此番做了一些整理,主要是针对TridentTopology部分,修改过的内容采用pdf格式发布,方便打印. 文章中有些内容的理解得益于徐明明和fxjwind两位的指点,非常感谢.

CI框架源码阅读笔记4 引导文件CodeIgniter.php

到了这里,终于进入CI框架的核心了.既然是"引导"文件,那么就是对用户的请求.参数等做相应的导向,让用户请求和数据流按照正确的线路各就各位.例如,用户的请求url: http://you.host.com/usr/reg 经过引导文件,实际上会交给Application中的UsrController控制器的reg方法去处理. 这之中,CodeIgniter.php做了哪些工作?我们一步步来看. 1.    导入预定义常量.框架环境初始化 之前的一篇博客(CI框架源码阅读笔记2 一切的入

jdk源码阅读笔记之java集合框架(二)(ArrayList)

关于ArrayList的分析,会从且仅从其添加(add)与删除(remove)方法入手. ArrayList类定义: p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco } span.s1 { color: #931a68 } public class ArrayList<E> extends AbstractList<E> implements List<E> ArrayList基本属性: /** *

dubbo源码阅读笔记--服务调用时序

上接dubbo源码阅读笔记--暴露服务时序,继续梳理服务调用时序,下图右面红线流程. 整理了调用时序图 分为3步,connect,decode,invoke. 连接 AllChannelHandler.connected(Channel) line: 38 HeartbeatHandler.connected(Channel) line: 47 MultiMessageHandler(AbstractChannelHandlerDelegate).connected(Channel) line: