mirror of
https://github.com/ddidderr/wuffs.git
synced 2026-11-22 08:47:28 +01:00
60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
// Use of this source code is governed by a BSD-style license that can be found
|
|
// in the LICENSE file.
|
|
|
|
//go:generate go run gen.go
|
|
|
|
// puffs-gen-c transpiles a Puffs program to a C program.
|
|
//
|
|
// The command line arguments list the source Puffs files. If no arguments are
|
|
// given, it reads from stdin.
|
|
//
|
|
// The generated program is written to stdout.
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"os"
|
|
"os/exec"
|
|
|
|
"github.com/google/puffs/lang/generate"
|
|
)
|
|
|
|
func main() {
|
|
if err := generate.Main(gen{}); err != nil {
|
|
os.Stderr.WriteString(err.Error() + "\n")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
type gen struct{}
|
|
|
|
func (gen) WritePreamble(w *bytes.Buffer) error {
|
|
w.WriteString("// Code generated by puffs-gen-c. DO NOT EDIT.\n\n")
|
|
w.WriteString(preamble)
|
|
w.WriteString("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n")
|
|
return nil
|
|
}
|
|
|
|
func (gen) WritePostamble(w *bytes.Buffer) error {
|
|
w.WriteString("\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n")
|
|
return nil
|
|
}
|
|
|
|
func (gen) Format(in []byte) ([]byte, error) {
|
|
cmd := exec.Command("clang-format", "-style=Chromium")
|
|
cmd.Stdin = bytes.NewReader(in)
|
|
out, err := cmd.CombinedOutput()
|
|
if _, ok := err.(*exec.ExitError); ok && len(out) > 0 {
|
|
// Go error messages usually don't end in "\n". The caller, who sees
|
|
// the error we return here, usually adds the "\n" themselves.
|
|
if out[len(out)-1] == '\n' {
|
|
out = out[:len(out)-1]
|
|
}
|
|
// The exec.ExitError's Error message doesn't include stderr, so we
|
|
// return that explicitly.
|
|
return nil, errors.New(string(out))
|
|
}
|
|
return out, err
|
|
}
|