prettyprinter.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package parser
  10. import (
  11. "bytes"
  12. "fmt"
  13. "strconv"
  14. "text/template"
  15. "devt.de/krotik/common/errorutil"
  16. "devt.de/krotik/common/stringutil"
  17. )
  18. /*
  19. Map of AST nodes corresponding to lexer tokens
  20. */
  21. var prettyPrinterMap map[string]*template.Template
  22. /*
  23. Map of nodes where the precedence might have changed because of parentheses
  24. */
  25. var bracketPrecedenceMap map[string]bool
  26. func init() {
  27. prettyPrinterMap = map[string]*template.Template{
  28. NodeSTRING: template.Must(template.New(NodeTRUE).Parse("{{.qval}}")),
  29. NodeNUMBER: template.Must(template.New(NodeTRUE).Parse("{{.val}}")),
  30. // NodeIDENTIFIER - Special case (handled in code)
  31. // Constructed tokens
  32. // NodeSTATEMENTS - Special case (handled in code)
  33. // NodeFUNCCALL - Special case (handled in code)
  34. /*
  35. NodeSTATEMENTS = "statements" // List of statements
  36. // Assignment statement
  37. NodeASSIGN = ":="
  38. */
  39. // Assignment statement
  40. NodeASSIGN + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} := {{.c2}}")),
  41. // Import statement
  42. NodeIMPORT + "_2": template.Must(template.New(NodeMINUS).Parse("import {{.c1}} as {{.c2}}")),
  43. // Arithmetic operators
  44. NodePLUS + "_1": template.Must(template.New(NodeMINUS).Parse("+{{.c1}}")),
  45. NodePLUS + "_2": template.Must(template.New(NodePLUS).Parse("{{.c1}} + {{.c2}}")),
  46. NodeMINUS + "_1": template.Must(template.New(NodeMINUS).Parse("-{{.c1}}")),
  47. NodeMINUS + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} - {{.c2}}")),
  48. NodeTIMES + "_2": template.Must(template.New(NodeTIMES).Parse("{{.c1}} * {{.c2}}")),
  49. NodeDIV + "_2": template.Must(template.New(NodeDIV).Parse("{{.c1}} / {{.c2}}")),
  50. NodeMODINT + "_2": template.Must(template.New(NodeMODINT).Parse("{{.c1}} % {{.c2}}")),
  51. NodeDIVINT + "_2": template.Must(template.New(NodeDIVINT).Parse("{{.c1}} // {{.c2}}")),
  52. // Boolean operators
  53. NodeOR + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} or {{.c2}}")),
  54. NodeAND + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} and {{.c2}}")),
  55. NodeNOT + "_1": template.Must(template.New(NodeNOT).Parse("not {{.c1}}")),
  56. // Condition operators
  57. NodeLIKE + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} like {{.c2}}")),
  58. NodeIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} in {{.c2}}")),
  59. NodeHASPREFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hasprefix {{.c2}}")),
  60. NodeHASSUFFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hassuffix {{.c2}}")),
  61. NodeNOTIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} notin {{.c2}}")),
  62. NodeGEQ + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} >= {{.c2}}")),
  63. NodeLEQ + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} <= {{.c2}}")),
  64. NodeNEQ + "_2": template.Must(template.New(NodeNEQ).Parse("{{.c1}} != {{.c2}}")),
  65. NodeEQ + "_2": template.Must(template.New(NodeEQ).Parse("{{.c1}} == {{.c2}}")),
  66. NodeGT + "_2": template.Must(template.New(NodeGT).Parse("{{.c1}} > {{.c2}}")),
  67. NodeLT + "_2": template.Must(template.New(NodeLT).Parse("{{.c1}} < {{.c2}}")),
  68. // Constants
  69. NodeTRUE: template.Must(template.New(NodeTRUE).Parse("true")),
  70. NodeFALSE: template.Must(template.New(NodeFALSE).Parse("false")),
  71. NodeNULL: template.Must(template.New(NodeNULL).Parse("null")),
  72. }
  73. bracketPrecedenceMap = map[string]bool{
  74. NodePLUS: true,
  75. NodeMINUS: true,
  76. NodeAND: true,
  77. NodeOR: true,
  78. }
  79. }
  80. /*
  81. PrettyPrint produces pretty printed code from a given AST.
  82. */
  83. func PrettyPrint(ast *ASTNode) (string, error) {
  84. var visit func(ast *ASTNode, level int) (string, error)
  85. ppMetaData := func(ast *ASTNode, ppString string) string {
  86. ret := ppString
  87. // Add meta data
  88. if len(ast.Meta) > 0 {
  89. for _, meta := range ast.Meta {
  90. if meta.Type() == MetaDataPreComment {
  91. ret = fmt.Sprintf("/*%v*/ %v", meta.Value(), ret)
  92. } else if meta.Type() == MetaDataPostComment {
  93. ret = fmt.Sprintf("%v #%v", ret, meta.Value())
  94. }
  95. }
  96. }
  97. return ret
  98. }
  99. visit = func(ast *ASTNode, level int) (string, error) {
  100. var buf bytes.Buffer
  101. var numChildren = len(ast.Children)
  102. tempKey := ast.Name
  103. tempParam := make(map[string]string)
  104. // First pretty print children
  105. if numChildren > 0 {
  106. for i, child := range ast.Children {
  107. res, err := visit(child, level+1)
  108. if err != nil {
  109. return "", err
  110. }
  111. if _, ok := bracketPrecedenceMap[child.Name]; ok && ast.binding > child.binding {
  112. // Put the expression in brackets iff (if and only if) the binding would
  113. // normally order things differently
  114. res = fmt.Sprintf("(%v)", res)
  115. }
  116. tempParam[fmt.Sprint("c", i+1)] = res
  117. }
  118. tempKey += fmt.Sprint("_", len(tempParam))
  119. }
  120. // Handle special cases - children in tempParam have been resolved
  121. if ast.Name == NodeSTATEMENTS {
  122. // For statements just concat all children
  123. for i := 0; i < numChildren; i++ {
  124. buf.WriteString(stringutil.GenerateRollingString(" ", level*4))
  125. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  126. buf.WriteString("\n")
  127. }
  128. return ppMetaData(ast, buf.String()), nil
  129. } else if ast.Name == NodeFUNCCALL {
  130. // For statements just concat all children
  131. for i := 0; i < numChildren; i++ {
  132. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  133. if i < numChildren-1 {
  134. buf.WriteString(", ")
  135. }
  136. }
  137. return ppMetaData(ast, buf.String()), nil
  138. } else if ast.Name == NodeIDENTIFIER {
  139. buf.WriteString(ast.Token.Val)
  140. for i := 0; i < numChildren; i++ {
  141. if ast.Children[i].Name == NodeIDENTIFIER {
  142. buf.WriteString(".")
  143. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  144. }
  145. if ast.Children[i].Name == NodeFUNCCALL {
  146. buf.WriteString("(")
  147. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  148. buf.WriteString(")")
  149. }
  150. }
  151. return ppMetaData(ast, buf.String()), nil
  152. }
  153. if ast.Token != nil {
  154. // Adding node value to template parameters
  155. tempParam["val"] = ast.Token.Val
  156. tempParam["qval"] = strconv.Quote(ast.Token.Val)
  157. }
  158. // Retrieve the template
  159. temp, ok := prettyPrinterMap[tempKey]
  160. if !ok {
  161. return "", fmt.Errorf("Could not find template for %v (tempkey: %v)",
  162. ast.Name, tempKey)
  163. }
  164. // Use the children as parameters for template
  165. errorutil.AssertOk(temp.Execute(&buf, tempParam))
  166. return ppMetaData(ast, buf.String()), nil
  167. }
  168. return visit(ast, 0)
  169. }