prettyprinter.go 16 KB

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