assyrianic / SourceGo

SourceGo is a transpiler that transforms a subset of Golang-like code to equivalent SourcePawn.
https://forums.alliedmods.net/showthread.php?t=328269
MIT License
25 stars 3 forks source link

Function Literals become actual, randomly named functions #5

Closed assyrianic closed 3 years ago

assyrianic commented 3 years ago

Golang allows you to make function literals:

my_func := func() {
    /// code here!
}
my_func()

Golang even allows more by directly calling from the literal:

func() {
    /// code here!
}()

We can generate that by getting the function signature and creating a new function out of it.

type FuncLit struct {
    Type *ast.FuncType  // function type
    Body *ast.BlockStmt // function body
}

Everything needed to make a full fledged function is there, just need a name and assign it from a *ast.FuncDecl instead. Once the function is made, we then replace the function literal with the (oddly) named function.

func() {} => func SGJDDS() {}
...
/// my_func := func() {}
my_func := SGJDDS

/// func() {}()
SGJDDS()

One thing to remember when doing this is got match functions by both the type and body nodes, gotta check to see if body nodes contain the same number of nodes and same type of expressions. Even then, that still might not be the best way to make sure it's the correct function literal but it's better than nothing.