From f80f57a531f3e0c865507ca309d08acf1fd8c00c Mon Sep 17 00:00:00 2001 From: Willyboar Date: Fri, 19 May 2023 15:45:08 +0300 Subject: [PATCH] Implement display blocks and tests --- src/glove.gleam | 25 +++++++++++++++++++------ test/glove_test.gleam | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/glove.gleam b/src/glove.gleam index e2e30d3..53d1857 100644 --- a/src/glove.gleam +++ b/src/glove.gleam @@ -1,5 +1,7 @@ import gleam/int +import gleam/string import gleam/option.{None, Option, Some} +import gleam/list // QBE Comparison Operators pub type Comp { @@ -185,7 +187,12 @@ pub type TypeDef { // Display function for TypeDef pub fn display_type_def(def: TypeDef) -> String { - todo + let align_str = case def.align { + Some(align) -> "align " <> int.to_string(align) <> " " + None -> "" + } + + "type :" <> def.name <> " = " <> align_str <> "{ " <> " }" } // QBE Data definition item @@ -219,8 +226,8 @@ pub type Statement { } // Display function for Statement -pub fn display_statement(state: Statement) -> String { - case state { +pub fn display_statement(stmt: Statement) -> String { + case stmt { Assign(val, typ, inst) -> display_value(val) <> " =" <> display_type(typ) <> " " <> display_inst( inst, @@ -231,12 +238,18 @@ pub fn display_statement(state: Statement) -> String { // Function block with a label pub type Block { - Block(label: String, statements: #(Statement)) + Block(label: String, statements: List(Statement)) } // Display function for block pub fn display_block(block: Block) -> String { - todo + let label = block.label + let statements = + block.statements + |> list.map(display_statement) + |> string.join("\n") + + label <> ":\n" <> statements } /// Adds a new instruction to the block @@ -312,7 +325,7 @@ pub fn private_with_section() -> Nil { todo } -/// A complete IL file +// A complete IL file pub type Module { Module(functions: #(Function), types: #(TypeDef), data: #(DataDef)) } diff --git a/test/glove_test.gleam b/test/glove_test.gleam index 3286882..8db95e8 100644 --- a/test/glove_test.gleam +++ b/test/glove_test.gleam @@ -1,4 +1,5 @@ import gleam/option.{None, Some} +import gleam/list import gleeunit import gleeunit/should import glove @@ -83,3 +84,27 @@ pub fn display_statement_test() { |> glove.display_statement |> should.equal("ret") } + +// Tests for QBE.Block Display +pub fn display_block_test() { + // Test empty block + let empty_block = glove.Block("label", []) + empty_block + |> glove.display_block() + |> should.equal("label:\n") + + // Test block with statements + let statements = [ + glove.Assign( + glove.Temporary("temp1"), + glove.Word, + glove.Add(glove.Temporary("a"), glove.Temporary("b")), + ), + glove.Volatile(glove.Ret(Some(glove.Temporary("temp1")))), + ] + + let block_with_statements = glove.Block("label", statements) + block_with_statements + |> glove.display_block + |> should.equal("label:\n%temp1 =w add %a, %b\nret %temp1") +}