prettyprinter.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. "bufio"
  13. "bytes"
  14. "fmt"
  15. "strconv"
  16. "strings"
  17. "text/template"
  18. "devt.de/krotik/common/errorutil"
  19. "devt.de/krotik/common/stringutil"
  20. )
  21. /*
  22. IndentationLevel is the level of indentation which the pretty printer should use
  23. */
  24. const IndentationLevel = 4
  25. /*
  26. Map of AST nodes corresponding to lexer tokens
  27. */
  28. var prettyPrinterMap map[string]*template.Template
  29. /*
  30. Map of nodes where the precedence might have changed because of parentheses
  31. */
  32. var bracketPrecedenceMap map[string]bool
  33. func init() {
  34. prettyPrinterMap = map[string]*template.Template{
  35. NodeSTRING: template.Must(template.New(NodeSTRING).Parse("{{.qval}}")),
  36. NodeNUMBER: template.Must(template.New(NodeNUMBER).Parse("{{.val}}")),
  37. // NodeIDENTIFIER - Special case (handled in code)
  38. // Constructed tokens
  39. // NodeSTATEMENTS - Special case (handled in code)
  40. // NodeFUNCCALL - Special case (handled in code)
  41. NodeCOMPACCESS + "_1": template.Must(template.New(NodeCOMPACCESS).Parse("[{{.c1}}]")),
  42. // TokenLIST - Special case (handled in code)
  43. // TokenMAP - Special case (handled in code)
  44. // TokenPARAMS - Special case (handled in code)
  45. NodeGUARD + "_1": template.Must(template.New(NodeGUARD).Parse("{{.c1}}")),
  46. // Condition operators
  47. NodeGEQ + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} >= {{.c2}}")),
  48. NodeLEQ + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} <= {{.c2}}")),
  49. NodeNEQ + "_2": template.Must(template.New(NodeNEQ).Parse("{{.c1}} != {{.c2}}")),
  50. NodeEQ + "_2": template.Must(template.New(NodeEQ).Parse("{{.c1}} == {{.c2}}")),
  51. NodeGT + "_2": template.Must(template.New(NodeGT).Parse("{{.c1}} > {{.c2}}")),
  52. NodeLT + "_2": template.Must(template.New(NodeLT).Parse("{{.c1}} < {{.c2}}")),
  53. // Separators
  54. NodeKVP + "_2": template.Must(template.New(NodeKVP).Parse("{{.c1}} : {{.c2}}")),
  55. NodePRESET + "_2": template.Must(template.New(NodePRESET).Parse("{{.c1}}={{.c2}}")),
  56. // Arithmetic operators
  57. NodePLUS + "_1": template.Must(template.New(NodePLUS).Parse("+{{.c1}}")),
  58. NodePLUS + "_2": template.Must(template.New(NodePLUS).Parse("{{.c1}} + {{.c2}}")),
  59. NodeMINUS + "_1": template.Must(template.New(NodeMINUS).Parse("-{{.c1}}")),
  60. NodeMINUS + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} - {{.c2}}")),
  61. NodeTIMES + "_2": template.Must(template.New(NodeTIMES).Parse("{{.c1}} * {{.c2}}")),
  62. NodeDIV + "_2": template.Must(template.New(NodeDIV).Parse("{{.c1}} / {{.c2}}")),
  63. NodeMODINT + "_2": template.Must(template.New(NodeMODINT).Parse("{{.c1}} % {{.c2}}")),
  64. NodeDIVINT + "_2": template.Must(template.New(NodeDIVINT).Parse("{{.c1}} // {{.c2}}")),
  65. // Assignment statement
  66. NodeASSIGN + "_2": template.Must(template.New(NodeASSIGN).Parse("{{.c1}} := {{.c2}}")),
  67. NodeLET + "_1": template.Must(template.New(NodeASSIGN).Parse("let {{.c1}}")),
  68. // Import statement
  69. NodeIMPORT + "_2": template.Must(template.New(NodeIMPORT).Parse("import {{.c1}} as {{.c2}}")),
  70. NodeAS + "_1": template.Must(template.New(NodeRETURN).Parse("as {{.c1}}")),
  71. // Sink definition
  72. // NodeSINK - Special case (handled in code)
  73. NodeKINDMATCH + "_1": template.Must(template.New(NodeKINDMATCH).Parse("kindmatch {{.c1}}")),
  74. NodeSCOPEMATCH + "_1": template.Must(template.New(NodeSCOPEMATCH).Parse("scopematch {{.c1}}")),
  75. NodeSTATEMATCH + "_1": template.Must(template.New(NodeSTATEMATCH).Parse("statematch {{.c1}}")),
  76. NodePRIORITY + "_1": template.Must(template.New(NodePRIORITY).Parse("priority {{.c1}}")),
  77. NodeSUPPRESSES + "_1": template.Must(template.New(NodeSUPPRESSES).Parse("suppresses {{.c1}}")),
  78. // Function definition
  79. NodeFUNC + "_2": template.Must(template.New(NodeFUNC).Parse("func {{.c1}} {\n{{.c2}}}")),
  80. NodeFUNC + "_3": template.Must(template.New(NodeFUNC).Parse("func {{.c1}}{{.c2}} {\n{{.c3}}}")),
  81. NodeRETURN: template.Must(template.New(NodeRETURN).Parse("return")),
  82. NodeRETURN + "_1": template.Must(template.New(NodeRETURN).Parse("return {{.c1}}")),
  83. // Boolean operators
  84. NodeOR + "_2": template.Must(template.New(NodeOR).Parse("{{.c1}} or {{.c2}}")),
  85. NodeAND + "_2": template.Must(template.New(NodeAND).Parse("{{.c1}} and {{.c2}}")),
  86. NodeNOT + "_1": template.Must(template.New(NodeNOT).Parse("not {{.c1}}")),
  87. // Condition operators
  88. NodeLIKE + "_2": template.Must(template.New(NodeLIKE).Parse("{{.c1}} like {{.c2}}")),
  89. NodeIN + "_2": template.Must(template.New(NodeIN).Parse("{{.c1}} in {{.c2}}")),
  90. NodeHASPREFIX + "_2": template.Must(template.New(NodeHASPREFIX).Parse("{{.c1}} hasprefix {{.c2}}")),
  91. NodeHASSUFFIX + "_2": template.Must(template.New(NodeHASSUFFIX).Parse("{{.c1}} hassuffix {{.c2}}")),
  92. NodeNOTIN + "_2": template.Must(template.New(NodeNOTIN).Parse("{{.c1}} notin {{.c2}}")),
  93. // Constant terminals
  94. NodeTRUE: template.Must(template.New(NodeTRUE).Parse("true")),
  95. NodeFALSE: template.Must(template.New(NodeFALSE).Parse("false")),
  96. NodeNULL: template.Must(template.New(NodeNULL).Parse("null")),
  97. // Conditional statements
  98. // TokenIF - Special case (handled in code)
  99. // TokenELIF - Special case (handled in code)
  100. // TokenELSE - Special case (handled in code)
  101. // Loop statement
  102. NodeLOOP + "_2": template.Must(template.New(NodeLOOP).Parse("for {{.c1}} {\n{{.c2}}}")),
  103. NodeBREAK: template.Must(template.New(NodeBREAK).Parse("break")),
  104. NodeCONTINUE: template.Must(template.New(NodeCONTINUE).Parse("continue")),
  105. // Try statement
  106. // TokenTRY - Special case (handled in code)
  107. // TokenEXCEPT - Special case (handled in code)
  108. NodeFINALLY + "_1": template.Must(template.New(NodeFINALLY).Parse(" finally {\n{{.c1}}}\n")),
  109. // Mutex block
  110. NodeMUTEX + "_2": template.Must(template.New(NodeLOOP).Parse("mutex {{.c1}} {\n{{.c2}}}\n")),
  111. }
  112. bracketPrecedenceMap = map[string]bool{
  113. NodePLUS: true,
  114. NodeMINUS: true,
  115. NodeAND: true,
  116. NodeOR: true,
  117. }
  118. }
  119. /*
  120. PrettyPrint produces pretty printed code from a given AST.
  121. */
  122. func PrettyPrint(ast *ASTNode) (string, error) {
  123. var visit func(ast *ASTNode, path []*ASTNode) (string, error)
  124. visit = func(ast *ASTNode, path []*ASTNode) (string, error) {
  125. var buf bytes.Buffer
  126. if ast == nil {
  127. return "", fmt.Errorf("Nil pointer in AST")
  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, append(path, child))
  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. if res, ok := ppSpecialDefs(ast, path, tempParam, &buf); ok {
  149. return res, nil
  150. } else if res, ok := ppSpecialBlocks(ast, path, tempParam, &buf); ok {
  151. return res, nil
  152. } else if res, ok := ppContainerBlocks(ast, path, tempParam, &buf); ok {
  153. return res, nil
  154. } else if res, ok := ppSpecialStatements(ast, path, tempParam, &buf); ok {
  155. return res, nil
  156. }
  157. if ast.Token != nil {
  158. // Adding node value to template parameters
  159. tempParam["val"] = ast.Token.Val
  160. tempParam["qval"] = strconv.Quote(ast.Token.Val)
  161. }
  162. // Retrieve the template
  163. temp, ok := prettyPrinterMap[tempKey]
  164. errorutil.AssertTrue(ok,
  165. fmt.Sprintf("Could not find template for %v (tempkey: %v)",
  166. ast.Name, tempKey))
  167. // Use the children as parameters for template
  168. errorutil.AssertOk(temp.Execute(&buf, tempParam))
  169. return ppPostProcessing(ast, path, buf.String()), nil
  170. }
  171. res, err := visit(ast, []*ASTNode{ast})
  172. return strings.TrimSpace(res), err
  173. }
  174. /*
  175. ppPostProcessing applies post processing rules.
  176. */
  177. func ppPostProcessing(ast *ASTNode, path []*ASTNode, ppString string) string {
  178. ret := ppString
  179. // Add meta data
  180. if len(ast.Meta) > 0 {
  181. for _, meta := range ast.Meta {
  182. metaValue := meta.Value()
  183. if meta.Type() == MetaDataPreComment {
  184. var buf bytes.Buffer
  185. scanner := bufio.NewScanner(strings.NewReader(metaValue))
  186. for scanner.Scan() {
  187. buf.WriteString(fmt.Sprintf(" %v\n", strings.TrimSpace(scanner.Text())))
  188. }
  189. buf.Truncate(buf.Len() - 1) // Remove the last newline
  190. if strings.Index(buf.String(), "\n") == -1 {
  191. buf.WriteString(" ")
  192. }
  193. ret = fmt.Sprintf("/*%v*/\n%v", buf.String(), ret)
  194. } else if meta.Type() == MetaDataPostComment {
  195. metaValue = strings.TrimSpace(strings.ReplaceAll(metaValue, "\n", ""))
  196. ret = fmt.Sprintf("%v # %v", ret, metaValue)
  197. }
  198. }
  199. }
  200. // Apply indentation
  201. if len(path) > 1 {
  202. if stringutil.IndexOf(ast.Name, []string{
  203. NodeSTATEMENTS,
  204. NodeMAP,
  205. NodeLIST,
  206. NodeKINDMATCH,
  207. NodeSTATEMATCH,
  208. NodeSCOPEMATCH,
  209. NodePRIORITY,
  210. NodeSUPPRESSES,
  211. }) != -1 {
  212. parent := path[len(path)-2]
  213. indentSpaces := stringutil.GenerateRollingString(" ", IndentationLevel)
  214. ret = strings.ReplaceAll(ret, "\n", "\n"+indentSpaces)
  215. // Add initial indent only if we are inside a block statement
  216. if stringutil.IndexOf(parent.Name, []string{
  217. NodeASSIGN,
  218. NodePRESET,
  219. NodeKVP,
  220. NodeLIST,
  221. NodeFUNCCALL,
  222. NodeKINDMATCH,
  223. NodeSTATEMATCH,
  224. NodeSCOPEMATCH,
  225. NodePRIORITY,
  226. NodeSUPPRESSES,
  227. }) == -1 {
  228. ret = fmt.Sprintf("%v%v", indentSpaces, ret)
  229. }
  230. // Remove indentation from last line unless we have a special case
  231. if stringutil.IndexOf(parent.Name, []string{
  232. NodeSINK,
  233. }) == -1 || ast.Name == NodeSTATEMENTS {
  234. if idx := strings.LastIndex(ret, "\n"); idx != -1 {
  235. ret = ret[:idx+1] + ret[idx+IndentationLevel+1:]
  236. }
  237. }
  238. }
  239. }
  240. return ret
  241. }
  242. /*
  243. ppSpecialDefs pretty prints special cases.
  244. */
  245. func ppSpecialDefs(ast *ASTNode, path []*ASTNode, tempParam map[string]string, buf *bytes.Buffer) (string, bool) {
  246. numChildren := len(ast.Children)
  247. if ast.Name == NodeFUNCCALL {
  248. for i := 0; i < numChildren; i++ {
  249. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  250. if i < numChildren-1 {
  251. buf.WriteString(", ")
  252. }
  253. }
  254. return ppPostProcessing(ast, path, buf.String()), true
  255. } else if ast.Name == NodeSINK {
  256. buf.WriteString("sink ")
  257. buf.WriteString(tempParam["c1"])
  258. buf.WriteString("\n")
  259. for i := 1; i < len(ast.Children)-1; i++ {
  260. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  261. buf.WriteString("\n")
  262. }
  263. buf.WriteString("{\n")
  264. buf.WriteString(tempParam[fmt.Sprint("c", len(ast.Children))])
  265. buf.WriteString("}\n")
  266. return ppPostProcessing(ast, path, buf.String()), true
  267. }
  268. return "", false
  269. }
  270. /*
  271. ppContainerBlocks pretty prints container structures.
  272. */
  273. func ppContainerBlocks(ast *ASTNode, path []*ASTNode, tempParam map[string]string, buf *bytes.Buffer) (string, bool) {
  274. numChildren := len(ast.Children)
  275. if ast.Name == NodeLIST {
  276. multilineThreshold := 4
  277. buf.WriteString("[")
  278. if numChildren > multilineThreshold {
  279. buf.WriteString("\n")
  280. }
  281. for i := 0; i < numChildren; i++ {
  282. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  283. if i < numChildren-1 {
  284. if numChildren > multilineThreshold {
  285. buf.WriteString(",")
  286. } else {
  287. buf.WriteString(", ")
  288. }
  289. }
  290. if numChildren > multilineThreshold {
  291. buf.WriteString("\n")
  292. }
  293. }
  294. buf.WriteString("]")
  295. return ppPostProcessing(ast, path, buf.String()), true
  296. } else if ast.Name == NodeMAP {
  297. multilineThreshold := 2
  298. buf.WriteString("{")
  299. if numChildren > multilineThreshold {
  300. buf.WriteString("\n")
  301. }
  302. for i := 0; i < numChildren; i++ {
  303. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  304. if i < numChildren-1 {
  305. if numChildren > multilineThreshold {
  306. buf.WriteString(",")
  307. } else {
  308. buf.WriteString(", ")
  309. }
  310. }
  311. if numChildren > multilineThreshold {
  312. buf.WriteString("\n")
  313. }
  314. }
  315. buf.WriteString("}")
  316. return ppPostProcessing(ast, path, buf.String()), true
  317. }
  318. return "", false
  319. }
  320. /*
  321. ppSpecialBlocks pretty prints special cases.
  322. */
  323. func ppSpecialBlocks(ast *ASTNode, path []*ASTNode, tempParam map[string]string, buf *bytes.Buffer) (string, bool) {
  324. numChildren := len(ast.Children)
  325. // Handle special cases - children in tempParam have been resolved
  326. if ast.Name == NodeSTATEMENTS {
  327. // For statements just concat all children
  328. for i := 0; i < numChildren; i++ {
  329. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  330. buf.WriteString("\n")
  331. }
  332. return ppPostProcessing(ast, path, buf.String()), true
  333. } else if ast.Name == NodeTRY {
  334. buf.WriteString("try {\n")
  335. buf.WriteString(tempParam[fmt.Sprint("c1")])
  336. buf.WriteString("}")
  337. for i := 1; i < len(ast.Children); i++ {
  338. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  339. }
  340. return ppPostProcessing(ast, path, buf.String()), true
  341. } else if ast.Name == NodeEXCEPT {
  342. buf.WriteString(" except ")
  343. for i := 0; i < len(ast.Children)-1; i++ {
  344. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  345. if ast.Children[i+1].Name != NodeAS && i < len(ast.Children)-2 {
  346. buf.WriteString(",")
  347. }
  348. buf.WriteString(" ")
  349. }
  350. buf.WriteString("{\n")
  351. buf.WriteString(tempParam[fmt.Sprint("c", len(ast.Children))])
  352. buf.WriteString("}")
  353. return ppPostProcessing(ast, path, buf.String()), true
  354. }
  355. return "", false
  356. }
  357. /*
  358. ppSpecialStatements pretty prints special cases.
  359. */
  360. func ppSpecialStatements(ast *ASTNode, path []*ASTNode, tempParam map[string]string, buf *bytes.Buffer) (string, bool) {
  361. numChildren := len(ast.Children)
  362. if ast.Name == NodeIDENTIFIER {
  363. buf.WriteString(ast.Token.Val)
  364. for i := 0; i < numChildren; i++ {
  365. if ast.Children[i].Name == NodeIDENTIFIER {
  366. buf.WriteString(".")
  367. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  368. } else if ast.Children[i].Name == NodeFUNCCALL {
  369. buf.WriteString("(")
  370. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  371. buf.WriteString(")")
  372. } else if ast.Children[i].Name == NodeCOMPACCESS {
  373. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  374. }
  375. }
  376. return ppPostProcessing(ast, path, buf.String()), true
  377. } else if ast.Name == NodePARAMS {
  378. buf.WriteString("(")
  379. i := 1
  380. for ; i < numChildren; i++ {
  381. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  382. buf.WriteString(", ")
  383. }
  384. buf.WriteString(tempParam[fmt.Sprint("c", i)])
  385. buf.WriteString(")")
  386. return ppPostProcessing(ast, path, buf.String()), true
  387. } else if ast.Name == NodeIF {
  388. writeGUARD := func(child int) {
  389. buf.WriteString(tempParam[fmt.Sprint("c", child)])
  390. buf.WriteString(" {\n")
  391. buf.WriteString(tempParam[fmt.Sprint("c", child+1)])
  392. buf.WriteString("}")
  393. }
  394. buf.WriteString("if ")
  395. writeGUARD(1)
  396. for i := 0; i < len(ast.Children); i += 2 {
  397. if i+2 == len(ast.Children) && ast.Children[i].Children[0].Name == NodeTRUE {
  398. buf.WriteString(" else {\n")
  399. buf.WriteString(tempParam[fmt.Sprint("c", i+2)])
  400. buf.WriteString("}")
  401. } else if i > 0 {
  402. buf.WriteString(" elif ")
  403. writeGUARD(i + 1)
  404. }
  405. }
  406. return ppPostProcessing(ast, path, buf.String()), true
  407. }
  408. return "", false
  409. }