From e22a844dd47be07acec8e1662e9abe7347d9d4fc Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Mon, 9 Jun 2025 09:58:47 -0500 Subject: [PATCH] true/false/nil --- parser/ast.go | 19 +++++++++++++++++++ parser/parser.go | 11 +++++++++++ parser/token.go | 8 +++++++- 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/parser/ast.go b/parser/ast.go index f1aa459..b90017a 100644 --- a/parser/ast.go +++ b/parser/ast.go @@ -67,6 +67,25 @@ type StringLiteral struct { func (sl *StringLiteral) expressionNode() {} func (sl *StringLiteral) String() string { return fmt.Sprintf(`"%s"`, sl.Value) } +// BooleanLiteral represents boolean literals +type BooleanLiteral struct { + Value bool +} + +func (bl *BooleanLiteral) expressionNode() {} +func (bl *BooleanLiteral) String() string { + if bl.Value { + return "true" + } + return "false" +} + +// NilLiteral represents nil literal +type NilLiteral struct{} + +func (nl *NilLiteral) expressionNode() {} +func (nl *NilLiteral) String() string { return "nil" } + // InfixExpression represents binary operations type InfixExpression struct { Left Expression diff --git a/parser/parser.go b/parser/parser.go index 749172e..c8dd8da 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -29,6 +29,9 @@ func NewParser(lexer *Lexer) *Parser { p.registerPrefix(IDENT, p.parseIdentifier) p.registerPrefix(NUMBER, p.parseNumberLiteral) p.registerPrefix(STRING, p.parseStringLiteral) + p.registerPrefix(TRUE, p.parseBooleanLiteral) + p.registerPrefix(FALSE, p.parseBooleanLiteral) + p.registerPrefix(NIL, p.parseNilLiteral) p.registerPrefix(LPAREN, p.parseGroupedExpression) p.infixParseFns = make(map[TokenType]func(Expression) Expression) @@ -153,6 +156,14 @@ func (p *Parser) parseStringLiteral() Expression { return &StringLiteral{Value: p.curToken.Literal} } +func (p *Parser) parseBooleanLiteral() Expression { + return &BooleanLiteral{Value: p.curTokenIs(TRUE)} +} + +func (p *Parser) parseNilLiteral() Expression { + return &NilLiteral{} +} + func (p *Parser) parseGroupedExpression() Expression { p.nextToken() diff --git a/parser/token.go b/parser/token.go index dca0bd1..a2e7168 100644 --- a/parser/token.go +++ b/parser/token.go @@ -8,6 +8,9 @@ const ( IDENT TokenType = iota NUMBER STRING + TRUE + FALSE + NIL // Operators ASSIGN // = @@ -59,7 +62,10 @@ var precedences = map[TokenType]Precedence{ // lookupIdent checks if an identifier is a keyword func lookupIdent(ident string) TokenType { keywords := map[string]TokenType{ - "var": VAR, + "var": VAR, + "true": TRUE, + "false": FALSE, + "nil": NIL, } if tok, ok := keywords[ident]; ok {