prettyprinter.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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(NodeSTRING).Parse("{{.qval}}")),
  29. NodeNUMBER: template.Must(template.New(NodeNUMBER).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. NodeCOMPACCESS + "_1": template.Must(template.New(NodeCOMPACCESS).Parse("[{{.c1}}]")),
  35. /*
  36. NodeSTATEMENTS = "statements" // List of statements
  37. // Assignment statement
  38. NodeASSIGN = ":="
  39. */
  40. // Assignment statement
  41. NodeASSIGN + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} := {{.c2}}")),
  42. // Import statement
  43. NodeIMPORT + "_2": template.Must(template.New(NodeMINUS).Parse("import {{.c1}} as {{.c2}}")),
  44. // Arithmetic operators
  45. NodePLUS + "_1": template.Must(template.New(NodePLUS).Parse("+{{.c1}}")),
  46. NodePLUS + "_2": template.Must(template.New(NodePLUS).Parse("{{.c1}} + {{.c2}}")),
  47. NodeMINUS + "_1": template.Must(template.New(NodeMINUS).Parse("-{{.c1}}")),
  48. NodeMINUS + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} - {{.c2}}")),
  49. NodeTIMES + "_2": template.Must(template.New(NodeTIMES).Parse("{{.c1}} * {{.c2}}")),
  50. NodeDIV + "_2": template.Must(template.New(NodeDIV).Parse("{{.c1}} / {{.c2}}")),
  51. NodeMODINT + "_2": template.Must(template.New(NodeMODINT).Parse("{{.c1}} % {{.c2}}")),
  52. NodeDIVINT + "_2": template.Must(template.New(NodeDIVINT).Parse("{{.c1}} // {{.c2}}")),
  53. // Boolean operators
  54. NodeOR + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} or {{.c2}}")),
  55. NodeAND + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} and {{.c2}}")),
  56. NodeNOT + "_1": template.Must(template.New(NodeNOT).Parse("not {{.c1}}")),
  57. // Condition operators
  58. NodeLIKE + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} like {{.c2}}")),
  59. NodeIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} in {{.c2}}")),
  60. NodeHASPREFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hasprefix {{.c2}}")),
  61. NodeHASSUFFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hassuffix {{.c2}}")),
  62. NodeNOTIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} notin {{.c2}}")),
  63. NodeGEQ + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} >= {{.c2}}")),
  64. NodeLEQ + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} <= {{.c2}}")),
  65. NodeNEQ + "_2": template.Must(template.New(NodeNEQ).Parse("{{.c1}} != {{.c2}}")),
  66. NodeEQ + "_2": template.Must(template.New(NodeEQ).Parse("{{.c1}} == {{.c2}}")),
  67. NodeGT + "_2": template.Must(template.New(NodeGT).Parse("{{.c1}} > {{.c2}}")),
  68. NodeLT + "_2": template.Must(template.New(NodeLT).Parse("{{.c1}} < {{.c2}}")),
  69. // Constants
  70. NodeTRUE: template.Must(template.New(NodeTRUE).Parse("true")),
  71. NodeFALSE: template.Must(template.New(NodeFALSE).Parse("false")),
  72. NodeNULL: template.Must(template.New(NodeNULL).Parse("null")),
  73. }
  74. bracketPrecedenceMap = map[string]bool{
  75. NodePLUS: true,
  76. NodeMINUS: true,
  77. NodeAND: true,
  78. NodeOR: true,
  79. }
  80. }
  81. /*
  82. PrettyPrint produces pretty printed code from a given AST.
  83. */
  84. func PrettyPrint(ast *ASTNode) (string, error) {
  85. var visit func(ast *ASTNode, level int) (string, error)
  86. ppMetaData := func(ast *ASTNode, ppString string) string {
  87. ret := ppString
  88. // Add meta data
  89. if len(ast.Meta) > 0 {
  90. for _, meta := range ast.Meta {
  91. if meta.Type() == MetaDataPreComment {
  92. ret = fmt.Sprintf("/*%v*/ %v", meta.Value(), ret)
  93. } else if meta.Type() == MetaDataPostComment {
  94. ret = fmt.Sprintf("%v #%v", ret, meta.Value())
  95. }
  96. }
  97. }
  98. return ret
  99. }
  100. visit = func(ast *ASTNode, level int) (string, error) {
  101. var buf bytes.Buffer
  102. var numChildren = len(ast.Children)
  103. tempKey := ast.Name
  104. tempParam := make(map[string]string)
  105. // First pretty print children
  106. if numChildren > 0 {
  107. for i, child := range ast.Children {
  108. res, err := visit(child, level+1)
  109. if err != nil {
  110. return "", err
  111. }
  112. if _, ok := bracketPrecedenceMap[child.Name]; ok && ast.binding > child.binding {
  113. // Put the expression in brackets iff (if and only if) the binding would
  114. // normally order things differently
  115. res = fmt.Sprintf("(%v)", res)
  116. }
  117. tempParam[fmt.Sprint("c", i+1)] = res
  118. }
  119. tempKey += fmt.Sprint("_", len(tempParam))
  120. }
  121. // Handle special cases - children in tempParam have been resolved
  122. if ast.Name == NodeSTATEMENTS {
  123. // For statements just concat all children
  124. for i := 0; i < numChildren; i++ {
  125. buf.WriteString(stringutil.GenerateRollingString(" ", level*4))
  126. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  127. buf.WriteString("\n")
  128. }
  129. return ppMetaData(ast, buf.String()), nil
  130. } else if ast.Name == NodeFUNCCALL {
  131. // For statements just concat all children
  132. for i := 0; i < numChildren; i++ {
  133. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  134. if i < numChildren-1 {
  135. buf.WriteString(", ")
  136. }
  137. }
  138. return ppMetaData(ast, buf.String()), nil
  139. } else if ast.Name == NodeIDENTIFIER {
  140. buf.WriteString(ast.Token.Val)
  141. for i := 0; i < numChildren; i++ {
  142. if ast.Children[i].Name == NodeIDENTIFIER {
  143. buf.WriteString(".")
  144. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  145. } else if ast.Children[i].Name == NodeFUNCCALL {
  146. buf.WriteString("(")
  147. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  148. buf.WriteString(")")
  149. } else if ast.Children[i].Name == NodeCOMPACCESS {
  150. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  151. }
  152. }
  153. return ppMetaData(ast, buf.String()), nil
  154. }
  155. if ast.Token != nil {
  156. // Adding node value to template parameters
  157. tempParam["val"] = ast.Token.Val
  158. tempParam["qval"] = strconv.Quote(ast.Token.Val)
  159. }
  160. // Retrieve the template
  161. temp, ok := prettyPrinterMap[tempKey]
  162. if !ok {
  163. return "", fmt.Errorf("Could not find template for %v (tempkey: %v)",
  164. ast.Name, tempKey)
  165. }
  166. // Use the children as parameters for template
  167. errorutil.AssertOk(temp.Execute(&buf, tempParam))
  168. return ppMetaData(ast, buf.String()), nil
  169. }
  170. return visit(ast, 0)
  171. }