Debian Codegraph @

tools/gen-tokens/main.go

raw symbols SCIP
1 // Command gen-tokens generates go representations of JavaScript tokens.
2 package main
3
4 import (
5 "embed"
6 "flag"
7 "fmt"
8 "log"
9 "os"
10 "os/exec"
11 "strings"
12 "text/template"
13
14 "gopkg.in/yaml.v3"
15 )
16
17 //go:embed .gen-tokens.yaml
18 var configData []byte
19
20 //go:embed templates/*
21 var templates embed.FS
22
23 // token represents a JavaScript token.
24 type token struct {
25 Group string `yaml:"group"`
26 Name string `yaml:"name"`
27 Symbol string `yaml:"symbol"`
28 Future bool `yaml:"future"`
29 Strict bool `yaml:"strict"`
30 }
31
32 // config represents our configuration.
33 type config struct {
34 Tokens []token `yaml:"tokens"`
35 }
36
37 // generate generates the context file writing the output to filename.
38 func generate(filename string) (err error) {
39 var cfg config
40 if err = yaml.Unmarshal(configData, &cfg); err != nil {
41 return fmt.Errorf("decode config: %w", err)
42 }
43
44 tmpl := template.New("base").Funcs(template.FuncMap{
45 "toLower": strings.ToLower,
46 })
47
48 tmpl, err = tmpl.ParseFS(templates, "templates/*.tmpl")
49 if err != nil {
50 return fmt.Errorf("parse templates: %w", err)
51 }
52
53 output, err := os.Create(filename) //nolint:gosec
54 if err != nil {
55 return fmt.Errorf("open output: %w", err)
56 }
57
58 defer func() {
59 if errc := output.Close(); err == nil && errc != nil {
60 err = errc
61 }
62 }()
63
64 if err = tmpl.ExecuteTemplate(output, "root.tmpl", cfg); err != nil {
65 return fmt.Errorf("execute template: %w", err)
66 }
67
68 cmd := exec.Command("gofmt", "-w", filename)
69 buf, err := cmd.CombinedOutput()
70 if err != nil {
71 return fmt.Errorf("format output %q: %w", string(buf), err)
72 }
73
74 return nil
75 }
76
77 func main() {
78 var filename string
79 flag.StringVar(&filename, "output", "token_const.go", "the filename to write the generated code to")
80 if err := generate(filename); err != nil {
81 log.Fatal(err)
82 }
83 }