aboutsummaryrefslogtreecommitdiff
path: root/cmd/vartan/compile.go
blob: 3753cd0559b3ec3b5b65d2c77798582d13efa380 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	verr "github.com/nihei9/vartan/error"
	"github.com/nihei9/vartan/grammar"
	"github.com/nihei9/vartan/spec"
	"github.com/spf13/cobra"
)

var compileFlags = struct {
	grammar *string
	output  *string
}{}

func init() {
	cmd := &cobra.Command{
		Use:     "compile",
		Short:   "Compile a grammar into a parsing table",
		Example: `  cat grammar | vartan compile -o grammar.json`,
		RunE:    runCompile,
	}
	compileFlags.grammar = cmd.Flags().StringP("grammar", "g", "", "grammar file path (default stdin)")
	compileFlags.output = cmd.Flags().StringP("output", "o", "", "output file path (default stdout)")
	rootCmd.AddCommand(cmd)
}

func runCompile(cmd *cobra.Command, args []string) (retErr error) {
	var tmpDirPath string
	defer func() {
		if tmpDirPath == "" {
			return
		}
		os.RemoveAll(tmpDirPath)
	}()

	grmPath := *compileFlags.grammar
	defer func() {
		v := recover()
		if v != nil {
			err, ok := v.(error)
			if !ok {
				retErr = fmt.Errorf("an unexpected error occurred: %v\n", v)
				fmt.Fprintln(os.Stderr, retErr)
				return
			}

			retErr = err
		}

		if retErr != nil {
			specErrs, ok := retErr.(verr.SpecErrors)
			if ok {
				for _, err := range specErrs {
					if *compileFlags.grammar != "" {
						err.FilePath = grmPath
						err.SourceName = grmPath
					} else {
						err.FilePath = grmPath
						err.SourceName = "stdin"
					}
				}
			}
			fmt.Fprintln(os.Stderr, retErr)
		}
	}()

	if grmPath == "" {
		var err error
		tmpDirPath, err = os.MkdirTemp("", "vartan-compile-*")
		if err != nil {
			return err
		}

		src, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			return err
		}

		grmPath = filepath.Join(tmpDirPath, "stdin.vr")
		err = ioutil.WriteFile(grmPath, src, 0600)
		if err != nil {
			return err
		}
	}

	gram, err := readGrammar(grmPath)
	if err != nil {
		return err
	}

	var descFileName string
	{
		_, grmFileName := filepath.Split(grmPath)
		descFileName = fmt.Sprintf("%v.desc", strings.TrimSuffix(grmFileName, ".vr"))
	}

	cgram, err := grammar.Compile(gram, grammar.EnableDescription(descFileName))
	if err != nil {
		return err
	}

	err = writeCompiledGrammar(cgram, *compileFlags.output)
	if err != nil {
		return fmt.Errorf("Cannot write a compiled grammar: %w", err)
	}

	return nil
}

func readGrammar(path string) (grm *grammar.Grammar, retErr error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("Cannot open the grammar file %s: %w", path, err)
	}
	defer f.Close()

	ast, err := spec.Parse(f)
	if err != nil {
		return nil, err
	}

	b := grammar.GrammarBuilder{
		AST: ast,
	}
	return b.Build()
}

func writeCompiledGrammar(cgram *spec.CompiledGrammar, path string) error {
	out, err := json.Marshal(cgram)
	if err != nil {
		return err
	}
	w := os.Stdout
	if path != "" {
		f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
		if err != nil {
			return fmt.Errorf("Cannot open the output file %s: %w", path, err)
		}
		defer f.Close()
		w = f
	}
	fmt.Fprintf(w, "%v\n", string(out))
	return nil
}