Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor special forms #29

Merged
merged 8 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ type Symbol struct {
func (s *Symbol) TokenLiteral() string { return s.Token.Literal }
func (s *Symbol) String() string { return s.Value }

type SpecialForm struct {
Token token.Token
Value string
}

func (s *SpecialForm) TokenLiteral() string { return s.Token.Literal }
func (s *SpecialForm) String() string { return s.Value }

type Nil struct {
Token token.Token
}
Expand Down
28 changes: 23 additions & 5 deletions ast/modify.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,38 @@ import (

type ModifierFun func(SExpression) SExpression

func Modify(sexp SExpression, modifier ModifierFun, triggers []string) SExpression {
func ModifyByUnquote(sexp SExpression, modifier ModifierFun) SExpression {
return modify(sexp, modifier, func(sexp SExpression) bool {
if spForm, ok := sexp.(*SpecialForm); ok {
return spForm.Value == "unquote"
}
return false
})
}

func ModifyByMacro(sexp SExpression, modifier ModifierFun, macroNames []string) SExpression {
return modify(sexp, modifier, func(sexp SExpression) bool {
if symbol, ok := sexp.(*Symbol); ok {
return slices.Contains(macroNames, symbol.Value)
}
return false
})
}

func modify(sexp SExpression, modifier ModifierFun, targetCond func(sexp SExpression) bool) SExpression {
switch st := sexp.(type) {
case *Program:
for i, sexp := range st.Expressions {
st.Expressions[i] = Modify(sexp, modifier, triggers)
st.Expressions[i] = modify(sexp, modifier, targetCond)
}
case *ConsCell:
if symbol, ok := st.CarField.(*Symbol); ok && slices.Contains(triggers, symbol.Value) {
if targetCond(st.Car()) {
// return not only the car field but also the cdr field
// since args(cdr field) are needed to modify the AST
return modifier(sexp)
}
st.CarField = Modify(st.CarField, modifier, triggers)
st.CdrField = Modify(st.CdrField, modifier, triggers)
st.CarField = modify(st.CarField, modifier, targetCond)
st.CdrField = modify(st.CdrField, modifier, targetCond)
}

return sexp
Expand Down
56 changes: 0 additions & 56 deletions evaluator/backquote.go

This file was deleted.

200 changes: 179 additions & 21 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import (
)

var (
Nil = &object.Nil{}
BackQuote = &object.Symbol{Name: "backquote"}
Nil = &object.Nil{}
)

func Eval(sexp ast.SExpression, env *object.Environment) object.Object {
Expand Down Expand Up @@ -91,14 +90,6 @@ func evalMinusPrefix(right object.Object) object.Object {
}

func evalSymbol(symbol *ast.Symbol, env *object.Environment) object.Object {
if symbol.Token.Type == token.BACKQUOTE && symbol.Value == "backquote" {
return BackQuote
}

if specialForm, ok := specialForms[symbol.Value]; ok {
return specialForm
}

if val, ok := env.Get(symbol.Value); ok {
return val
}
Expand All @@ -112,24 +103,38 @@ func evalSymbol(symbol *ast.Symbol, env *object.Environment) object.Object {

// evaluate cdr of the cons cell as arguments to the command car
func evalList(sexp *ast.ConsCell, env *object.Environment) object.Object {
// Evaluate the car of the cons cell
car := Eval(sexp.Car(), env)
if isError(car) {
return car
switch car := sexp.Car().(type) {
case *ast.Symbol:
return evalNormalForm(sexp, env)
case *ast.ConsCell:
if isLambdaExpression(car) {
return evalNormalForm(sexp, env)
}
case *ast.SpecialForm:
return evalSpecialForm(sexp, env)
}

// check if the car is a backquote
if _, ok := car.(*object.Symbol); ok && car == BackQuote {
return evalBackquote(sexp.Cdr(), env)
return newError("unknown operator type: %T", sexp.Car())
}

func isLambdaExpression(consCell *ast.ConsCell) bool {
spForm, ok := consCell.Car().(*ast.SpecialForm)
if !ok {
return false
}

// check if the car is a special form
if specialForm, ok := car.(*object.SpecialForm); ok {
return specialForm.Fn(sexp.Cdr(), env)
return spForm.Token.Type == token.LAMBDA
}

func evalNormalForm(consCell *ast.ConsCell, env *object.Environment) object.Object {
// Evaluate the car of the cons cell
car := Eval(consCell.Car(), env)
if isError(car) {
return car
}

// Evaluate the arguments
args := evalArgs(sexp.Cdr(), env)
args := evalArgs(consCell.Cdr(), env)
if len(args) == 1 && isError(args[0]) {
return args[0]
}
Expand Down Expand Up @@ -208,3 +213,156 @@ func extendFunctionEnv(fn *object.Function, args []object.Object) (*object.Envir

return env, nil
}

func evalSpecialForm(sexp *ast.ConsCell, env *object.Environment) object.Object {
spForm, ok := sexp.Car().(*ast.SpecialForm)
if !ok {
return newError("expect special form, got %T", sexp.Car())
}

switch spForm.Value {
case "lambda":
return evalLambda(sexp, env)
case "quote":
return evalQuote(sexp)
case "backquote":
return evalBackquote(sexp, env)
}

return newError("unknown special form: %s", spForm.Value)
}

func evalLambda(sexp *ast.ConsCell, env *object.Environment) object.Object {
spForm, ok := sexp.Car().(*ast.SpecialForm)
if !ok {
return newError("expect special form, got %T", sexp.Car())
}
if spForm.Token.Type != token.LAMBDA {
return newError("expect special form lambda, got %s", spForm.Token.Type)
}

cdr, ok := sexp.Cdr().(*ast.ConsCell)
if !ok {
return newError("not defined lambda parameters")
}

params, err := evalLambdaParams(cdr.Car())
if err != nil {
return newError(err.Error())
}

cddr, ok := cdr.Cdr().(*ast.ConsCell)
if !ok {
return newError("not defined lambda body")
}

return &object.Function{
Parameters: params,
Body: cddr.Car(),
Env: env,
}
}

func evalLambdaParams(sexp ast.SExpression) ([]*ast.Symbol, error) {
params := []*ast.Symbol{}

if _, ok := sexp.(*ast.Nil); ok {
return params, nil
}

consCell, ok := sexp.(*ast.ConsCell)
if !ok {
return nil, fmt.Errorf("parameters must be a list, got %T", sexp)
}

for {
symbol, ok := consCell.Car().(*ast.Symbol)
if !ok {
return nil, fmt.Errorf("parameter must be a symbol, got %T", consCell.Car())
}
params = append(params, symbol)

switch cdr := consCell.Cdr().(type) {
case *ast.Nil:
return params, nil
case *ast.ConsCell:
consCell = cdr
default:
return nil, fmt.Errorf("parameters must be a list, got %T", consCell.Cdr())
}
}
}

func evalQuote(sexp *ast.ConsCell) object.Object {
spForm, ok := sexp.Car().(*ast.SpecialForm)
if !ok {
return newError("expect special form, got %T", sexp.Car())
}
if spForm.Token.Type != token.QUOTE {
return newError("expect special form quote, got %s", spForm.Token.Type)
}

cdr, ok := sexp.Cdr().(*ast.ConsCell)
if !ok {
return newError("not defined quote expression")
}

return &object.Quote{
SExpression: cdr.Car(),
}
}

func evalBackquote(sexp *ast.ConsCell, env *object.Environment) object.Object {
spForm, ok := sexp.Car().(*ast.SpecialForm)
if !ok {
return newError("expect special form, got %T", sexp.Car())
}
if spForm.Token.Type != token.BACKQUOTE {
return newError("expect special form backquote, got %s", spForm.Token.Type)
}

cdr, ok := sexp.Cdr().(*ast.ConsCell)
if !ok {
return newError("not defined backquote expression")
}

unquoted := evalUnquote(cdr.Car(), env)

return &object.Quote{
SExpression: unquoted,
}
}

func evalUnquote(sexp ast.SExpression, env *object.Environment) ast.SExpression {
return ast.ModifyByUnquote(sexp, func(sexp ast.SExpression) ast.SExpression {
consCell, ok := sexp.(*ast.ConsCell)
if !ok {
return sexp
}

if car, ok := consCell.Car().(*ast.SpecialForm); !ok || car.Value != "unquote" {
return sexp
}

// evaluate unquoted s-expression
cdr := consCell.Cdr().(*ast.ConsCell)
evaluated := Eval(cdr.Car(), env)

return convertObjectToSExpression(evaluated)
})
}

func convertObjectToSExpression(obj object.Object) ast.SExpression {
switch obj := obj.(type) {
case *object.Integer:
t := token.Token{
Type: token.INT,
Literal: fmt.Sprintf("%d", obj.Value),
}
return &ast.IntegerLiteral{Token: t, Value: obj.Value}
case *object.Quote:
return obj.SExpression
default:
return nil
}
}
Loading
Loading