prettyprinter.go 9.1 KB

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