Golang でプログラミング言語を作る__Part12

Tuyoshi Akiyama
Aug 22, 2017 · 3 min read

前回からの続きになります。実際に、ソースコード内の、全ての値タイプをオブジェクトとしてevaluate(意味付け)してきます。

まずは、新しいフォルダobjectをプロジェクト上の作成し、次のobjectを値ごとに定義していきます。

object/object.go

type ObjectType stringtype Object interface {
Type() ObjectType
Inspect() string
}

上のタイプはObjectは、全ての値を包み込む(wrapする)ものになります。

Tokenのときの、TokenとTokenTypeの様な関係性がここでも表されています。

このObjectTypeに数値や論理値などが入ります。

では、実際に数値、論理値、NULLの順に定義したものが次のコードになります。

type Integer struct {
Value int64
}
func (i *Integer) Inspect() string { return fmt.Sprintf("%d", i.Value) }
func (i *Integer) Type() ObjectType { return INTEGER_OBJ }
type Boolean struct {
Value bool
}
func (b *Boolean) Type() ObjectType { return BOOLEAN_OBJ }
func (b *Boolean) Inspect() string { return fmt.Sprintf("%t", b.Value) }
type Null struct{}func (n *Null) Type() ObjectType { return NULL_OBJ }
func (n *Null) Inspect() string { return "null" }

ある値タイプを見つけた際には、必ず、その値を表すASTに変換されます。

そのASTノードをさらに、オブジェクトに変換してevaluation(意味付け)を行います。

また、それぞれのobject.Type(オブジェクトのタイプ名)は次のconst内で、まとめられています。

const (
INTEGER_OBJ = "INTEGER"
BOOLEAN_OBJ = "BOOLEAN"
NULL_OBJ = "NULL"
)

以上でオブジェクトの定義を行いました。これによって、ASTからきたコードを実行する際に、値を保持することができるようになります。

では、次はExpression(値)を評価して、意味付けを行っていきます。

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade