From cf6dd4b0e5efa1f8041d5570497a5228c737c454 Mon Sep 17 00:00:00 2001 From: Bobby Date: Fri, 29 Mar 2024 20:19:31 +0000 Subject: Strings --- parser/parser.go | 8 ++++++++ parser/parser_test.go | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) (limited to 'parser') diff --git a/parser/parser.go b/parser/parser.go index 3fe3d9f..6ca88b3 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -71,6 +71,7 @@ func New(l *lexer.Lexer) *Parser { p.registerPrefix(tokens.IF, p.parseIfExpression) p.registerPrefix(tokens.FUNCTION, p.parseFunctionLiteral) p.registerPrefix(tokens.LPAREN, p.parseGroupedExpression) + p.registerPrefix(tokens.STRING, p.parseStringLiteral) // Initialize the infix parse functions. p.infixParseFns = make(map[tokens.TokenType]infixParseFn) @@ -436,6 +437,13 @@ func (p *Parser) parseCallArguments() []ast.Expression { return args } +func (p *Parser) parseStringLiteral() ast.Expression { + return &ast.StringLiteral{ + Token: p.curToken, + Value: p.curToken.Literal, + } +} + // curTokenIs returns true if the current token is of the given type. func (p *Parser) curTokenIs(t tokens.TokenType) bool { return p.curToken.Type == t diff --git a/parser/parser_test.go b/parser/parser_test.go index 08539b7..3a574a7 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -772,3 +772,22 @@ func TestCallExpressionParsing(t *testing.T) { testInfixExpression(t, exp.Arguments[1], 2, "*", 3) testInfixExpression(t, exp.Arguments[2], 4, "+", 5) } + +func TestStringLiteralExpression(t *testing.T) { + input := `"hello world";` + + var l *lexer.Lexer = lexer.New(input) + var p *Parser = New(l) + var program *ast.Program = p.ParseProgram() + checkParserErrors(t, p) + + stmt := program.Statements[0].(*ast.ExpressionStatement) + literal, ok := stmt.Expression.(*ast.StringLiteral) + if !ok { + t.Fatalf("exp not *ast.StringLiteral. got=%T", stmt.Expression) + } + + if literal.Value != "hello world" { + t.Errorf("literal.Value not %q. got=%q", "hello world", literal.Value) + } +} -- cgit v1.2.3