github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/ast/ifstat.go (about) 1 package ast 2 3 import ( 4 "github.com/arnodel/golua/token" 5 ) 6 7 // IfStat is a statement node representing an "if ... [elseif] ... [else] ... 8 // end" statement, where the else clause is optional and there can be 0 or more 9 // elseif clauses. 10 type IfStat struct { 11 Location 12 If CondStat 13 ElseIfs []CondStat 14 Else *BlockStat 15 } 16 17 var _ Stat = IfStat{} 18 19 // NewIfStat returns an IfStat with the given condition and then clause. 20 func NewIfStat(ifTok *token.Token, cond ExpNode, body BlockStat) IfStat { 21 return IfStat{ 22 Location: LocFromToken(ifTok), 23 If: CondStat{cond, body}, 24 } 25 } 26 27 // WithElse returns an IfStat based on the receiver but with the given else 28 // clause. 29 func (s IfStat) WithElse(endTok *token.Token, body BlockStat) IfStat { 30 s.Location = MergeLocations(s, LocFromToken(endTok)) 31 s.Else = &body 32 return s 33 } 34 35 // AddElseIf returns an IfStat based on the receiver but adding an extra elseif 36 // clause. 37 func (s IfStat) AddElseIf(cond ExpNode, body BlockStat) IfStat { 38 s.ElseIfs = append(s.ElseIfs, CondStat{cond, body}) 39 return s 40 } 41 42 // ProcessStat uses the given StatProcessor to process the receiver. 43 func (s IfStat) ProcessStat(p StatProcessor) { 44 p.ProcessIfStat(s) 45 } 46 47 // HWrite prints a tree representation of the node. 48 func (s IfStat) HWrite(w HWriter) { 49 w.Writef("if: ") 50 w.Indent() 51 s.If.HWrite(w) 52 for _, elseifstat := range s.ElseIfs { 53 w.Next() 54 w.Writef("elseif: ") 55 elseifstat.HWrite(w) 56 } 57 if s.Else != nil { 58 w.Next() 59 w.Writef("else:") 60 s.Else.HWrite(w) 61 } 62 w.Dedent() 63 }