github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/ast/indentwriter.go (about) 1 package ast 2 3 import ( 4 "fmt" 5 "io" 6 ) 7 8 // IndentWriter is an implementation of HWriter that writes AST with indentation 9 // to show the tree structure. 10 type IndentWriter struct { 11 writer io.Writer 12 depth int 13 } 14 15 var _ HWriter = (*IndentWriter)(nil) 16 17 // NewIndentWriter returns a new pointer to IndentWriter that will write using 18 // the given io.Writer. 19 func NewIndentWriter(w io.Writer) *IndentWriter { 20 return &IndentWriter{writer: w} 21 } 22 23 // Writef is like Printf. 24 func (w *IndentWriter) Writef(f string, args ...interface{}) { 25 fmt.Fprintf(w.writer, f, args...) 26 } 27 28 // Indent increments the current indentation by one level. 29 func (w *IndentWriter) Indent() { 30 w.depth++ 31 } 32 33 // Dedent decrements the current indentation by one level. 34 func (w *IndentWriter) Dedent() { 35 w.depth-- 36 } 37 38 const spaces80 = " " 39 40 // Next moves on to the next line and adds the necessary indentation. 41 func (w *IndentWriter) Next() { 42 w.writer.Write([]byte("\n")) 43 i := w.depth * 4 44 for i > 80 { 45 w.writer.Write([]byte(spaces80)) 46 i -= 80 47 } 48 w.writer.Write([]byte(spaces80)[:i]) 49 }