From 9d18f62407bec90f95919356bfd6711c7ba7923c Mon Sep 17 00:00:00 2001 From: Ibrahim Muftee Date: Fri, 24 Jul 2026 16:11:27 -0500 Subject: begin chapter 2.6 --- ast/ast.odin | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'ast') diff --git a/ast/ast.odin b/ast/ast.odin index 67039a3..8007e54 100644 --- a/ast/ast.odin +++ b/ast/ast.odin @@ -1,6 +1,9 @@ package ast import "../token" +import "core:bytes" + +THIRTY_TWO_KILOBYTES := 262144 Node :: union { Program, @@ -28,6 +31,11 @@ Return_Statement :: struct { return_value: Expression, } +Expression_Statement :: struct { + token: token.Token, + expression: Expression, +} + Expression :: union { Identifier, } @@ -50,6 +58,8 @@ token_literal :: proc(node: Node) -> (literal: string) { case Let_Statement: literal = token.literal(s.token) case Return_Statement: + literal = token.literal(s.token) + case Expression_Statement: literal = token.literal(s.token) } case Expression: @@ -60,3 +70,42 @@ token_literal :: proc(node: Node) -> (literal: string) { } return literal } + +node_to_string :: proc(node: Node) -> string { + out: bytes.Buffer + bytes.buffer_init_allocator(&out, 4, THIRTY_TWO_KILOBYTES, context.temp_allocator) + + switch n in node { + case Program: + for stmt in n { + bytes.buffer_write_string(&out, node_to_string(n)) + } + case Statement: + switch s in n { + case Let_Statement: + bytes.buffer_write_string(&out, token.literal(s.token) + " ") + bytes.buffer_write_string(&out, node_to_string(s.name)) + bytes.buffer_write_string(&out, " = ") + if s.value != nil { + bytes.buffer_write_string(&out, node_to_string(s.value)) + } + bytes.buffer_write_string(&out, ";") + case Return_Statement: + bytes.buffer_write_string(&out, token.literal(s.token) + " ") + if s.return_value != nil { + bytes.buffer_write_string(&out, node_to_string(s.return_value)) + } + case Expression_Statement: + if s.expression != nil { + bytes.buffer_write_string(&out, node_to_string(s.expression)) + } + } + case Expression: + switch e in n { + case Identifier: + literal = token.literal(e.token) + } + } + + return bytes.buffer_to_string(&out) +} -- cgit v1.2.3