about summary refs log tree commit diff
path: root/pkg/lang/vm/text
diff options
context:
space:
mode:
authorMel <einebeere@gmail.com>2022-05-27 16:44:22 +0000
committerGitHub <noreply@github.com>2022-05-27 16:49:02 +0000
commit47c4cd3705bee9d7154c42ce95aef6f8a19e0661 (patch)
treef6b2d502cbc256914a6f7181e2cf623460f9d912 /pkg/lang/vm/text
parentc2d4bf51de9a2d721168c62b14b89f5281ed366e (diff)
downloadjinx-47c4cd3705bee9d7154c42ce95aef6f8a19e0661.tar.zst
jinx-47c4cd3705bee9d7154c42ce95aef6f8a19e0661.zip
Add debug info to compiled VM code
Diffstat (limited to 'pkg/lang/vm/text')
-rw-r--r--pkg/lang/vm/text/compiler.go8
-rw-r--r--pkg/lang/vm/text/compiler_test.go29
2 files changed, 36 insertions, 1 deletions
diff --git a/pkg/lang/vm/text/compiler.go b/pkg/lang/vm/text/compiler.go
index 2732aea..1480171 100644
--- a/pkg/lang/vm/text/compiler.go
+++ b/pkg/lang/vm/text/compiler.go
@@ -31,6 +31,7 @@ func NewCompiler(src io.Reader) *Compiler {
 
 func (cpl *Compiler) Compile() (code.Code, error) {
 	res := []byte{}
+	info := code.NewDebugInfo("unknown file")
 
 	for {
 		_, eof, err := cpl.src.Peek()
@@ -48,6 +49,11 @@ func (cpl *Compiler) Compile() (code.Code, error) {
 		}
 
 		cpl.codePos += len(line)
+
+		if line != nil {
+			info.AppendLine(cpl.codePos-1, cpl.src.Loc().Row-1)
+		}
+
 		res = append(res, line...)
 	}
 
@@ -55,7 +61,7 @@ func (cpl *Compiler) Compile() (code.Code, error) {
 		return code.Code{}, err
 	}
 
-	return code.New(res), nil
+	return code.New(res, info), nil
 }
 
 func (cpl *Compiler) compileLine() ([]byte, error) {
diff --git a/pkg/lang/vm/text/compiler_test.go b/pkg/lang/vm/text/compiler_test.go
index 237e884..56b886d 100644
--- a/pkg/lang/vm/text/compiler_test.go
+++ b/pkg/lang/vm/text/compiler_test.go
@@ -129,6 +129,35 @@ func TestLabels(t *testing.T) {
 	require.Equal(t, joinSlices(parts), res.Code())
 }
 
+func TestDebugInfo(t *testing.T) {
+	src := `
+	push_int 1
+	push_int 2
+
+	add
+	add
+	
+	@1:
+		nop
+		ret
+	`
+
+	c := text.NewCompiler(strings.NewReader(src))
+	res, err := c.Compile()
+	require.NoError(t, err)
+
+	expected := code.NewDebugInfo("unknown file")
+
+	expected.AppendLine(8, 1)
+	expected.AppendLine(17, 2)
+	expected.AppendLine(18, 4)
+	expected.AppendLine(19, 5)
+	expected.AppendLine(20, 8)
+	expected.AppendLine(21, 9)
+
+	require.Equal(t, expected, *res.Debug())
+}
+
 func opBin(op code.Op) []byte {
 	return []byte{byte(op)}
 }