github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/ast/function.go (about) 1 package ast 2 3 import ( 4 "github.com/arnodel/golua/token" 5 ) 6 7 // A Function is an expression node representing a function definition, i.e. 8 // "function Name(ParList) do Body end". The Name is optional. 9 type Function struct { 10 Location 11 ParList 12 Body BlockStat 13 Name string 14 } 15 16 var _ ExpNode = Function{} 17 18 // NewFunction returns a Function instance built from the given arguments. 19 func NewFunction(startTok, endTok *token.Token, parList ParList, body BlockStat) Function { 20 // Make sure we return at the end of the function 21 if body.Return == nil { 22 body.Return = []ExpNode{} 23 } 24 return Function{ 25 Location: LocFromTokens(startTok, endTok), 26 ParList: parList, 27 Body: body, 28 } 29 } 30 31 // ProcessExp uses the given ExpProcessor to process the receiver. 32 func (f Function) ProcessExp(p ExpProcessor) { 33 p.ProcessFunctionExp(f) 34 } 35 36 // HWrite prints a tree representation of the node. 37 func (f Function) HWrite(w HWriter) { 38 w.Writef("(") 39 for i, param := range f.Params { 40 w.Writef(param.Val) 41 if i < len(f.Params)-1 || f.HasDots { 42 w.Writef(", ") 43 } 44 } 45 if f.HasDots { 46 w.Writef("...") 47 } 48 w.Writef(")") 49 w.Indent() 50 w.Next() 51 f.Body.HWrite(w) 52 w.Dedent() 53 } 54 55 // A ParList represents a function parameter list (it is not a node). 56 type ParList struct { 57 Params []Name 58 HasDots bool 59 } 60 61 // NewParList returns ParList instance for the given parameters. 62 func NewParList(params []Name, hasDots bool) ParList { 63 return ParList{ 64 Params: params, 65 HasDots: hasDots, 66 } 67 }