Skip to content

Commit

Permalink
feat: parse string expression
Browse files Browse the repository at this point in the history
  • Loading branch information
Aden-Q committed May 12, 2024
1 parent 9f394cf commit d1765a6
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
25 changes: 25 additions & 0 deletions internal/ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,31 @@ func NewBooleanExpression(value bool) *BooleanExpression {
}
}

// StringExpression implements the Expression interface
type StringExpression struct {
// the string token
Token token.Token
Value string
}

func (se *StringExpression) expressionNode() {}

func (se *StringExpression) TokenLiteral() string {
return se.Token.Literal
}

func (se *StringExpression) String() string {
return se.Token.Literal
}

// NewStringExpression creates a String node
func NewStringExpression(literal string) *StringExpression {
return &StringExpression{
Token: token.New(token.STRING, literal),
Value: literal,
}
}

// IfExpression implements the Expression interface
type IfExpression struct {
// the if token
Expand Down
6 changes: 6 additions & 0 deletions internal/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ func New(l lexer.Lexer) Parser {
// handler for boolean expression
p.registerPrefixParseFn(token.TRUE, p.parseBoolean)
p.registerPrefixParseFn(token.FALSE, p.parseBoolean)
// handler for string expression
p.registerPrefixParseFn(token.STRING, p.parseString)
// handler for grouped expression
p.registerPrefixParseFn(token.LPAREN, p.parseGroupedExpression)
// handler for if expression
Expand Down Expand Up @@ -276,6 +278,10 @@ func (p *parser) parseBoolean() (ast.Expression, error) {
return ast.NewBooleanExpression(value), nil
}

func (p *parser) parseString() (ast.Expression, error) {
return ast.NewStringExpression(p.curToken.Literal), nil
}

func (p *parser) parseGroupedExpression() (ast.Expression, error) {
// move forward to make p.curToken point to the first token after the ( token
p.nextToken()
Expand Down
18 changes: 18 additions & 0 deletions internal/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,24 @@ var _ = Describe("Parser", func() {
Expect(errs).To(Equal(expectedErrors))
})

It("string expressions", func() {
text = `
"foo";
"foo bar";
`
expectedProgram := &ast.Program{
Statements: []ast.Statement{
ast.NewExpressionStatement(ast.NewStringExpression("foo")),
ast.NewExpressionStatement(ast.NewStringExpression("foo bar")),
},
}
expectedErrors := []error{}

program, errs = p.ParseProgram(text)
Expect(program).To(Equal(expectedProgram))
Expect(errs).To(Equal(expectedErrors))
})

It("if expressions", func() {
text = `
if (x < y) { x; };
Expand Down

0 comments on commit d1765a6

Please sign in to comment.