prettyprinter.go 10 KB

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