prettyprinter.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package parser
  11. import (
  12. "bytes"
  13. "fmt"
  14. "strconv"
  15. "text/template"
  16. "devt.de/krotik/common/errorutil"
  17. "devt.de/krotik/common/stringutil"
  18. )
  19. /*
  20. Map of AST nodes corresponding to lexer tokens
  21. */
  22. var prettyPrinterMap map[string]*template.Template
  23. /*
  24. Map of nodes where the precedence might have changed because of parentheses
  25. */
  26. var bracketPrecedenceMap map[string]bool
  27. func init() {
  28. prettyPrinterMap = map[string]*template.Template{
  29. NodeSTRING: template.Must(template.New(NodeSTRING).Parse("{{.qval}}")),
  30. NodeNUMBER: template.Must(template.New(NodeNUMBER).Parse("{{.val}}")),
  31. // NodeIDENTIFIER - Special case (handled in code)
  32. // Constructed tokens
  33. // NodeSTATEMENTS - Special case (handled in code)
  34. // NodeFUNCCALL - Special case (handled in code)
  35. NodeCOMPACCESS + "_1": template.Must(template.New(NodeCOMPACCESS).Parse("[{{.c1}}]")),
  36. // TokenLIST - Special case (handled in code)
  37. // TokenMAP - Special case (handled in code)
  38. // TokenPARAMS - Special case (handled in code)
  39. NodeGUARD + "_1": template.Must(template.New(NodeGUARD).Parse("{{.c1}}")),
  40. // Condition operators
  41. NodeGEQ + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} >= {{.c2}}")),
  42. NodeLEQ + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} <= {{.c2}}")),
  43. NodeNEQ + "_2": template.Must(template.New(NodeNEQ).Parse("{{.c1}} != {{.c2}}")),
  44. NodeEQ + "_2": template.Must(template.New(NodeEQ).Parse("{{.c1}} == {{.c2}}")),
  45. NodeGT + "_2": template.Must(template.New(NodeGT).Parse("{{.c1}} > {{.c2}}")),
  46. NodeLT + "_2": template.Must(template.New(NodeLT).Parse("{{.c1}} < {{.c2}}")),
  47. // Separators
  48. NodeKVP + "_2": template.Must(template.New(NodeKVP).Parse("{{.c1}} : {{.c2}}")),
  49. NodePRESET + "_2": template.Must(template.New(NodePRESET).Parse("{{.c1}}={{.c2}}")),
  50. // Arithmetic operators
  51. NodePLUS + "_1": template.Must(template.New(NodePLUS).Parse("+{{.c1}}")),
  52. NodePLUS + "_2": template.Must(template.New(NodePLUS).Parse("{{.c1}} + {{.c2}}")),
  53. NodeMINUS + "_1": template.Must(template.New(NodeMINUS).Parse("-{{.c1}}")),
  54. NodeMINUS + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} - {{.c2}}")),
  55. NodeTIMES + "_2": template.Must(template.New(NodeTIMES).Parse("{{.c1}} * {{.c2}}")),
  56. NodeDIV + "_2": template.Must(template.New(NodeDIV).Parse("{{.c1}} / {{.c2}}")),
  57. NodeMODINT + "_2": template.Must(template.New(NodeMODINT).Parse("{{.c1}} % {{.c2}}")),
  58. NodeDIVINT + "_2": template.Must(template.New(NodeDIVINT).Parse("{{.c1}} // {{.c2}}")),
  59. // Assignment statement
  60. NodeASSIGN + "_2": template.Must(template.New(NodeASSIGN).Parse("{{.c1}} := {{.c2}}")),
  61. // Import statement
  62. NodeIMPORT + "_2": template.Must(template.New(NodeIMPORT).Parse("import {{.c1}} as {{.c2}}")),
  63. // Sink definition
  64. // NodeSINK - Special case (handled in code)
  65. NodeKINDMATCH + "_1": template.Must(template.New(NodeKINDMATCH).Parse("kindmatch {{.c1}}")),
  66. NodeSCOPEMATCH + "_1": template.Must(template.New(NodeSCOPEMATCH).Parse("scopematch {{.c1}}")),
  67. NodeSTATEMATCH + "_1": template.Must(template.New(NodeSTATEMATCH).Parse("statematch {{.c1}}")),
  68. NodePRIORITY + "_1": template.Must(template.New(NodePRIORITY).Parse("priority {{.c1}}")),
  69. NodeSUPPRESSES + "_1": template.Must(template.New(NodeSUPPRESSES).Parse("suppresses {{.c1}}")),
  70. // Function definition
  71. NodeFUNC + "_2": template.Must(template.New(NodeFUNC).Parse("func {{.c1}} {\n{{.c2}}}")),
  72. NodeFUNC + "_3": template.Must(template.New(NodeFUNC).Parse("func {{.c1}}{{.c2}} {\n{{.c3}}}")),
  73. NodeRETURN: template.Must(template.New(NodeRETURN).Parse("return")),
  74. NodeRETURN + "_1": template.Must(template.New(NodeRETURN).Parse("return {{.c1}}")),
  75. // Boolean operators
  76. NodeOR + "_2": template.Must(template.New(NodeOR).Parse("{{.c1}} or {{.c2}}")),
  77. NodeAND + "_2": template.Must(template.New(NodeAND).Parse("{{.c1}} and {{.c2}}")),
  78. NodeNOT + "_1": template.Must(template.New(NodeNOT).Parse("not {{.c1}}")),
  79. // Condition operators
  80. NodeLIKE + "_2": template.Must(template.New(NodeLIKE).Parse("{{.c1}} like {{.c2}}")),
  81. NodeIN + "_2": template.Must(template.New(NodeIN).Parse("{{.c1}} in {{.c2}}")),
  82. NodeHASPREFIX + "_2": template.Must(template.New(NodeHASPREFIX).Parse("{{.c1}} hasprefix {{.c2}}")),
  83. NodeHASSUFFIX + "_2": template.Must(template.New(NodeHASSUFFIX).Parse("{{.c1}} hassuffix {{.c2}}")),
  84. NodeNOTIN + "_2": template.Must(template.New(NodeNOTIN).Parse("{{.c1}} notin {{.c2}}")),
  85. // Constant terminals
  86. NodeTRUE: template.Must(template.New(NodeTRUE).Parse("true")),
  87. NodeFALSE: template.Must(template.New(NodeFALSE).Parse("false")),
  88. NodeNULL: template.Must(template.New(NodeNULL).Parse("null")),
  89. // Conditional statements
  90. // TokenIF - Special case (handled in code)
  91. // TokenELIF - Special case (handled in code)
  92. // TokenELSE - Special case (handled in code)
  93. // Loop statements
  94. NodeLOOP + "_2": template.Must(template.New(NodeLOOP).Parse("for {{.c1}} {\n{{.c2}}}\n")),
  95. NodeBREAK: template.Must(template.New(NodeBREAK).Parse("break")),
  96. NodeCONTINUE: template.Must(template.New(NodeCONTINUE).Parse("continue")),
  97. }
  98. bracketPrecedenceMap = map[string]bool{
  99. NodePLUS: true,
  100. NodeMINUS: true,
  101. NodeAND: true,
  102. NodeOR: true,
  103. }
  104. }
  105. /*
  106. PrettyPrint produces pretty printed code from a given AST.
  107. */
  108. func PrettyPrint(ast *ASTNode) (string, error) {
  109. var visit func(ast *ASTNode, level int) (string, error)
  110. ppMetaData := func(ast *ASTNode, ppString string) string {
  111. ret := ppString
  112. // Add meta data
  113. if len(ast.Meta) > 0 {
  114. for _, meta := range ast.Meta {
  115. if meta.Type() == MetaDataPreComment {
  116. ret = fmt.Sprintf("/*%v*/ %v", meta.Value(), ret)
  117. } else if meta.Type() == MetaDataPostComment {
  118. ret = fmt.Sprintf("%v #%v", ret, meta.Value())
  119. }
  120. }
  121. }
  122. return ret
  123. }
  124. visit = func(ast *ASTNode, level int) (string, error) {
  125. var buf bytes.Buffer
  126. var numChildren int
  127. if ast == nil {
  128. return "", fmt.Errorf("Nil pointer in AST at level: %v", level)
  129. }
  130. numChildren = len(ast.Children)
  131. tempKey := ast.Name
  132. tempParam := make(map[string]string)
  133. // First pretty print children
  134. if numChildren > 0 {
  135. for i, child := range ast.Children {
  136. res, err := visit(child, level+1)
  137. if err != nil {
  138. return "", err
  139. }
  140. if _, ok := bracketPrecedenceMap[child.Name]; ok && ast.binding > child.binding {
  141. // Put the expression in brackets iff (if and only if) the binding would
  142. // normally order things differently
  143. res = fmt.Sprintf("(%v)", res)
  144. }
  145. tempParam[fmt.Sprint("c", i+1)] = res
  146. }
  147. tempKey += fmt.Sprint("_", len(tempParam))
  148. }
  149. // Handle special cases - children in tempParam have been resolved
  150. if ast.Name == NodeSTATEMENTS {
  151. // For statements just concat all children
  152. for i := 0; i < numChildren; i++ {
  153. buf.WriteString(stringutil.GenerateRollingString(" ", level*4))
  154. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  155. buf.WriteString("\n")
  156. }
  157. return ppMetaData(ast, buf.String()), nil
  158. } else if ast.Name == NodeSINK {
  159. buf.WriteString("sink ")
  160. buf.WriteString(tempParam["c1"])
  161. buf.WriteString("\n")
  162. for i := 1; i < len(ast.Children)-1; i++ {
  163. buf.WriteString(" ")
  164. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  165. buf.WriteString("\n")
  166. }
  167. buf.WriteString("{\n")
  168. buf.WriteString(tempParam[fmt.Sprint("c", len(ast.Children))])
  169. buf.WriteString("}\n")
  170. return ppMetaData(ast, buf.String()), nil
  171. } else if ast.Name == NodeFUNCCALL {
  172. // For statements just concat all children
  173. for i := 0; i < numChildren; i++ {
  174. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  175. if i < numChildren-1 {
  176. buf.WriteString(", ")
  177. }
  178. }
  179. return ppMetaData(ast, buf.String()), nil
  180. } else if ast.Name == NodeIDENTIFIER {
  181. buf.WriteString(ast.Token.Val)
  182. for i := 0; i < numChildren; i++ {
  183. if ast.Children[i].Name == NodeIDENTIFIER {
  184. buf.WriteString(".")
  185. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  186. } else if ast.Children[i].Name == NodeFUNCCALL {
  187. buf.WriteString("(")
  188. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  189. buf.WriteString(")")
  190. } else if ast.Children[i].Name == NodeCOMPACCESS {
  191. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  192. }
  193. }
  194. return ppMetaData(ast, buf.String()), nil
  195. } else if ast.Name == NodeLIST {
  196. buf.WriteString("[")
  197. i := 1
  198. for ; i < numChildren; i++ {
  199. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  200. buf.WriteString(", ")
  201. }
  202. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  203. buf.WriteString("]")
  204. return ppMetaData(ast, buf.String()), nil
  205. } else if ast.Name == NodeMAP {
  206. buf.WriteString("{")
  207. i := 1
  208. for ; i < numChildren; i++ {
  209. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  210. buf.WriteString(", ")
  211. }
  212. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  213. buf.WriteString("}")
  214. return ppMetaData(ast, buf.String()), nil
  215. } else if ast.Name == NodePARAMS {
  216. buf.WriteString("(")
  217. i := 1
  218. for ; i < numChildren; i++ {
  219. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  220. buf.WriteString(", ")
  221. }
  222. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  223. buf.WriteString(")")
  224. return ppMetaData(ast, buf.String()), nil
  225. } else if ast.Name == NodeIF {
  226. writeGUARD := func(child int) {
  227. buf.WriteString(tempParam[fmt.Sprint("c", child)])
  228. buf.WriteString(" {\n")
  229. buf.WriteString(tempParam[fmt.Sprint("c", child+1)])
  230. buf.WriteString("}")
  231. }
  232. buf.WriteString("if ")
  233. writeGUARD(1)
  234. for i := 0; i < len(ast.Children); i += 2 {
  235. if i+2 == len(ast.Children) && ast.Children[i].Children[0].Name == NodeTRUE {
  236. buf.WriteString(" else {\n")
  237. buf.WriteString(tempParam[fmt.Sprint("c", i+2)])
  238. buf.WriteString("}")
  239. } else if i > 0 {
  240. buf.WriteString(" elif ")
  241. writeGUARD(i + 1)
  242. }
  243. }
  244. buf.WriteString("\n")
  245. return ppMetaData(ast, buf.String()), nil
  246. }
  247. if ast.Token != nil {
  248. // Adding node value to template parameters
  249. tempParam["val"] = ast.Token.Val
  250. tempParam["qval"] = strconv.Quote(ast.Token.Val)
  251. }
  252. // Retrieve the template
  253. temp, ok := prettyPrinterMap[tempKey]
  254. errorutil.AssertTrue(ok,
  255. fmt.Sprintf("Could not find template for %v (tempkey: %v)",
  256. ast.Name, tempKey))
  257. // Use the children as parameters for template
  258. errorutil.AssertOk(temp.Execute(&buf, tempParam))
  259. return ppMetaData(ast, buf.String()), nil
  260. }
  261. return visit(ast, 0)
  262. }