### Install go-fAST Golang Library Source: https://github.com/t14raptor/go-fast/blob/master/README.md This command installs the go-fAST library into your Go project using the go get command. Ensure you have Go installed and configured in your environment. ```sh go get github.com/t14raptor/go-fast ``` -------------------------------- ### Traverse and Count AST Node Types in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Illustrates how to traverse an Abstract Syntax Tree (AST) and count occurrences of different node types using a custom visitor pattern in Go. This example utilizes the `go-fast/ast` and `go-fast/parser` packages to parse source code and then visit each node. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/ast" "github.com/t14raptor/go-fast/parser" ) // TypeInspector reports node types type TypeInspector struct { ast.NoopVisitor Types map[string]int } func (ti *TypeInspector) recordType(name string) { ti.Types[name]++ } func (ti *TypeInspector) VisitStringLiteral(n *ast.StringLiteral) { ti.recordType("StringLiteral") } func (ti *TypeInspector) VisitNumberLiteral(n *ast.NumberLiteral) { ti.recordType("NumberLiteral") } func (ti *TypeInspector) VisitBinaryExpression(n *ast.BinaryExpression) { ti.recordType("BinaryExpression") n.VisitChildrenWith(ti) } func (ti *TypeInspector) VisitCallExpression(n *ast.CallExpression) { ti.recordType("CallExpression") n.VisitChildrenWith(ti) } func (ti *TypeInspector) VisitArrowFunctionLiteral(n *ast.ArrowFunctionLiteral) { ti.recordType("ArrowFunctionLiteral") n.VisitChildrenWith(ti) } func (ti *TypeInspector) VisitFunctionLiteral(n *ast.FunctionLiteral) { ti.recordType("FunctionLiteral") n.VisitChildrenWith(ti) } func (ti *TypeInspector) VisitIfStatement(n *ast.IfStatement) { ti.recordType("IfStatement") n.VisitChildrenWith(ti) } func (ti *TypeInspector) VisitForStatement(n *ast.ForStatement) { ti.recordType("ForStatement") n.VisitChildrenWith(ti) } func main() { source := ` const greeting = "Hello"; const count = 42; const add = (a, b) => a + b; function multiply(x, y) { return x * y; } if (count > 0) { console.log(greeting); } for (let i = 0; i < 10; i++) { add(i, 1); } ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } inspector := &TypeInspector{Types: make(map[string]int)} inspector.V = inspector program.VisitWith(inspector) fmt.Println("AST Node Types Found:") for nodeType, count := range inspector.Types { fmt.Printf(" %s: %d\n", nodeType, count) } // Output: // AST Node Types Found: // StringLiteral: 1 // NumberLiteral: 4 // BinaryExpression: 3 // CallExpression: 2 // ArrowFunctionLiteral: 1 // FunctionLiteral: 1 // IfStatement: 1 // ForStatement: 1 } ``` -------------------------------- ### Custom AST Traversal with Visitor Pattern in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Implements the ast.Visitor interface to perform custom traversals of an Abstract Syntax Tree (AST). By embedding ast.NoopVisitor, developers can selectively override methods for specific node types, enabling focused analysis while ensuring children are automatically visited. This example shows collecting function names and counting identifier usages. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/ast" "github.com/t14raptor/go-fast/parser" ) // FunctionCollector finds all function names in code type FunctionCollector struct { ast.NoopVisitor Functions []string } func (fc *FunctionCollector) VisitFunctionLiteral(n *ast.FunctionLiteral) { if n.Name != nil { fc.Functions = append(fc.Functions, n.Name.Name) } // Continue visiting children n.VisitChildrenWith(fc) } // IdentifierCounter counts variable references type IdentifierCounter struct { ast.NoopVisitor Counts map[string]int } func (ic *IdentifierCounter) VisitIdentifier(n *ast.Identifier) { ic.Counts[n.Name]++ } func main() { source := ` function calculateTotal(items) { function sum(a, b) { return a + b; } let total = 0; for (const item of items) { total = sum(total, item.price); } return total; } const result = calculateTotal(products); ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Collect function names collector := &FunctionCollector{} collector.V = collector program.VisitWith(collector) fmt.Printf("Functions found: %v\n", collector.Functions) // Output: Functions found: [calculateTotal sum] // Count identifier usage counter := &IdentifierCounter{Counts: make(map[string]int)} counter.V = counter program.VisitWith(counter) fmt.Printf("Variable 'total' used %d times\n", counter.Counts["total"]) fmt.Printf("Variable 'item' used %d times\n", counter.Counts["item"]) // Output: // Variable 'total' used 4 times // Variable 'item' used 2 times } ``` -------------------------------- ### Dead Code Elimination in Go AST Source: https://context7.com/t14raptor/go-fast/llms.txt Removes unreachable and unused code from an Abstract Syntax Tree (AST) using the deadcode.Eliminate function. This process analyzes variable usage, removes unused declarations, and prunes code paths that cannot be executed. It's beneficial for code optimization and deobfuscation. The example demonstrates removing unused functions and variables, as well as simplifying conditional logic. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/generator" "github.com/t14raptor/go-fast/parser" "github.com/t14raptor/go-fast/transform/deadcode" ) func main() { // Code with dead code source := ` function used() { return 42; } function unused() { return "never called"; } const a = 1; const b = 2; // unused const c = 3; // unused const result = used() + a; console.log(result); ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Remove dead code (true = resolve scope first) deadcode.Eliminate(program, true) // Generate cleaned code output := generator.Generate(program) fmt.Println(output) // Output: // function used() { // return 42; // } // const a = 1; // const result = used() + a; // console.log(result); // Eliminates unreachable branches source2 := ` const debug = false; if (debug && expensiveCheck()) { console.log("Debug mode"); } const value = true || computeDefault(); ` program2, _ := parser.ParseFile(source2) deadcode.Eliminate(program2, true) fmt.Println(generator.Generate(program2)) // Output shows simplified conditionals with dead branches removed } ``` -------------------------------- ### Deep Copy AST Nodes with Clone() in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Demonstrates how to create deep copies of AST nodes using the `Clone()` method in Go. This allows for modification of the copied nodes without altering the original AST. It requires the `go-fast/ast`, `go-fast/generator`, and `go-fast/parser` packages. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/ast" "github.com/t14raptor/go-fast/generator" "github.com/t14raptor/go-fast/parser" ) func main() { source := ` function greet(name) { return "Hello, " + name; } ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Clone the entire program cloned := program.Clone() // Modify the clone without affecting original // Access first statement (function declaration) if len(cloned.Body) > 0 { if funcDecl, ok := cloned.Body[0].Stmt.(*ast.FunctionDeclaration); ok { funcDecl.Function.Name.Name = "sayHello" } } // Original unchanged fmt.Println("Original:") fmt.Println(generator.Generate(program)) // Output: // function greet(name) { // return "Hello, " + name; // } // Clone modified fmt.Println("Clone:") fmt.Println(generator.Generate(cloned)) // Output: // function sayHello(name) { // return "Hello, " + name; // } // Clone individual expressions exprSource := `const x = a + b * c;` prog2, _ := parser.ParseFile(exprSource) if len(prog2.Body) > 0 { if varDecl, ok := prog2.Body[0].Stmt.(*ast.VariableDeclaration); ok { if len(varDecl.List) > 0 && varDecl.List[0].Initializer != nil { exprClone := varDecl.List[0].Initializer.Clone() fmt.Printf("Cloned expression type: %T\n", exprClone.Expr) // Output: Cloned expression type: *ast.BinaryExpression } } } } ``` -------------------------------- ### Parse JavaScript Code with go-fast Source: https://context7.com/t14raptor/go-fast/llms.txt Parses JavaScript source code into an Abstract Syntax Tree (AST) using the `parser.ParseFile` function. This is the initial step in the parse-transform-generate workflow. It takes a file path as input and returns the AST and any potential errors. ```go package main import ( "fmt" "github.com/t14raptor/go-fast/parser" ) func main() { filePath := "./example.js" ast, err := parser.ParseFile(filePath, nil) if err != nil { fmt.Printf("Error parsing file: %v\n", err) return } fmt.Printf("Successfully parsed AST from %s\n", filePath) // Further processing of the AST can be done here _ = ast // Avoid unused variable error } ``` -------------------------------- ### Simplify Expressions in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Optimizes and simplifies expressions by evaluating constant expressions, folding literals, and reducing complex expressions to simpler forms using the go-fast library. This is useful for deobfuscation and code optimization. It takes source code as a string, parses it, simplifies it, and then generates the optimized code. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/generator" "github.com/t14raptor/go-fast/parser" "github.com/t14raptor/go-fast/transform/simplifier" ) func main() { // Code with expressions that can be simplified source := ` const a = 1 + 2 + 3; const b = "Hello, " + "World!"; const c = 10 * 2 / 4; const d = true && false; const e = 5 > 3 ? "yes" : "no"; const f = typeof "string"; const g = !true; const h = [1, 2, 3].length; const i = "hello"[0]; const j = [10, 20, 30][1]; ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Simplify expressions (true = resolve scope first) simplifier.Simplify(program, true) output := generator.Generate(program) fmt.Println(output) // Output: // const a = 6; // const b = "Hello, World!"; // const c = 5; // const d = false; // const e = "yes"; // const f = "string"; // const g = false; // const h = 3; // const i = "h"; // const j = (0, 20); // Deobfuscation example obfuscated := ` var _0x1 = 2 + 2; var _0x2 = "he" + "ll" + "o"; var _0x3 = (1 > 0) ? _0x2 : "bye"; var _0x4 = !![]; var _0x5 = +[]; ` program2, _ := parser.ParseFile(obfuscated) simplifier.Simplify(program2, true) fmt.Println(generator.Generate(program2)) // Output shows simplified/deobfuscated code } ``` -------------------------------- ### Resolve Scopes in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Resolves variable scopes and bindings in the Abstract Syntax Tree (AST) using the go-fast library. This is essential for accurate dead code elimination and other transformations that need to understand variable usage across scopes. It parses source code, resolves scopes, and then allows for analysis of scope contexts. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/ast" "github.com/t14raptor/go-fast/parser" "github.com/t14raptor/go-fast/resolver" ) // ScopeAnalyzer examines scope contexts type ScopeAnalyzer struct { ast.NoopVisitor Scopes map[ast.ScopeContext][]string } func (sa *ScopeAnalyzer) VisitIdentifier(n *ast.Identifier) { if sa.Scopes == nil { sa.Scopes = make(map[ast.ScopeContext][]string) } sa.Scopes[n.ScopeContext] = append(sa.Scopes[n.ScopeContext], n.Name) } func main() { source := ` const globalVar = "global"; function outer() { const outerVar = "outer"; function inner() { const innerVar = "inner"; console.log(globalVar, outerVar, innerVar); } inner(); } outer(); ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Resolve scopes resolver.Resolve(program) // Analyze scope contexts analyzer := &ScopeAnalyzer{Scopes: make(map[ast.ScopeContext][]string)} analyzer.V = analyzer program.VisitWith(analyzer) fmt.Printf("Found %d different scope contexts\n", len(analyzer.Scopes)) // Variables are now tagged with their scope context for accurate analysis for ctx, vars := range analyzer.Scopes { fmt.Printf("Scope %d: %v\n", ctx, vars) } } ``` -------------------------------- ### Parse JavaScript Source Code to AST in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Parses JavaScript source code into an AST representation using the `parser.ParseFile` function. This function takes a string of JavaScript code and returns an `ast.Program` node or an error. It supports modern JavaScript syntax including ES6+ features. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/parser" ) func main() { // Parse JavaScript code source := ` function greet(name) { return "Hello, " + name + "!"; } const result = greet("World"); console.log(result); ` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Access the AST fmt.Printf("Parsed %d statements\n", len(program.Body)) // Output: Parsed 3 statements // Parse modern JavaScript with ES6+ features modernJS := ` const add = (a, b) => a + b; const nums = [1, 2, 3]; const [first, ...rest] = nums; const obj = { x: 1, y: 2, ...{ z: 3 } }; class Calculator { constructor(value = 0) { this.value = value; } add(n) { this.value += n; return this; } } async function fetchData(url) { const response = await fetch(url); return response.json(); } ` program2, err := parser.ParseFile(modernJS) if err != nil { log.Fatalf("Parse error: %v", err) } fmt.Printf("Parsed modern JS with %d statements\n", len(program2.Body)) // Output: Parsed modern JS with 6 statements } ``` -------------------------------- ### Generate JavaScript Code from AST in Go Source: https://context7.com/t14raptor/go-fast/llms.txt Converts an AST node back into JavaScript source code using the `generator.Generate` function. This function takes an `ast.Program` node and returns a formatted JavaScript string. It enables round-trip parsing and code generation. ```go package main import ( "fmt" "log" "github.com/t14raptor/go-fast/generator" "github.com/t14raptor/go-fast/parser" ) func main() { // Parse and regenerate code source := `function add(a,b){return a+b}const x=add(1,2);` program, err := parser.ParseFile(source) if err != nil { log.Fatalf("Parse error: %v", err) } // Generate formatted JavaScript from AST output := generator.Generate(program) fmt.Println(output) // Output: // function add(a, b) { // return a + b; // } // const x = add(1, 2); // Generate code for individual nodes complexSource := ` const config = { debug: true, settings: { theme: "dark", fontSize: 14 } }; ` program2, _ := parser.ParseFile(complexSource) regenerated := generator.Generate(program2) fmt.Println(regenerated) // Output: // const config = { // debug: true, // settings: { // theme: "dark", // fontSize: 14 // } // }; } ``` -------------------------------- ### Generate JavaScript Code with go-fast Source: https://context7.com/t14raptor/go-fast/llms.txt Regenerates JavaScript code from an Abstract Syntax Tree (AST) using the `generator.Generate` function. This is the final step in the parse-transform-generate workflow, converting the modified AST back into source code. It takes an AST node as input and returns the generated code as a string. ```go package main import ( "fmt" "github.com/t14raptor/go-fast/generator" "github.com/t14raptor/go-fast/parser" ) func main() { // Assume 'ast' is a valid AST obtained from parser.ParseFile filePath := "./example.js" ast, err := parser.ParseFile(filePath, nil) if err != nil { fmt.Printf("Error parsing file: %v\n", err) return } generatedCode, err := generator.Generate(ast) if err != nil { fmt.Printf("Error generating code: %v\n", err) return } fmt.Println("Generated JavaScript code:") fmt.Println(generatedCode) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.