From 5daf4f9aa2308004dc7bc7ba977a4de20df44351 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Tue, 6 May 2025 17:49:04 -0500 Subject: [PATCH] add nil literal --- compiler/compiler.go | 4 ++++ lexer/lexer.go | 3 +++ parser/ast.go | 7 +++++++ parser/parser.go | 5 +++++ vm/vm.go | 4 ++-- 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/compiler/compiler.go b/compiler/compiler.go index 37f8a1e..edb7e09 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -136,6 +136,10 @@ func (c *compiler) compileExpression(expr parser.Expression) { constIndex := c.addConstant(e.Value) c.emit(types.OpConstant, constIndex) + case *parser.NilLiteral: + constIndex := c.addConstant(nil) + c.emit(types.OpConstant, constIndex) + case *parser.Identifier: nameIndex := c.addConstant(e.Value) diff --git a/lexer/lexer.go b/lexer/lexer.go index aa6b4f7..ccf8001 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -37,6 +37,7 @@ const ( TokenOr TokenNot TokenElseIf + TokenNil ) type Token struct { @@ -166,6 +167,8 @@ func (l *Lexer) NextToken() Token { tok.Type = TokenOr case "not": tok.Type = TokenNot + case "nil": + tok.Type = TokenNil default: tok.Type = TokenIdentifier } diff --git a/parser/ast.go b/parser/ast.go index 0c82620..2311ff4 100644 --- a/parser/ast.go +++ b/parser/ast.go @@ -156,3 +156,10 @@ type BooleanLiteral struct { func (bl *BooleanLiteral) expressionNode() {} func (bl *BooleanLiteral) TokenLiteral() string { return bl.Token.Value } + +type NilLiteral struct { + Token lexer.Token +} + +func (nl *NilLiteral) expressionNode() {} +func (nl *NilLiteral) TokenLiteral() string { return nl.Token.Value } diff --git a/parser/parser.go b/parser/parser.go index 8f04bbd..a3917fa 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -74,6 +74,7 @@ func New(l *lexer.Lexer) *Parser { p.registerPrefix(lexer.TokenTrue, p.parseBooleanLiteral) p.registerPrefix(lexer.TokenFalse, p.parseBooleanLiteral) p.registerPrefix(lexer.TokenNot, p.parsePrefixExpression) + p.registerPrefix(lexer.TokenNil, p.parseNilLiteral) // Initialize infix parse functions p.infixParseFns = make(map[lexer.TokenType]infixParseFn) @@ -573,3 +574,7 @@ func (p *Parser) parseUnexpectedToken() Expression { p.curToken.Line, p.curToken.Value)) return nil } + +func (p *Parser) parseNilLiteral() Expression { + return &NilLiteral{Token: p.curToken} +} diff --git a/vm/vm.go b/vm/vm.go index cb9e17a..9fb5ca6 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -190,7 +190,7 @@ func (vm *VM) Run(bytecode *types.Bytecode) { case types.TypeBoolean: fmt.Println(value.Data.(bool)) case types.TypeNull: - fmt.Println("null") + fmt.Println("nil") case types.TypeTable: fmt.Println(vm.formatTable(value.Data.(*types.Table))) } @@ -465,7 +465,7 @@ func (vm *VM) formatValue(value types.Value) string { case types.TypeBoolean: return fmt.Sprintf("%v", value.Data.(bool)) case types.TypeNull: - return "null" + return "nil" case types.TypeTable: return vm.formatTable(value.Data.(*types.Table)) default: