// Command uigen generates the checked public UI facade from the private // renderer API. Run it from the repository root with go generate ./ui. package main import ( "bytes" "fmt" "go/ast" "go/format" "go/parser" "go/token" "os" "path/filepath" "sort" "strings" ) var parts = map[string]string{ "TabsParts": "tabsParts", "SelectParts": "selectParts", "ComboboxParts": "comboboxParts", "CollapsibleParts": "collapsibleParts", "SegmentedParts": "segmentedParts", "ToastParts": "toastParts", "AccordionParts": "accordionParts", "MenuParts": "menuParts", "TreeParts": "treeParts", "TreeItemParts": "treeItemParts", "SplitButtonParts": "splitButtonParts", } func main() { if cwd, err := os.Getwd(); err == nil && filepath.Base(cwd) == "ui" { check(os.Chdir("..")) } fs := token.NewFileSet() paths, err := filepath.Glob("ui/*.go") check(err) files := map[string]*ast.File{} for _, path := range paths { if strings.HasSuffix(path, "_gen.go") || filepath.Base(path) == "frame.go" || filepath.Base(path) == "declarations.go" { continue } f, err := parser.ParseFile(fs, path, nil, parser.ParseComments) check(err) if f.Name.Name == "ui" { files[path] = f } } var funcs []*ast.FuncDecl var nodeType *ast.StructType var structs = map[string]*ast.TypeSpec{} imports := map[string]string{} for path, f := range files { if strings.HasSuffix(path, "_test.go") { continue } for _, im := range f.Imports { p := strings.Trim(im.Path.Value, "\"") name := filepath.Base(p) if im.Name != nil { name = im.Name.Name } imports[name] = p } for _, d := range f.Decls { if fn, ok := d.(*ast.FuncDecl); ok { r := "" if fn.Recv != nil { r = baseName(fn.Recv.List[0].Type) } if strings.HasPrefix(fn.Name.Name, "core") || (ast.IsExported(fn.Name.Name) && (r == "node" || r == "context" || publicPart(r) != "")) { funcs = append(funcs, fn) } } if gd, ok := d.(*ast.GenDecl); ok { for _, spec := range gd.Specs { if ts, ok := spec.(*ast.TypeSpec); ok && ts.Name.Name == "node" { nodeType = ts.Type.(*ast.StructType) } if ts, ok := spec.(*ast.TypeSpec); ok && publicPart(ts.Name.Name) != "" { structs[ts.Name.Name] = ts } } } } } if nodeType == nil { check(fmt.Errorf("uigen: run from the MyGo root or ui directory")) } sort.Slice(funcs, func(i, j int) bool { return receiver(funcs[i])+funcs[i].Name.Name < receiver(funcs[j])+funcs[j].Name.Name }) var out bytes.Buffer out.WriteString("// Code generated by go generate ./ui; DO NOT EDIT.\n\npackage ui\n\n") // Generate first, then keep only imports actually used by the facade. var body bytes.Buffer for _, fn := range funcs { generate(&body, fs, fn) } keys := make([]string, 0, len(structs)) for name := range structs { keys = append(keys, name) } sort.Strings(keys) for _, name := range keys { generatePart(&body, fs, structs[name]) } used := map[string]bool{} f, err := parser.ParseFile(token.NewFileSet(), "generated.go", "package ui\n"+body.String(), 0) if err != nil { os.WriteFile("/private/tmp/mygo-ui-invalid.go", body.Bytes(), 0644) check(err) } ast.Inspect(f, func(n ast.Node) bool { if s, ok := n.(*ast.SelectorExpr); ok { if id, ok := s.X.(*ast.Ident); ok { used[id.Name] = true } } return true }) out.WriteString("import (\n") keys = keys[:0] for name := range imports { if used[name] { keys = append(keys, name) } } sort.Strings(keys) for _, name := range keys { fmt.Fprintf(&out, "%s %q\n", name, imports[name]) } out.WriteString(")\n\n") out.Write(body.Bytes()) formatted, err := format.Source(out.Bytes()) check(err) check(os.WriteFile("ui/api_gen.go", formatted, 0644)) } func mentions(n ast.Node, names ...string) bool { found := false ast.Inspect(n, func(n ast.Node) bool { if id, ok := n.(*ast.Ident); ok { for _, name := range names { if id.Name == name { found = true } } } return true }) return found } func baseName(e ast.Expr) string { switch e := e.(type) { case *ast.Ident: return e.Name case *ast.StarExpr: return baseName(e.X) case *ast.IndexExpr: return baseName(e.X) case *ast.IndexListExpr: return baseName(e.X) } return "" } func receiver(fn *ast.FuncDecl) string { if fn.Recv == nil { return "" } return baseName(fn.Recv.List[0].Type) } func publicPart(name string) string { for pub, priv := range parts { if priv == name { return pub } } return "" } func source(fs *token.FileSet, n ast.Node) string { var b bytes.Buffer check(format.Node(&b, fs, n)) return b.String() } func genericArgs(fs *token.FileSet, fields *ast.FieldList) string { if fields == nil { return "" } var names []string for _, f := range fields.List { for _, name := range f.Names { names = append(names, name.Name) } } return "[" + strings.Join(names, ",") + "]" } func publicType(fs *token.FileSet, e ast.Expr, callbacks bool) string { switch e := e.(type) { case *ast.StarExpr: switch baseName(e.X) { case "context": return "*Context" case "node": return "Element" } if p := publicPart(baseName(e.X)); p != "" { return publicType(fs, e.X, false) } return "*" + publicType(fs, e.X, false) case *ast.Ident: if p := publicPart(e.Name); p != "" { return p } return e.Name case *ast.IndexExpr: return publicType(fs, e.X, false) + "[" + publicType(fs, e.Index, false) + "]" case *ast.IndexListExpr: var ix []string for _, i := range e.Indices { ix = append(ix, publicType(fs, i, false)) } return publicType(fs, e.X, false) + "[" + strings.Join(ix, ",") + "]" case *ast.FuncType: p := params(fs, e.Params, true, false) return "func(" + p + ")" + results(fs, e.Results, true) case *ast.Ellipsis: return "..." + publicType(fs, e.Elt, false) default: return source(fs, e) } } func builderCallback(t *ast.FuncType) bool { if t.Results != nil && len(t.Results.List) > 0 { return false } return !mentions(t, "Menu", "Painter", "InputEvent", "error") } func params(fs *token.FileSet, fields *ast.FieldList, pub, callbacks bool) string { if fields == nil { return "" } var p []string for i, f := range fields.List { t := source(fs, f.Type) if pub { t = publicType(fs, f.Type, callbacks && (len(f.Names) == 0 || (f.Names[0].Name != "action" && f.Names[0].Name != "done"))) } names := f.Names if len(names) == 0 { names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("arg%d", i))} } for _, n := range names { p = append(p, n.Name+" "+t) } } return strings.Join(p, ",") } func results(fs *token.FileSet, fields *ast.FieldList, pub bool) string { if fields == nil || len(fields.List) == 0 { return "" } var r []string for _, f := range fields.List { t := source(fs, f.Type) if pub { t = publicType(fs, f.Type, false) } count := max(len(f.Names), 1) for range count { r = append(r, t) } } if len(r) == 1 { return " " + r[0] } return " (" + strings.Join(r, ",") + ")" } func fieldsCount(fields *ast.FieldList) int { n := 0 if fields != nil { for _, f := range fields.List { n += max(len(f.Names), 1) } } return n } func zero(fs *token.FileSet, e ast.Expr) string { t := publicType(fs, e, false) if t == "Element" || publicPart(baseName(e)) != "" { return t + "{}" } switch t { case "bool": return "false" case "string": return "\"\"" case "int", "uint64", "uint32", "float32", "float64", "Modifiers", "time.Duration": return "0" } if strings.HasPrefix(t, "*") || strings.HasPrefix(t, "[]") || strings.HasPrefix(t, "func(") { return "nil" } return "*new(" + t + ")" } func zeroReturn(fs *token.FileSet, r *ast.FieldList) string { if r == nil || len(r.List) == 0 { return "return" } var vals []string for _, f := range r.List { for range max(len(f.Names), 1) { vals = append(vals, zero(fs, f.Type)) } } return "return " + strings.Join(vals, ",") } func convertArg(fs *token.FileSet, t ast.Expr, name, c string) string { if st, ok := t.(*ast.StarExpr); ok { switch baseName(st.X) { case "context": return c case "node": return name + ".nodeFor(" + c + ".rt)" } } if ft, ok := t.(*ast.FuncType); ok { var rawNames, args []string converts := false if ft.Params != nil { for i, p := range ft.Params.List { names := p.Names if len(names) == 0 { names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("a%d", i))} } for _, n := range names { rawNames = append(rawNames, n.Name+" "+source(fs, p.Type)) v := n.Name if mentions(p.Type, "context") { v = "makeContext(" + v + ")" converts = true } else if st, ok := p.Type.(*ast.StarExpr); ok && baseName(st.X) == "node" { v = "wrapElement(" + v + ")" converts = true } args = append(args, v) } } } if !converts { // The callback types match: preserve nil and avoid a wrapper closure. return name } ret := "" if ft.Results != nil && len(ft.Results.List) > 0 { ret = "return " } return "func(" + strings.Join(rawNames, ",") + ")" + sourceResults(fs, ft.Results) + " {" + ret + name + "(" + strings.Join(args, ",") + ")}" } if _, ok := t.(*ast.Ellipsis); ok { return name + "..." } return name } func sourceResults(fs *token.FileSet, r *ast.FieldList) string { if r == nil { return "" } var v []string for _, f := range r.List { for range max(len(f.Names), 1) { v = append(v, source(fs, f.Type)) } } if len(v) == 1 { return " " + v[0] } return " (" + strings.Join(v, ",") + ")" } var special = map[string]bool{"Element.Children": true, "Element.Key": true, "Element.Material": true, "Context.Invalidate": true, "List": true} // Public action queries must see bound edits on controls already built. // Keep this at the facade: private widget queries can run in constructors, // before callers finish configuring the widget's input options. var inputQueries = map[string]bool{ "Element.Clicked": true, "Element.Clicks": true, "Element.DoubleClicked": true, "Element.RightClicked": true, "Element.WindowDoubleClicked": true, "Element.Shortcut": true, "Element.OverlayShortcut": true, "Context.Shortcut": true, "ListState.Shortcut": true, } func generate(out *bytes.Buffer, fs *token.FileSet, fn *ast.FuncDecl) { r := receiver(fn) pubR := r switch r { case "node": pubR = "Element" case "context": pubR = "Context" default: if p := publicPart(r); p != "" { pubR = p } } name := strings.TrimPrefix(fn.Name.Name, "core") if pubR == "Element" && name == "Rows" { name = "GridRows" } if special[pubR+"."+name] || (r == "" && special[name]) { return } if fn.Doc != nil { for _, comment := range fn.Doc.List { v := comment.Text v = strings.ReplaceAll(v, "*Element", "Element") for pub, priv := range parts { v = strings.ReplaceAll(v, priv, pub) } fmt.Fprintln(out, v) } } recv := "" rawRecv := "" if fn.Recv != nil { rt := pubR if ix, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok { if r == "context" { rt = "*Context" } else if r != "node" && publicPart(r) == "" { rt = "*" + publicType(fs, ix.X, false) } else if publicPart(r) != "" { rt = publicType(fs, ix.X, false) } } else { rt = publicType(fs, fn.Recv.List[0].Type, false) if r == "node" { rt = "Element" } if r == "context" { rt = "*Context" } } recv = "(_handle " + rt + ") " rawRecv = "_handle." } tp := "" if fn.Type.TypeParams != nil { tp = "[" + params(fs, fn.Type.TypeParams, false, false) + "]" } fmt.Fprintf(out, "func %s%s%s(%s)%s {\n", recv, name, tp, params(fs, fn.Type.Params, true, true), results(fs, fn.Type.Results, true)) c := "_ctx" if r == "node" { fmt.Fprintln(out, "_node := _handle.node(); if _node == nil {", zeroReturn(fs, fn.Type.Results), "}; _ctx := _node.c; _ = _ctx") rawRecv = "_node." } if r == "context" { fmt.Fprintln(out, "_ctx := _handle.build(); if _ctx == nil {", zeroReturn(fs, fn.Type.Results), "}") rawRecv = "_ctx." } if publicPart(r) != "" { fmt.Fprintln(out, "_parts := _handle.resolve(); if _parts == nil {", zeroReturn(fs, fn.Type.Results), "}; _ctx := _parts.c; _ = _ctx") rawRecv = "_parts." } // A constructor, which builds controls in the frame of its context: // their input applies as it returns (see ui/value_input.go). constructor := false if r == "" || r == "Router" || r == "Route" || r == "ListState" { frameParam := "" if fn.Type.Params != nil { for _, p := range fn.Type.Params.List { if st, ok := p.Type.(*ast.StarExpr); ok && baseName(st.X) == "context" { frameParam = p.Names[0].Name break } } } if frameParam != "" { constructor = true fmt.Fprintf(out, "_ctx := %s.build(); if _ctx == nil { %s };\n", frameParam, zeroReturn(fs, fn.Type.Results)) } else if mentions(fn.Type, "node") { if name == "Local" || name == "Drop" || name == "DragOver" || name == "DropData" || name == "DataDragOver" { fmt.Fprintln(out, "_node := e.node(); if _node == nil {", zeroReturn(fs, fn.Type.Results), "}; _ctx := _node.c; _ = _ctx") } else if r == "Route" && name == "Page" { fmt.Fprintln(out, "_ctx := _handle.router.rtContext(); if _ctx == nil { return Element{} }") } } } if inputQueries[pubR+"."+name] { fmt.Fprintln(out, "_ctx.rt.applyInputs()") } var args []string if fn.Type.Params != nil { for _, p := range fn.Type.Params.List { for _, n := range p.Names { args = append(args, convertArg(fs, p.Type, n.Name, c)) } } } call := rawRecv + fn.Name.Name + genericArgs(fs, fn.Type.TypeParams) + "(" + strings.Join(args, ",") + ")" count := fieldsCount(fn.Type.Results) // A part's method that builds an element, as a select's Item or a // tab list's Tab, or parts, as an accordion's Item, is a constructor // too. if publicPart(r) != "" && count == 1 && (mentions(fn.Type.Results, "node") || publicPart(baseName(fn.Type.Results.List[0].Type)) != "") { constructor = true } if count == 1 && mentions(fn.Type.Results, "node") { if constructor { fmt.Fprintf(out, "_ctx.rt.beginBuild(); _e := %s; _ctx.rt.endBuild()\nreturn wrapElement(_e)\n", call) } else { fmt.Fprintf(out, "return wrapElement(%s)\n", call) } } else if count == 1 && publicPart(baseName(fn.Type.Results.List[0].Type)) != "" { part := publicPart(baseName(fn.Type.Results.List[0].Type)) arg := genericTypeArguments(fs, fn.Type.Results.List[0].Type) if constructor { fmt.Fprintf(out, "_ctx.rt.beginBuild(); _p := %s; _ctx.rt.endBuild()\nreturn wrap%s%s(_p)\n", call, part, arg) } else { fmt.Fprintf(out, "return wrap%s%s(%s)\n", part, arg, call) } } else if count > 0 { fmt.Fprintf(out, "return %s\n", call) } else { fmt.Fprintf(out, "%s\n", call) } fmt.Fprintln(out, "}") fmt.Fprintln(out) } func genericTypeArguments(fs *token.FileSet, e ast.Expr) string { if s, ok := e.(*ast.StarExpr); ok { e = s.X } switch e := e.(type) { case *ast.IndexExpr: return "[" + source(fs, e.Index) + "]" case *ast.IndexListExpr: var a []string for _, x := range e.Indices { a = append(a, source(fs, x)) } return "[" + strings.Join(a, ",") + "]" } return "" } func generatePart(out *bytes.Buffer, fs *token.FileSet, t *ast.TypeSpec) { pub := publicPart(t.Name.Name) tp := "" args := genericArgs(fs, t.TypeParams) if t.TypeParams != nil { tp = "[" + params(fs, t.TypeParams, false, false) + "]" } fmt.Fprintf(out, "// %s contains checked handles for the parts of a custom widget.\ntype %s%s struct {\n", pub, pub, tp) st := t.Type.(*ast.StructType) root := "" for _, f := range st.Fields.List { for _, n := range f.Names { if ast.IsExported(n.Name) { fmt.Fprintf(out, "%s %s\n", n.Name, publicType(fs, f.Type, false)) if root == "" { root = n.Name } } } } fmt.Fprintln(out, "part uint32\n}") ptr := "" if pub == "SelectParts" || pub == "ComboboxParts" || pub == "MenuParts" { ptr = "*" } fmt.Fprintf(out, "func wrap%s%s(p %s%s%s) %s%s {\n", pub, tp, ptr, t.Name.Name, args, pub, args) // Value-returning parts are kept until the next build, like pointer parts. take := "&p" if ptr != "" { take = "p" fmt.Fprintf(out, "if p == nil { return %s%s{} };\n", pub, args) } fmt.Fprintf(out, "c := p.c; if c == nil { return %s%s{} }; _slot := c.rt.keepPart(%s);\n", pub, args, take) fmt.Fprintf(out, "return %s%s{part: _slot", pub, args) for _, f := range st.Fields.List { for _, n := range f.Names { if ast.IsExported(n.Name) { fmt.Fprintf(out, ",%s:wrapElement(p.%s)", n.Name, n.Name) } } } fmt.Fprintln(out, "}\n}") fmt.Fprintf(out, "func (p %s%s) resolve() *%s%s { n := p.%s.node(); if n == nil { return nil }; if int(p.part) >= len(n.c.rt.parts) { return nil }; return n.c.rt.parts[p.part].(*%s%s) }\n", pub, args, t.Name.Name, args, root, t.Name.Name, args) } func check(err error) { if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }