-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.go
More file actions
66 lines (59 loc) · 1.33 KB
/
codegen.go
File metadata and controls
66 lines (59 loc) · 1.33 KB
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
package codegen
import (
"fmt"
"strings"
"github.com/bitcode-framework/go-json/lang"
)
// CodeGenerator generates source code from a compiled go-json program.
type CodeGenerator interface {
Generate(program *lang.CompiledProgram) (string, error)
Language() string
}
func indent(level int) string {
return strings.Repeat("\t", level)
}
func commentFromMeta(meta *lang.NodeMeta) string {
if meta.Comment != "" {
return meta.Comment
}
if len(meta.Comments) > 0 {
return strings.Join(meta.Comments, "\n")
}
return ""
}
func transformExpr(expr string, lang string) string {
if lang == "go" {
return expr
}
if lang == "javascript" {
expr = strings.ReplaceAll(expr, "&&", "&&")
expr = strings.ReplaceAll(expr, "||", "||")
return expr
}
if lang == "python" {
expr = strings.ReplaceAll(expr, "&&", " and ")
expr = strings.ReplaceAll(expr, "||", " or ")
expr = strings.ReplaceAll(expr, "!", "not ")
expr = strings.ReplaceAll(expr, "true", "True")
expr = strings.ReplaceAll(expr, "false", "False")
expr = strings.ReplaceAll(expr, "nil", "None")
return expr
}
return expr
}
func formatValue(v any) string {
if v == nil {
return "nil"
}
switch val := v.(type) {
case string:
return fmt.Sprintf("%q", val)
case bool:
if val {
return "true"
}
return "false"
default:
return fmt.Sprintf("%v", val)
}
}