about summary refs log tree commit diff
path: root/pkg/lang/vm/text/decompiler_test.go
diff options
context:
space:
mode:
authorMel <einebeere@gmail.com>2022-06-12 14:48:52 +0000
committerGitHub <noreply@github.com>2022-06-12 14:48:52 +0000
commit565b141c38da7c9c86499c67bf62ac7dd69a5aae (patch)
tree766e4ee593cbafb1c534c7620c1811cd31f084c3 /pkg/lang/vm/text/decompiler_test.go
parente1ffe8f4967002eccda902a01518894e5b8e9ed4 (diff)
downloadjinx-565b141c38da7c9c86499c67bf62ac7dd69a5aae.tar.zst
jinx-565b141c38da7c9c86499c67bf62ac7dd69a5aae.zip
Add simple Lang BC Decompiler
Diffstat (limited to 'pkg/lang/vm/text/decompiler_test.go')
-rw-r--r--pkg/lang/vm/text/decompiler_test.go75
1 files changed, 75 insertions, 0 deletions
diff --git a/pkg/lang/vm/text/decompiler_test.go b/pkg/lang/vm/text/decompiler_test.go
new file mode 100644
index 0000000..01e49b0
--- /dev/null
+++ b/pkg/lang/vm/text/decompiler_test.go
@@ -0,0 +1,75 @@
+package text_test
+
+import (
+	"jinx/pkg/lang/vm/text"
+	"strings"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+)
+
+func TestDecompileSimple(t *testing.T) {
+	src := `
+	push_int 1
+	push_int 2
+
+	add
+	`
+
+	expected := `
+	push_int 1
+	push_int 2
+	add
+	`
+
+	test(t, src, expected)
+}
+
+func TestDecompileValues(t *testing.T) {
+	src := `
+	push_int 1
+	push_string "foo"
+	push_float 3.14
+	push_function @foo
+	halt
+	@foo:
+		push_int 1
+		ret
+	`
+
+	// No label names yet.
+	expected := `
+	push_int 1
+	push_string "foo"
+	push_float 3.14
+	push_function @33
+	halt
+	push_int 1
+	ret
+	`
+
+	test(t, src, expected)
+}
+
+func test(t *testing.T, code string, expected string) {
+	expectedLines := strings.Split(expected, "\n")
+	trimmedExpectedLines := make([]string, 0, len(expectedLines))
+	for _, line := range expectedLines {
+		trimmedLine := strings.TrimSpace(line)
+		if trimmedLine == "" {
+			continue
+		}
+
+		trimmedExpectedLines = append(trimmedExpectedLines, trimmedLine)
+	}
+
+	trimmedExpected := strings.Join(trimmedExpectedLines, "\n")
+
+	comp := text.NewCompiler(strings.NewReader(code))
+	resCompiled, err := comp.Compile()
+	require.NoError(t, err)
+
+	decomp := text.NewDecompiler(resCompiled)
+	resDecompiled := decomp.Decompile()
+	require.Equal(t, trimmedExpected, resDecompiled)
+}