prettyprinter.go 8.2 KB

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