aboutsummaryrefslogtreecommitdiff
path: root/cli/cmd/compile.go
blob: 23aa1209945131b8427d8e888d440eb16ce65521 (plain) (blame)
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
43
44
45
46
47
48
49
package cmd

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/nihei9/maleeni/compiler"
	"github.com/nihei9/maleeni/spec"
	"github.com/spf13/cobra"
)

func init() {
	cmd := &cobra.Command{
		Use:     "compile",
		Short:   "Compile a lexical specification into a DFA",
		Long:    `compile takes a lexical specification and generates a DFA accepting the tokens described in the specification.`,
		Example: `  cat lexspec.json | maleeni compile > clexspec.json`,
		RunE:    runCompile,
	}
	rootCmd.AddCommand(cmd)
}

func runCompile(cmd *cobra.Command, args []string) error {
	var lspec *spec.LexSpec
	{
		data, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			return err
		}
		lspec = &spec.LexSpec{}
		err = json.Unmarshal(data, lspec)
		if err != nil {
			return err
		}
	}
	clspec, err := compiler.Compile(lspec)
	if err != nil {
		return err
	}
	out, err := json.Marshal(clspec)
	if err != nil {
		return err
	}
	fmt.Fprintf(os.Stdout, "%v\n", string(out))

	return nil
}