### Run unify-detect Example Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Command to execute the AST diff engine script. ```bash wile-goast --run unify-detect ``` -------------------------------- ### Transformation Phase Examples Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Illustrative examples of how different control flow patterns are transformed during the four phases. ```scheme ;; Phase 0b: forward goto → if !cond wrapping ;; if x > 0 { goto end }; println(x); end: println(0) ;; → if !(x > 0) { println(x) }; println(0) ;; Phase 1: loop returns → _ctl + break + guard ;; for _, v := range items { if v < 0 { return v } }; return 0 ;; → var _ctl0 int; for ... { _ctl0 = 1; break }; if _ctl0 == 1 { return v } else { return 0 } ;; Phase 1 with func-type: result variable synthesis ;; (go-cfg-to-structured body ftype) ;; → var _ctl0 int; var _r0 int; for ... { _r0 = v; _ctl0 = 1; break } ;; if _ctl0 == 1 { return _r0 } else { return 0 } ;; Phase 2: linear guards → if/else ;; if x < lo { return lo }; if x > hi { return hi }; return x ;; → if x < lo { return lo } else if x > hi { return hi } else { return x } ``` -------------------------------- ### Run goast-query Example Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Command to execute the basic AST query script. ```bash wile-goast --run goast-query ``` -------------------------------- ### Callgraph Generation Example Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/reference/cheatsheet.md Example of generating a static callgraph for the current directory. ```scheme (go-callgraph "." 'static) ``` -------------------------------- ### Normalized Site Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/normalize-divergent-sites.md The refactored version of readC, now using defer to match the dominant pattern and prevent resource leaks. ```go func readC(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return validate(f) } ``` -------------------------------- ### Install wile-goast binary Source: https://github.com/aalpar/wile-goast/blob/master/README.md Installs the latest version of the wile-goast command-line tool using the Go toolchain. ```bash go install github.com/aalpar/wile-goast/cmd/wile-goast@latest ``` -------------------------------- ### Supporting Declarations Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/tail-merging.md Common functions used in the tail merging examples. ```go func prepA() {} func prepB() {} func commit() {} func notify() {} ``` -------------------------------- ### Divergent Site Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/normalize-divergent-sites.md Demonstrates a pattern where readA and readB use defer for resource cleanup, while readC manually closes the file, leading to a potential leak. ```go import "os" func readA(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return validate(f) } func readB(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return validate(f) } // Deviant site: manual Close — leaks f on the validate-error path. func readC(path string) error { f, err := os.Open(path) if err != nil { return err } if err := validate(f); err != nil { return err // f is never closed here } f.Close() return nil } ``` -------------------------------- ### Branch Fusion Refactoring Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/branch-fusion.md Demonstrates the transformation from two separate guards testing the same predicate to a single fused guard. ```go func apply(x bool, n int) int { if x { n += 10 } if x { n -= 3 } return n } ``` ```go func apply(x bool, n int) int { if x { n += 10 n -= 3 } return n } ``` -------------------------------- ### Boolean Simplification Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/boolean-simplification.md Demonstrates the reduction of a complex boolean expression into a simpler equivalent form. ```go func keep(a, b bool) bool { return (a && b) || (a && !b) } ``` ```go func keep(a, b bool) bool { return a } ``` -------------------------------- ### Define shared declarations for Go refactoring examples Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/guard-clause-flattening.md Common types and variables used in the process function examples. ```go import "errors" type T struct{ ok bool } var errNil = errors.New("nil") var errNotOK = errors.New("not ok") func doWork(v *T) {} ``` -------------------------------- ### Dead-store elimination example in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/dead-store-elimination.md Demonstrates the removal of an assignment that is overwritten before being read. ```go func compute(x int) int { y := 0 y = x + 1 return y } ``` ```go func compute(x int) int { return x + 1 } ``` -------------------------------- ### Extract Class Refactoring Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/extract-class.md Demonstrates splitting a monolithic widget struct into separate rect and color types. ```go type widget struct { x, y, w, h int r, g, b uint8 } func (wd *widget) area() int { return wd.w * wd.h } func (wd *widget) gray() uint8 { return (wd.r + wd.g + wd.b) / 3 } ``` ```go type rect struct{ x, y, w, h int } type color struct{ r, g, b uint8 } type widget struct { bounds rect fill color } func (r rect) area() int { return r.w * r.h } func (c color) gray() uint8 { return (c.r + c.g + c.b) / 3 } ``` -------------------------------- ### Supporting Declarations Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/convert-method-to-function.md Common types and helper functions used in the refactoring examples. ```go type Token int func newErr(tok Token, base error, form string) error { return fmt.Errorf("%w: unterminated %s at token %d", base, form, tok) } type Parser struct { cur Token err error } ``` -------------------------------- ### Define shared struct for conditional examples Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/consolidate-conditional.md Shared data structure used in the conditional logic examples. ```go type T struct { banned bool expired bool active bool } ``` -------------------------------- ### Supporting declarations for loop unswitching Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/loop-unswitching.md Shared function declarations used in the loop unswitching examples. ```go func fast(i int) {} func slow(i int) {} ``` -------------------------------- ### Move Field Refactoring Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/move-field.md Demonstrates the transition of a field from one struct to another to improve data locality and simplify function signatures. ```go type Account struct { ID int Currency string } type Money struct { Amount int } func render(a Account, m Money) string { return format(m.Amount, a.Currency) } func format(amount int, currency string) string { return currency } ``` ```go type Account struct { ID int } type Money struct { Amount int Currency string } func render(m Money) string { return format(m.Amount, m.Currency) } ``` -------------------------------- ### Interface implementor information structure Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Example of the tagged alist structure returned by the go-interface-implementors primitive. ```scheme (interface-info (name . "Store") (pkg . "github.com/example/pkg") (methods . ("Get" "Set" "Delete")) (implementors . (((type . "MemoryStore") (pkg . "github.com/example/pkg")) ((type . "SimpleStore") (pkg . "github.com/example/pkg"))))) ``` -------------------------------- ### Merge Struct Refactoring Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/merge-struct.md Demonstrates the transformation from a nested struct structure to a flattened structure. ```go type Address struct { Street string City string } type Customer struct { Name string Addr Address } func label(c Customer) string { return c.Name + " " + c.Addr.Street + " " + c.Addr.City } ``` ```go type Customer struct { Name string Street string City string } func label(c Customer) string { return c.Name + " " + c.Street + " " + c.City } ``` -------------------------------- ### Common Subexpression Elimination Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/common-subexpression-elimination.md Demonstrates the transformation of redundant multiplication operations into a single computed variable. ```go func area(w, h int) int { return w*h + w*h/2 } ``` ```go func area(w, h int) int { wh := w * h return wh + wh/2 } ``` -------------------------------- ### Extract function reference profiles Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Example output structure for a function reference profile, showing the function name, package, and external object references. ```scheme ((func-ref (name . "MyFunc") (pkg . "my/pkg") (refs . ((ref (pkg . "io") (objects . ("Reader" "Writer"))) (ref (pkg . "fmt") (objects . ("Println"))))))) ``` -------------------------------- ### Callgraph Query Algorithm Selection Source: https://github.com/aalpar/wile-goast/blob/master/TODO.md Examples of the legacy symbol-based algorithm selection and the new canonical string-based approach for the go-callgraph query. ```scheme (go-callgraph prog 'cha) ``` ```scheme (go-callgraph prog "cha") ``` -------------------------------- ### Inline Function Refactoring Example Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/inline-function.md Demonstrates the transformation of a function call into its body to remove unnecessary indirection. ```go func handle(n int) int { return double(n) + 1 } func double(n int) int { return n * 2 } ``` ```go func handle(n int) int { return n*2 + 1 } ``` -------------------------------- ### Run Go analysis and process diagnostics Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates listing available analyzers, executing specific analyzers on a package, and iterating over the resulting diagnostic list. ```scheme (import (wile goast lint)) ;; List available analyzers (go-analyze-list) ;; Run nilness and shadow on the current package (define diags (go-analyze "." "nilness" "shadow")) ;; Print diagnostics (for-each (lambda (d) (display (cdr (assoc 'pos (cdr d)))) (display ": ") (display (cdr (assoc 'message (cdr d)))) (newline)) diags) ``` -------------------------------- ### Manage Go sessions and queries Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates loading packages into a reusable session for multiple queries versus loading fresh packages for individual operations. ```scheme ;; Load once, query many — all layers see the same source snapshot (define s (go-load "my/pkg/a" "my/pkg/b")) (define pkgs (go-typecheck-package s)) (define ssa (go-ssa-build s)) (define cfg (go-cfg s "MyFunc")) (define cg (go-callgraph s 'cha)) ;; Old style still works — loads fresh each time (go-ssa-build "my/pkg/a") ``` -------------------------------- ### Run the initial package analysis Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/prompts/goast-split.md Execute the basic dependency analysis on a target package to generate a split recommendation. ```scheme (import (wile goast split)) (import (wile goast utils)) (define refs (go-func-refs "{{package}}")) (define report (recommend-split refs)) report ``` -------------------------------- ### Analyze Go function control flow Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates building a CFG, generating a dominator tree, checking dominance, and enumerating paths between blocks. ```scheme (import (wile goast cfg)) ;; Build CFG for function Run (define cfg (go-cfg "." "Run")) ;; Build dominator tree (define dom (go-cfg-dominators cfg)) ;; Does block 1 dominate block 5? (go-cfg-dominates? dom 1 5) ; => #t or #f ;; Enumerate paths from entry (0) to exit block (define paths (go-cfg-paths cfg 0 3)) ``` -------------------------------- ### Build and Test Commands Source: https://github.com/aalpar/wile-goast/blob/master/README.md Use these Makefile targets to manage the build process, run tests, and perform linting. ```bash make build # Build to ./dist/{os}/{arch}/wile-goast make test # Run all tests make lint # Run golangci-lint make ci # Full CI: lint + build + test + covercheck + verify-mod ``` -------------------------------- ### Run the legibility probe Source: https://github.com/aalpar/wile-goast/blob/master/tools/legibility/README.md Execute the probe using specific fixtures and optional model overrides. ```bash go run tools/legibility/probe.go --fixture dupcluster go run tools/legibility/probe.go --fixture nodups --model claude-haiku-4-5-20251001 ``` -------------------------------- ### (go-ssa-build pattern . options) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Builds the SSA intermediate representation for a specified Go package. ```APIDOC ## (go-ssa-build pattern . options) ### Description Builds SSA (Static Single Assignment) intermediate representation for a Go package. Returns a list of `ssa-func` nodes. ### Parameters - **pattern** (string) - Required - A `go list`-compatible pattern. - **options** (symbol) - Optional - Use `'positions` to include source positions on instructions. ### Return Value - **ssa-func** (list) - A list of function nodes containing name, signature, params, free-vars, and blocks. ``` -------------------------------- ### Shared Validation Helper Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/normalize-divergent-sites.md A helper function used by the example code to simulate file validation. ```go func validate(f *os.File) error { return nil } ``` -------------------------------- ### Replace manual lazy initialization with sync.Once Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/replace-manual-init-with-sync-once.md The before state shows a non-thread-safe manual flag check, while the after state demonstrates the use of sync.Once to handle initialization safely. ```go type Config struct{ v int } var ( cfg *Config ready bool ) func Get() *Config { if !ready { cfg = &Config{v: 42} ready = true } return cfg } ``` ```go import "sync" var ( cfg *Config once sync.Once ) func Get() *Config { once.Do(func() { cfg = &Config{v: 42} }) return cfg } ``` -------------------------------- ### (go-cfg-dominators cfg) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Builds a dominator tree from a previously generated CFG. ```APIDOC ## (go-cfg-dominators cfg) ### Description Builds a dominator tree from the provided CFG. ### Parameters - **cfg** (list) - Required - The CFG block list returned by `go-cfg`. ### Returns - **list of dom-node** - A list of nodes containing block index, immediate dominator, and children. ``` -------------------------------- ### Manual resource release pattern Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/introduce-defer-for-cleanup.md Demonstrates the error-prone approach where manual release calls must be repeated on every return path. ```go import ( "errors" "sync" ) var mu sync.Mutex var errBad = errors.New("bad") func update(ok bool) error { mu.Lock() if !ok { mu.Unlock() return errBad } mu.Unlock() return nil } ``` -------------------------------- ### Compare SSA functions and determine unification Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates importing the unification module, calculating similarity between canonicalized SSA nodes, and performing a threshold-based unification check. ```scheme (import (wile goast unify)) ;; Compare two SSA functions after canonicalization (let* ((r (ssa-diff canon-a canon-b)) (sim (diff-result-similarity r))) (display sim)) ;; Full verdict (unifiable? (ssa-diff canon-a canon-b) 0.80) ``` -------------------------------- ### Common AST Query Patterns Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/reference/cheatsheet.md Basic patterns for inspecting Go packages and file structures using Scheme primitives. ```scheme (go-typecheck-package "./...") ; typed packages (big; summarize it) (length (go-typecheck-package "./...")) ; how many packages (map car (go-parse-file "main.go")) ; top-level structure tags only ``` -------------------------------- ### Execute belief-example Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Command to run the belief DSL smoke test. ```bash wile-goast --run belief-example ``` -------------------------------- ### Tail Merging Transformation Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/tail-merging.md Demonstration of the before and after states of the tail merging optimization. ```go func handle(x bool) { if x { prepA() commit() notify() } else { prepB() commit() notify() } } ``` ```go func handle(x bool) { if x { prepA() } else { prepB() } commit() notify() } ``` -------------------------------- ### Introduce Parameter Object in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/introduce-parameter-object.md Demonstrates replacing multiple positional parameters with structured types. ```go func drawLine(x1, y1, x2, y2 int, r, g, b uint8) {} ``` ```go type point struct{ x, y int } type rgb struct{ r, g, b uint8 } func drawLine(from, to point, color rgb) {} ``` -------------------------------- ### (go-cfg-paths cfg from to) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Enumerates simple paths between two blocks in the CFG. ```APIDOC ## (go-cfg-paths cfg from to) ### Description Enumerate simple paths between blocks. Capped at 1024 paths to bound cost. ### Parameters - **cfg** (list) - Required - The CFG block list returned by `go-cfg`. - **from** (integer) - Required - Starting block index. - **to** (integer) - Required - Ending block index. ### Returns - **list of lists of integers** - A list of paths, where each path is a list of block index integers. ``` -------------------------------- ### Initialize and evaluate with wile-goast engine Source: https://github.com/aalpar/wile-goast/blob/master/README.md Configures the engine with various analysis extensions and executes a Go expression evaluation. ```go engine, err := wile.NewEngine(ctx, wile.WithProfile(wile.KitchenSink), wile.WithExtension(goast.Extension), wile.WithExtension(goastssa.Extension), wile.WithExtension(goastcfg.Extension), wile.WithExtension(goastcg.Extension), wile.WithExtension(goastlint.Extension), ) defer engine.Close() val, err := engine.Eval(ctx, `(go-parse-expr "1 + 2")`) ``` -------------------------------- ### Utilize Wile Goast Utilities Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates field extraction and tree walking using the (wile goast utils) library. ```scheme (import (wile goast utils)) ;; Extract a field (nf some-node 'name) ; => "Add" or #f ;; Find all call-expr nodes in a function body (walk (nf func-decl 'body) (lambda (node) (and (tag? node 'call-expr) node))) ``` -------------------------------- ### Session Management Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Primitives for managing Go package loading sessions and dependency discovery. ```APIDOC ## (go-load pattern ... . options) ### Description Creates a GoSession that holds loaded packages and lazily builds SSA. ### Parameters - **pattern** (string) - Required - Package import path pattern - **options** (symbol) - Optional - 'lint ## (go-list-deps pattern ...) ### Description Performs transitive import path discovery for the given package patterns. ### Parameters - **pattern** (string) - Required - Package import path pattern ``` -------------------------------- ### Algebraic simplification in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/algebraic-simplification.md Demonstrates the transformation of an unoptimized expression into its simplified canonical form. ```go func reduce(x, y int) int { return x*1 + y*0 + (x & x) } ``` ```go func reduce(x, y int) int { return 2 * x } ``` -------------------------------- ### Build and query call graphs Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Shows how to generate a call graph using the VTA algorithm and query for callers and callees of specific functions. ```scheme (import (wile goast callgraph)) (define cg (go-callgraph "." 'vta)) ;; Who calls ProcessRequest? (define callers (go-callgraph-callers cg "(*Server).ProcessRequest")) ;; What does main call directly? (define callees (go-callgraph-callees cg "command-line-arguments.main")) ``` -------------------------------- ### Break import cycle in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/break-import-cycle.md Demonstrates the transition from a circular dependency between user and order packages to a unidirectional dependency using ID references. ```go // package user type User struct { History []order.Order // user → order } // package order type Order struct { Buyer *user.User // order → user ← cycle } ``` ```go // package user — imports nothing from order type User struct { OrderIDs []int } // package order — imports user only import "example/user" type Order struct { ID int Buyer *user.User } ``` -------------------------------- ### Constant folding and propagation in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/constant-folding.md Demonstrates the transformation of a function computing a product at run time into a function returning a pre-calculated constant. ```go func windowBytes() int { width := 1024 scale := 8 return width * scale } ``` ```go func windowBytes() int { return 8192 } ``` -------------------------------- ### Loop Fusion Transformation in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/loop-fusion.md Demonstrates the transformation of two sequential loops into a single fused loop to optimize performance. ```go func transform(xs []int) []int { out := make([]int, len(xs)) for i, x := range xs { out[i] = x * 2 } for i := range out { out[i]++ } return out } ``` ```go func transform(xs []int) []int { out := make([]int, len(xs)) for i, x := range xs { out[i] = x*2 + 1 } return out } ``` -------------------------------- ### Deferred resource release pattern Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/introduce-defer-for-cleanup.md Demonstrates the refactored approach using defer to guarantee resource release on all exit paths. ```go func update(ok bool) error { mu.Lock() defer mu.Unlock() if !ok { return errBad } return nil } ``` -------------------------------- ### Parse and manipulate Go AST Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates parsing a Go file, extracting function names from the AST, and formatting the AST back into source code. ```scheme (import (wile goast)) ;; Parse a file with positions and comments (define ast (go-parse-file "main.go" 'positions 'comments)) ;; Extract function names (define names (filter-map (lambda (decl) (and (eq? (car decl) 'func-decl) (cdr (assoc 'name (cdr decl))))) (cdr (assoc 'decls (cdr ast))))) ;; Round-trip: AST to source (define src (go-format ast)) ;; Type-check a package (define pkgs (go-typecheck-package "./..." 'positions)) ``` -------------------------------- ### Configure stdio MCP Server Source: https://github.com/aalpar/wile-goast/blob/master/docs/MCP.md Use this configuration in your MCP client settings to run wile-goast as a stdio-based server. ```json {"mcpServers": {"wile-goast": {"command": "wile-goast", "args": ["--mcp"]}}} ``` -------------------------------- ### Replace switch with dispatch table in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/replace-switch-with-dispatch-table.md Demonstrates the transformation from a switch-based command handler to a map-based dispatch table. ```go func dispatch(cmd string, n int) int { switch cmd { case "inc": return n + 1 case "dec": return n - 1 case "double": return n * 2 } return n } ``` ```go var ops = map[string]func(int) int{ "inc": func(n int) int { return n + 1 }, "dec": func(n int) int { return n - 1 }, "double": func(n int) int { return n * 2 }, } func dispatch(cmd string, n int) int { if op, ok := ops[cmd]; ok { return op(n) } return n } ``` -------------------------------- ### Run Unification Detection Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Execute the unification detection script on all packages within the current Go module. ```bash cd /path/to/go/module wile-goast --run unify-detect-pkg ``` -------------------------------- ### Collapse single-implementation interface in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/collapse-single-impl-interface.md Demonstrates the transformation from an interface-based design to direct usage of a concrete type. ```go type Store interface { Get(k string) string } type memStore struct { m map[string]string } func (s *memStore) Get(k string) string { return s.m[k] } func lookup(s Store, k string) string { return s.Get(k) } ``` ```go type memStore struct { m map[string]string } func (s *memStore) Get(k string) string { return s.m[k] } func lookup(s *memStore, k string) string { return s.Get(k) } ``` -------------------------------- ### Configure Streamable HTTP MCP Server Source: https://github.com/aalpar/wile-goast/blob/master/docs/MCP.md Use this configuration to connect to a wile-goast instance running as a streamable HTTP server. ```json {"mcpServers": {"wile-goast": {"type": "streamable-http", "url": "http://127.0.0.1:8080/mcp"}}} ``` -------------------------------- ### Detect Unification Candidates Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/prompts/goast-refactor.md Initializes the wile-goast environment for package-wide unification detection. ```scheme ;; For package-wide scan: (begin (import (wile goast) (wile goast utils)) ;; Load and run unify-detect-pkg logic ) ``` -------------------------------- ### Execute inline-expand transformation Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Command to run the AST transformation script. ```bash wile-goast -f examples/goast-query/inline-expand.scm ``` -------------------------------- ### (go-callgraph pattern algorithm) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Builds a whole-program call graph for the specified Go package pattern using the chosen analysis algorithm. ```APIDOC ## (go-callgraph pattern algorithm) ### Description Builds a whole-program call graph for the specified Go package pattern using the chosen analysis algorithm. ### Parameters - **pattern** (string) - Required - A go list-compatible pattern. - **algorithm** (symbol) - Required - One of 'static, 'cha, 'rta, 'vta. ### Returns - **list of cg-node** - A list of nodes representing the call graph. ``` -------------------------------- ### Replace loop with pipeline in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/replace-loop-with-pipeline.md Demonstrates the transformation from an imperative loop with append/continue logic to a functional pipeline using generic Filter and Map functions. ```go import "strings" func longNames(users []string) []string { var out []string for _, u := range users { if len(u) > 3 { out = append(out, strings.ToUpper(u)) } } return out } ``` ```go import "strings" func Filter[T any](xs []T, keep func(T) bool) []T { var out []T for _, x := range xs { if keep(x) { out = append(out, x) } } return out } func Map[T, U any](xs []T, f func(T) U) []U { out := make([]U, len(xs)) for i, x := range xs { out[i] = f(x) } return out } func longNames(users []string) []string { return Map(Filter(users, func(u string) bool { return len(u) > 3 }), strings.ToUpper) } ``` -------------------------------- ### Managing Shared Go Sessions Source: https://github.com/aalpar/wile-goast/blob/master/docs/GO-STATIC-ANALYSIS.md Use go-load to create a session that persists loaded package state across multiple analysis primitives, avoiding redundant loading. ```scheme (define s (go-load "my/pkg/a" "my/pkg/b")) (go-typecheck-package s) ;; reuses loaded state (go-ssa-build s) ;; same packages, no reload (go-cfg s "MyFunc") ;; same SSA program (go-callgraph s 'cha) ;; same snapshot ``` -------------------------------- ### Walk all nodes in a package Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/prompts/goast-analyze.md Traverse all files and nodes in a package to identify specific AST structures like composite literals. ```scheme (import (wile goast utils)) (let ((pkgs (go-typecheck-package "my/package"))) (for-each (lambda (pkg) (for-each (lambda (file) (walk file (lambda (node) (when (eq? (car node) 'composite-lit) (display (nf (nf node 'type) 'name)) (newline)) #f))) (cdr (assoc 'files (cdr pkg))))) pkgs)) ``` -------------------------------- ### Core Primitives Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/reference/cheatsheet.md A collection of Scheme functions for interacting with Go source code, ASTs, and static analysis data. ```APIDOC ## Scheme Primitives ### go-parse-file - **Signature**: `(go-parse-file . opts)` - **Description**: Parses a Go file into an alist representation. ### go-parse-string - **Signature**: `(go-parse-string . opts)` - **Description**: Parses a Go source string into an alist representation. ### go-typecheck-package - **Signature**: `(go-typecheck-package . opts)` - **Description**: Performs type checking on a Go package target. ### go-format - **Signature**: `(go-format )` - **Description**: Converts an AST back into a Go source string. ### go-ssa-build - **Signature**: `(go-ssa-build . opts)` - **Description**: Builds SSA representation for a given pattern. ### go-cfg - **Signature**: `(go-cfg . opts)` - **Description**: Generates a Control Flow Graph for a specific function. ### go-callgraph - **Signature**: `(go-callgraph )` - **Description**: Generates a call graph using the specified algorithm (e.g., 'static, 'cha, 'rta, 'vta). ### go-callgraph-callers - **Signature**: `(go-callgraph-callers )` - **Description**: Retrieves callers for a specific function name in the call graph. ### go-callgraph-callees - **Signature**: `(go-callgraph-callees )` - **Description**: Retrieves callees for a specific function name in the call graph. ### go-analyze - **Signature**: `(go-analyze ...)` - **Description**: Runs static analysis diagnostics on a pattern. ### go-analyze-list - **Signature**: `(go-analyze-list)` - **Description**: Returns a list of available analyzer names. ``` -------------------------------- ### (go-cfg pattern func-name . options) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Builds the control flow graph for a specified function within a Go package. ```APIDOC ## (go-cfg pattern func-name . options) ### Description Builds the control flow graph for a named function. Searches package-level functions and methods on named types. ### Parameters - **pattern** (string) - Required - A `go list`-compatible pattern. - **func-name** (string) - Required - Function name (unqualified). - **options** (symbol) - Optional - Use `'positions` to include source positions on blocks. ### Returns - **list of cfg-block** - A list of blocks containing index, preds, succs, idom, and optional metadata. ``` -------------------------------- ### Parse Go source and extract function names Source: https://github.com/aalpar/wile-goast/blob/master/docs/GO-STATIC-ANALYSIS.md Demonstrates parsing a Go string into an AST and filtering for function declarations. ```scheme (define file (go-parse-string "package demo func Add(a, b int) int { return a + b } func helper() {}")) (define names (filter-map (lambda (decl) (and (eq? (car decl) 'func-decl) (cdr (assoc 'name (cdr decl))))) (cdr (assoc 'decls (cdr file))))) names ; => ("Add" "helper") ``` -------------------------------- ### Extract Interface Refactoring in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/extract-interface.md Demonstrates the transition from a concrete type dependency to an interface-based dependency. ```go type FileStore struct{} func (FileStore) Save(data []byte) error { return nil } func backup(s FileStore, data []byte) error { return s.Save(data) } ``` ```go type FileStore struct{} func (FileStore) Save(data []byte) error { return nil } type Saver interface { Save(data []byte) error } func backup(s Saver, data []byte) error { return s.Save(data) } ``` -------------------------------- ### Build a call graph and query callers Source: https://github.com/aalpar/wile-goast/blob/master/docs/GO-STATIC-ANALYSIS.md Constructs a call graph for a package and queries for callers and callees of specific functions. ```scheme (import (wile goast callgraph)) (define cg (go-callgraph "." 'cha)) (define callers (go-callgraph-callers cg "(*Server).Handle")) ;; What does main call directly? (define callees (go-callgraph-callees cg "command-line-arguments.main")) ``` -------------------------------- ### Package Splitting API Source: https://github.com/aalpar/wile-goast/blob/master/docs/LIBRARIES.md Functions for analyzing Go package dependencies and recommending package splits based on IDF-weighted FCA. ```APIDOC ## import-signatures ### Description Extract per-function package dependency sets from go-func-refs output. ## compute-idf ### Description Calculate IDF weights for dependency informativeness. ## filter-noise ### Description Remove ubiquitous (low-IDF) dependencies. ## build-package-context ### Description Build FCA context at package granularity. ## refine-by-api-surface ### Description Build FCA context at (package, object) granularity. ## find-split ### Description Perform min-cut two-way partition via concept lattice. ## verify-acyclic ### Description Check a proposed split for Go import cycles. ## recommend-split ### Description Top-level function to recommend a split using IDF, FCA, min-cut, and cycle checking. ## recommend-split-findings ### Description Generate located findings for a recommend-split report, identifying group members and their positions. ``` -------------------------------- ### (walk val visitor) Source: https://github.com/aalpar/wile-goast/blob/master/docs/AST-NODES.md Performs a depth-first traversal of the AST. ```APIDOC ## (walk val visitor) ### Description Performs a depth-first walk over the AST. It calls the visitor function on each tagged-alist node and collects non-#f return values. ### Parameters - **val** (node) - The AST value to traverse. - **visitor** (function) - A function to apply to each node. ### Returns - **list** (list) - A list of collected non-#f results. ``` -------------------------------- ### Using NF Utility Source: https://github.com/aalpar/wile-goast/blob/master/docs/GO-STATIC-ANALYSIS.md Helper functions for querying node fields and tags using the (wile goast utils) library. ```scheme (import (wile goast utils)) (nf node 'name) ; => "Add" or #f (tag? node 'ident) ; => #t or #f ``` -------------------------------- ### go-format Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Converts an AST node back into formatted Go source code. ```APIDOC ## go-format ### Description Formats an AST node back into a Go source string. ### Parameters - **ast** (tagged alist) - Required - An s-expression AST node. ``` -------------------------------- ### Replace nil-check with null object in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/replace-nil-check-with-null-object.md Demonstrates the transition from a nilable pointer requiring manual checks to an interface-based approach using a no-op implementation. ```go type Logger struct{} func (Logger) Log(msg string) {} func run(log *Logger) { if log != nil { log.Log("start") } if log != nil { log.Log("end") } } ``` ```go type Logger interface{ Log(msg string) } type nopLogger struct{} func (nopLogger) Log(string) {} func run(log Logger) { log.Log("start") log.Log("end") } ``` -------------------------------- ### Apply SSA Normalization Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Shows how to apply default and custom normalization rules to SSA binop nodes using (wile goast ssa-normalize). ```scheme (import (wile goast ssa-normalize)) ;; Apply default normalization (ssa-normalize some-binop-node) ;; Custom rule set (commutative only) (define my-rules (ssa-rule-set (ssa-rule-commutative))) (ssa-normalize some-binop-node my-rules) ``` -------------------------------- ### Consolidate conditional expression in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/consolidate-conditional.md Demonstrates the transformation from multiple 'if' guards to a single return statement using boolean operators. ```go func disabled(u *T) bool { if u.banned { return true } if u.expired { return true } if !u.active { return true } return false } ``` ```go func disabled(u *T) bool { return u.banned || u.expired || !u.active } ``` -------------------------------- ### Analyze SSA instructions and field access Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Demonstrates how to extract store instructions and identify functions that write to a specific field using the SSA analysis module. ```scheme (import (wile goast ssa)) (define funcs (go-ssa-build "." 'positions)) ;; Find all store instructions across all functions (define stores (apply append (map (lambda (fn) (apply append (map (lambda (blk) (filter (lambda (i) (eq? (car i) 'ssa-store)) (cdr (assoc 'instrs (cdr blk))))) (cdr (assoc 'blocks (cdr fn)))))) funcs))) ;; Field index: find which functions write to a specific field (define index (go-ssa-field-index ".")) (define writers (filter-map (lambda (summary) (let ((writes (filter-map (lambda (access) (and (eq? (cdr (assoc 'mode (cdr access))) 'write) (equal? (cdr (assoc 'field (cdr access))) "Name") access)) (cdr (assoc 'fields (cdr summary)))))) (and (pair? writes) (cdr (assoc 'func (cdr summary)))))) index)) ``` -------------------------------- ### Core wile-goast Primitives Source: https://github.com/aalpar/wile-goast/blob/master/cmd/wile-goast/reference/cheatsheet.md A list of available Scheme functions for interacting with Go source code and analysis tools. ```scheme (go-parse-file . opts) -> (file ...) alist (go-parse-string . opts) -> (file ...) alist (go-typecheck-package . opts) -> list of (package ...) (go-format ) -> Go source string (go-ssa-build . opts) -> list of ssa-func (go-cfg . opts) -> list of cfg-block (go-callgraph ) -> list of cg-node (go-callgraph-callers ) -> list of cg-edge or #f (go-callgraph-callees ) -> list of cg-edge or #f (go-analyze ...) -> list of diagnostic (go-analyze-list) -> list of analyzer names ``` -------------------------------- ### Execute Beliefs Source: https://github.com/aalpar/wile-goast/blob/master/docs/GO-STATIC-ANALYSIS.md Run all defined beliefs against the project source code using the command line interface. ```bash wile-goast '(begin (import (wile goast belief)) (load ".goast-beliefs/lock-unlock.scm") (run-beliefs "./..."))' ``` -------------------------------- ### Encapsulate Collection Refactoring in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/encapsulate-collection.md Demonstrates the transition from exposing an internal slice directly to returning a defensive copy to ensure encapsulation. ```go type Roster struct { names []string } func (r *Roster) Names() []string { return r.names } func (r *Roster) Add(name string) { r.names = append(r.names, name) } ``` ```go type Roster struct { names []string } func (r *Roster) Names() []string { out := make([]string, len(r.names)) copy(out, r.names) return out } func (r *Roster) Add(name string) { r.names = append(r.names, name) } ``` -------------------------------- ### Find interface implementors Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Shows how to query for types implementing an interface using either a package pattern or a shared session. ```scheme ;; Find implementors of a project-local interface (define info (go-interface-implementors "Store" "my/pkg/...")) ;; With a shared session (define s (go-load "my/pkg/...")) (define info (go-interface-implementors "Store" s)) ;; Use in belief DSL via selectors (preferred) (define-belief "store-handles-errors" (sites (interface-methods "Store" "Get")) (expect (contains-call "ErrNotFound")) (threshold 0.80 2)) ``` -------------------------------- ### Configure MCP server Source: https://github.com/aalpar/wile-goast/blob/master/README.md JSON configuration block to register wile-goast as an MCP server within your client settings. ```json { "mcpServers": { "wile-goast": { "command": "wile-goast", "args": ["--mcp"] } } } ``` -------------------------------- ### Function Implementation (After) Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/convert-method-to-function.md The refactored version where the token is passed as an explicit parameter. ```go func wrapMidParseEOF(err error, tok Token, form string) error { if errors.Is(err, io.EOF) { return newErr(tok, io.ErrUnexpectedEOF, form) } return err } func (p *Parser) use() error { return wrapMidParseEOF(p.err, p.cur, "list") } ``` -------------------------------- ### Parameterize by Difference in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/parameterize-by-difference.md Consolidates functions with identical logic by introducing a parameter for the varying multiplier. ```go func priceSmall(n int) int { return n * 5 } func priceLarge(n int) int { return n * 9 } ``` ```go func priceSmall(n int) int { return price(n, 5) } func priceLarge(n int) int { return price(n, 9) } func price(n, unit int) int { return n * unit } ``` -------------------------------- ### (go-analyze-list) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Retrieves a list of all available analyzer names. ```APIDOC ## (go-analyze-list) ### Description Returns a sorted list of strings representing all available analyzer names that can be used with the go-analyze primitive. ``` -------------------------------- ### reference Source: https://github.com/aalpar/wile-goast/blob/master/docs/MCP.md Returns the distilled Scheme cheatsheet containing primitive arities, patterns, and idioms. ```APIDOC ## Tool: reference ### Description Returns the distilled Scheme cheatsheet, serving as a single source of truth for primitives and idioms. ``` -------------------------------- ### Refactor consume function to accept io.Reader Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/accept-smallest-interface.md Demonstrates narrowing a function parameter from a concrete *os.File type to the io.Reader interface. ```go import "os" func consume(f *os.File) ([]byte, error) { buf := make([]byte, 4) _, err := f.Read(buf) return buf, err } ``` ```go import "io" func consume(r io.Reader) ([]byte, error) { buf := make([]byte, 4) _, err := r.Read(buf) return buf, err } ``` -------------------------------- ### go-parse-file Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Parses a Go source file into a tagged alist AST representation. ```APIDOC ## go-parse-file ### Description Parses a Go file from the filesystem into a tagged alist AST node. ### Parameters - **filename** (string) - Required - Filesystem path to a .go file. ### Return Value - **(file ...)** (tagged alist) - The parsed AST structure. ``` -------------------------------- ### Split Loop Refactoring in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/split-loop.md Demonstrates the transformation from a single loop performing two unrelated accumulations to two distinct loops, each handling one concern. ```go func process(xs []int) (int, int) { total := 0 count := 0 for _, x := range xs { total += x if x < 0 { count++ } } return total, count } ``` ```go func process(xs []int) (int, int) { total := 0 for _, x := range xs { total += x } count := 0 for _, x := range xs { if x < 0 { count++ } } return total, count } ``` -------------------------------- ### Run SSA Unification Detection Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Executes the full unification pipeline on test case pairs to measure similarity across AST and SSA stages. ```bash cd /path/to/wile-goast wile-goast -f examples/goast-query/ssa-unify-detect.scm ``` -------------------------------- ### Implement nested conditional logic in Go Source: https://github.com/aalpar/wile-goast/blob/master/refactorings/guard-clause-flattening.md Initial state where the happy path is buried within multiple levels of conditional checks. ```go func process(v *T) error { if v != nil { if v.ok { doWork(v) return nil } return errNotOK } return errNil } ``` -------------------------------- ### (go-ssa-field-index pattern) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Generates a pre-correlated field access index for functions within a package. ```APIDOC ## (go-ssa-field-index pattern) ### Description Returns a pre-correlated field access index, providing one entry per function that reads or writes at least one struct field. Functions with no field accesses are omitted. ### Parameters - **pattern** (string) - Required - A `go list`-compatible pattern. ### Return Value - **ssa-field-summary** (list) - A list of nodes containing function name, package path, and a list of `ssa-field-access` entries. ``` -------------------------------- ### (go-analyze pattern analyzer-name ...) Source: https://github.com/aalpar/wile-goast/blob/master/docs/PRIMITIVES.md Runs specified Go analysis passes on a package matching the provided pattern. ```APIDOC ## (go-analyze pattern analyzer-name ...) ### Description Executes named Go analyzers on a specified package. Returns a list of diagnostic nodes. ### Parameters - **pattern** (string) - Required - A go list-compatible pattern. - **analyzer-name** (string) - Required - One or more analyzer names to execute. ### Return values - **analyzer** (string) - Name of the analyzer that produced the diagnostic. - **pos** (string) - Source position in format file:line:col. - **message** (string) - The diagnostic message. - **category** (string) - The diagnostic category. ``` -------------------------------- ### Run wile-goast scripts Source: https://github.com/aalpar/wile-goast/blob/master/docs/EXAMPLES.md Execute a specific belief script against a target Go directory. ```bash cd /path/to/etcd/server # or etcd/raft for raft-* scripts wile-goast -f /path/to/examples/etcd/