aboutsummaryrefslogtreecommitdiff
path: root/cmd/hlang/compile.go
blob: b1455b74194af24ea6d2ce6b512674d91eaa4f9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"strings"

	"github.com/eaburns/peggy/peg"
	"within.website/x/cmd/hlang/h"
	"within.website/x/cmd/hlang/nguh"
)

// CompiledProgram is a fully parsed and compiled h program.
type CompiledProgram struct {
	Source string `json:"src"`
	Binary []byte `json:"bin"`
	AST    string `json:"ast"`
}

func compile(source string) (*CompiledProgram, error) {
	tree, err := h.Parse(source)
	if err != nil {
		return nil, err
	}

	var sb strings.Builder
	err = peg.PrettyWrite(&sb, tree)
	if err != nil {
		return nil, err
	}

	wasmBytes, err := nguh.Compile(tree)
	if err != nil {
		return nil, err
	}

	result := CompiledProgram{
		Source: source,
		AST:    sb.String(),
		Binary: wasmBytes,
	}

	return &result, nil
}