From c07b5f8fd0cf8bd1654825dcf7401d670fda4c0a Mon Sep 17 00:00:00 2001 From: Bobby Date: Wed, 24 Jan 2024 21:03:26 +0000 Subject: If-Else Parsing --- ast/ast.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'ast') diff --git a/ast/ast.go b/ast/ast.go index b2634d4..31b1be1 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -88,6 +88,24 @@ func (i *Identifier) String() string { return i.Value } +// BlockStatement represents a block statement. +type BlockStatement struct { + Token tokens.Token // the token.LBRACE token + Statements []Statement +} + +func (bs *BlockStatement) statementNode() {} +func (bs *BlockStatement) TokenLiteral() string { return bs.Token.Literal } +func (bs *BlockStatement) String() string { + var out bytes.Buffer + + for _, s := range bs.Statements { + out.WriteString(s.String()) + } + + return out.String() +} + // ReturnStatement represents a return statement. type ReturnStatement struct { Token tokens.Token // the token.RETURN token @@ -204,3 +222,28 @@ func (b *Boolean) TokenLiteral() string { func (b *Boolean) String() string { return b.Token.Literal } + +type IfExpression struct { + Token tokens.Token // the 'if' token + Condition Expression + Consequence *BlockStatement + Alternative *BlockStatement +} + +func (ie *IfExpression) expressionNode() {} +func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal } +func (ie *IfExpression) String() string { + var out bytes.Buffer + + out.WriteString("if") + out.WriteString(ie.Condition.String()) + out.WriteString(" ") + out.WriteString(ie.Consequence.String()) + + if ie.Alternative != nil { + out.WriteString("else ") + out.WriteString(ie.Alternative.String()) + } + + return out.String() +} -- cgit v1.2.3