-
Notifications
You must be signed in to change notification settings - Fork 33
/
compile.go
131 lines (114 loc) · 2.49 KB
/
compile.go
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
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"
"github.com/nokia/ntt/internal/fs"
"github.com/nokia/ntt/ttcn3"
"github.com/nokia/ntt/ttcn3/syntax"
"github.com/spf13/cobra"
)
var (
CompileCommand = &cobra.Command{
Use: "compile",
Short: "Compile TTCN-3 sources and generate output for other tools",
Long: `Compile TTCN-3 sources and generate output for other tools.`,
RunE: compile,
}
format string
)
func init() {
CompileCommand.Flags().StringVarP(&format, "generator", "G", "stdout", "generator to use (default stdout)")
}
func compile(cmd *cobra.Command, args []string) error {
srcs, err := fs.TTCN3Files(Project.Sources...)
if err != nil {
return err
}
imports, err := fs.TTCN3Files(Project.Imports...)
if err != nil {
return err
}
files := append(srcs, imports...)
if format == "stdout" {
writeSource(os.Stdout, files...)
return nil
}
generator, err := exec.LookPath(fmt.Sprintf("ntt-gen-%s", format))
if err != nil {
return fmt.Errorf("could not find generator %q", format)
}
proc := exec.Command(generator)
proc.Stdout = os.Stdout
proc.Stderr = os.Stderr
stdin, err := proc.StdinPipe()
if err != nil {
return err
}
go func() {
defer stdin.Close()
writeSource(stdin, files...)
}()
if err := proc.Run(); err != nil {
return err
}
return nil
}
func writeSource(w io.Writer, files ...string) {
for _, file := range files {
src := buildSource(file)
b, err := json.MarshalIndent(src, "", " ")
if err != nil {
fatal(err)
}
w.Write(b)
}
}
func buildSource(file string) ttcn3.Source {
src := ttcn3.Source{
Filename: file,
}
var visit func(n syntax.Node)
visit = func(n syntax.Node) {
if n == nil {
return
}
k := strings.TrimPrefix(strings.TrimPrefix(fmt.Sprintf("%T", n), "*"), "syntax.")
begin := int(n.Pos())
end := int(n.End())
switch n := n.(type) {
case syntax.Token:
if n == nil {
break
}
src.Events = append(src.Events, ttcn3.NodeEvent{
Kind: "AddToken",
Text: n.String(),
Offs: begin,
Len: end - begin,
})
default:
src.Events = append(src.Events, ttcn3.NodeEvent{
Kind: "Open" + k,
Offs: begin,
Len: end - begin,
})
idx := len(src.Events) - 1
for _, c := range n.Children() {
visit(c)
}
src.Events = append(src.Events, ttcn3.NodeEvent{
Kind: "Close" + k,
Offs: begin,
Len: end - begin,
Other: idx,
})
src.Events[idx].Other = len(src.Events) - 1
}
}
visit(ttcn3.ParseFile(file).Root)
return src
}