miqt/cmd/genbindings/main.go

291 lines
6.3 KiB
Go
Raw Normal View History

2024-08-06 01:03:23 +00:00
package main
import (
"context"
"encoding/json"
2024-08-06 01:03:23 +00:00
"flag"
2024-08-06 02:29:12 +00:00
"io/ioutil"
2024-08-06 01:03:23 +00:00
"log"
"os"
2024-08-06 02:29:12 +00:00
"path/filepath"
"runtime"
2024-08-06 01:03:23 +00:00
"strings"
"sync"
)
const (
ClangSubprocessCount = 3
2024-08-06 01:03:23 +00:00
)
2024-08-26 10:45:11 +00:00
func cacheFilePath(inputHeader string) string {
return filepath.Join("cachedir", strings.Replace(inputHeader, `/`, `__`, -1)+".json")
}
func findHeadersInDir(srcDir string) []string {
content, err := os.ReadDir(srcDir)
if err != nil {
panic(err)
}
var ret []string
for _, includeFile := range content {
if includeFile.IsDir() {
continue
}
if !strings.HasSuffix(includeFile.Name(), `.h`) {
continue
}
fullPath := filepath.Join(srcDir, includeFile.Name())
if !AllowHeader(fullPath) {
continue
}
ret = append(ret, fullPath)
}
return ret
}
func cleanGeneratedFilesInDir(dirpath string) {
log.Printf("Cleaning up output directory %q...", dirpath)
existing, err := os.ReadDir(dirpath)
if err != nil {
panic(err)
}
cleaned := 0
for _, e := range existing {
if e.IsDir() {
continue
}
if !strings.HasPrefix(e.Name(), `gen_`) {
continue
}
// One of ours, clean up
err := os.Remove(filepath.Join(dirpath, e.Name()))
if err != nil {
log.Printf("WARNING: Failed to remove existing file %q", e.Name())
continue
}
cleaned++
}
log.Printf("Removed %d file(s).", cleaned)
}
2024-08-06 01:03:23 +00:00
func main() {
ctx := context.Background()
clang := flag.String("clang", "clang", "Custom path to clang")
cflags := flag.String("cflags", `-DQT_WIDGETS_LIB -I/usr/include/x86_64-linux-gnu/qt5/QtWidgets -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtCore -DQT_GUI_LIB -I/usr/include/x86_64-linux-gnu/qt5/QtGui -DQT_CORE_LIB`, "Cflags to pass to clang (e.g. `pkg-config --cflags Qt5Widgets`)")
outDir := flag.String("outdir", "../../qt", "Output directory for generated gen_** files")
2024-08-06 01:03:23 +00:00
flag.Parse()
var includeFiles []string
for _, srcDir := range []string{
"/usr/include/x86_64-linux-gnu/qt5/QtCore",
"/usr/include/x86_64-linux-gnu/qt5/QtGui",
"/usr/include/x86_64-linux-gnu/qt5/QtWidgets",
} {
includeFiles = append(includeFiles, findHeadersInDir(srcDir)...)
}
log.Printf("Found %d header files to process.", len(includeFiles))
cleanGeneratedFilesInDir(*outDir)
2024-08-06 01:03:23 +00:00
2024-08-26 10:45:11 +00:00
var processHeaders []*CppParsedHeader
atr := astTransformRedundant{
preserve: make(map[string]*CppEnum),
}
2024-08-26 10:45:11 +00:00
InsertTypedefs()
//
// PASS 0 (Fill clang cache)
//
var clangChan = make(chan string, 0)
var clangWg sync.WaitGroup
for i := 0; i < ClangSubprocessCount; i++ {
clangWg.Add(1)
go func() {
defer clangWg.Done()
log.Printf("Clang worker: starting")
for {
inputHeader, ok := <-clangChan
if !ok {
return // Done
}
log.Printf("Clang worker got message for file %q", inputHeader)
// Parse the file
// This seems to intermittently fail, so allow retrying
astInner := mustClangExec(ctx, *clang, inputHeader, strings.Fields(*cflags))
// Write to cache
jb, err := json.MarshalIndent(astInner, "", "\t")
if err != nil {
panic(err)
}
err = ioutil.WriteFile(cacheFilePath(inputHeader), jb, 0644)
if err != nil {
panic(err)
}
astInner = nil
jb = nil
runtime.GC()
}
log.Printf("Clang worker: exiting")
}()
}
for _, inputHeader := range includeFiles {
// Check if there is a matching cache hit
2024-08-26 10:45:11 +00:00
cacheFile := cacheFilePath(inputHeader)
if _, err := os.Stat(cacheFile); err != nil && os.IsNotExist(err) {
// Nonexistent cache file, regenerate from clang
log.Printf("No AST cache for file %q, running clang...", filepath.Base(inputHeader))
clangChan <- inputHeader
}
}
// Done with all clang workers
close(clangChan)
clangWg.Wait()
// The cache should now be fully populated.
//
// PASS 1 (clang2il)
//
for _, inputHeader := range includeFiles {
cacheFile := cacheFilePath(inputHeader)
astJson, err := ioutil.ReadFile(cacheFile)
if err != nil {
panic("Expected cache to be created for " + inputHeader + ", but got error " + err.Error())
}
// Json decode
var astInner []interface{} = nil
err = json.Unmarshal(astJson, &astInner)
if err != nil {
panic(err)
}
// Convert it to our intermediate format
2024-08-27 07:12:08 +00:00
parsed, err := parseHeader(astInner, "")
if err != nil {
panic(err)
}
2024-08-26 10:45:11 +00:00
parsed.Filename = inputHeader // Stash
// AST transforms on our IL
astTransformChildClasses(parsed) // must be first
astTransformOptional(parsed)
astTransformOverloads(parsed)
atr.Process(parsed)
// Update global state tracker (AFTER astTransformChildClasses)
// Currently, this is only used for inner classes
for _, c := range parsed.Classes {
KnownClassnames[c.ClassName] = struct{}{}
}
for _, td := range parsed.Typedefs {
KnownTypedefs[td.Alias] = td // copy
}
2024-09-04 06:54:10 +00:00
for _, en := range parsed.Enums {
KnownEnums[en.EnumName] = en // copy
}
2024-08-26 10:45:11 +00:00
processHeaders = append(processHeaders, parsed)
}
//
// PASS 2
//
for _, parsed := range processHeaders {
log.Printf("Processing %q...", parsed.Filename)
// More AST transforms on our IL
astTransformTypedefs(parsed)
astTransformBlocklist(parsed) // Must happen after typedef transformation
{
// Save the IL file for debug inspection
jb, err := json.MarshalIndent(parsed, "", "\t")
if err != nil {
panic(err)
}
2024-08-26 10:45:11 +00:00
err = ioutil.WriteFile(cacheFilePath(parsed.Filename)+".ours.json", jb, 0644)
if err != nil {
panic(err)
}
}
// Breakout if there is nothing bindable
if parsed.Empty() {
log.Printf("Nothing in this header was bindable.")
continue
}
// Emit 3 code files from the intermediate format
2024-08-26 10:45:11 +00:00
outputName := filepath.Join(*outDir, "gen_"+strings.TrimSuffix(filepath.Base(parsed.Filename), `.h`))
2024-08-26 10:45:11 +00:00
goSrc, err := emitGo(parsed, filepath.Base(parsed.Filename))
if err != nil {
panic(err)
}
err = ioutil.WriteFile(outputName+".go", []byte(goSrc), 0644)
if err != nil {
panic(err)
}
2024-08-26 10:45:11 +00:00
bindingCppSrc, err := emitBindingCpp(parsed, filepath.Base(parsed.Filename))
if err != nil {
panic(err)
}
2024-08-06 02:29:12 +00:00
err = ioutil.WriteFile(outputName+".cpp", []byte(bindingCppSrc), 0644)
if err != nil {
panic(err)
}
2024-08-06 01:03:23 +00:00
2024-08-26 10:45:11 +00:00
bindingHSrc, err := emitBindingHeader(parsed, filepath.Base(parsed.Filename))
if err != nil {
panic(err)
}
2024-08-06 02:29:12 +00:00
err = ioutil.WriteFile(outputName+".h", []byte(bindingHSrc), 0644)
if err != nil {
panic(err)
}
2024-08-06 02:29:12 +00:00
// Done
2024-08-06 02:29:12 +00:00
}
log.Printf("Processing %d file(s) completed", len(includeFiles))
2024-08-06 01:03:23 +00:00
}