prettyprinter.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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(NodeTRUE).Parse("{{.qval}}")),
  29. NodeNUMBER: template.Must(template.New(NodeTRUE).Parse("{{.val}}")),
  30. NodeIDENTIFIER: template.Must(template.New(NodeTRUE).Parse("{{.val}}")),
  31. // Constructed tokens
  32. // NodeSTATEMENTS - Special case (handled in code)
  33. /*
  34. NodeSTATEMENTS = "statements" // List of statements
  35. // Assignment statement
  36. NodeASSIGN = ":="
  37. */
  38. NodeASSIGN + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} := {{.c2}}")),
  39. // Arithmetic operators
  40. NodePLUS + "_1": template.Must(template.New(NodeMINUS).Parse("+{{.c1}}")),
  41. NodePLUS + "_2": template.Must(template.New(NodePLUS).Parse("{{.c1}} + {{.c2}}")),
  42. NodeMINUS + "_1": template.Must(template.New(NodeMINUS).Parse("-{{.c1}}")),
  43. NodeMINUS + "_2": template.Must(template.New(NodeMINUS).Parse("{{.c1}} - {{.c2}}")),
  44. NodeTIMES + "_2": template.Must(template.New(NodeTIMES).Parse("{{.c1}} * {{.c2}}")),
  45. NodeDIV + "_2": template.Must(template.New(NodeDIV).Parse("{{.c1}} / {{.c2}}")),
  46. NodeMODINT + "_2": template.Must(template.New(NodeMODINT).Parse("{{.c1}} % {{.c2}}")),
  47. NodeDIVINT + "_2": template.Must(template.New(NodeDIVINT).Parse("{{.c1}} // {{.c2}}")),
  48. // Boolean operators
  49. NodeOR + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} or {{.c2}}")),
  50. NodeAND + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} and {{.c2}}")),
  51. NodeNOT + "_1": template.Must(template.New(NodeNOT).Parse("not {{.c1}}")),
  52. // Condition operators
  53. NodeLIKE + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} like {{.c2}}")),
  54. NodeIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} in {{.c2}}")),
  55. NodeHASPREFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hasprefix {{.c2}}")),
  56. NodeHASSUFFIX + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} hassuffix {{.c2}}")),
  57. NodeNOTIN + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} notin {{.c2}}")),
  58. NodeGEQ + "_2": template.Must(template.New(NodeGEQ).Parse("{{.c1}} >= {{.c2}}")),
  59. NodeLEQ + "_2": template.Must(template.New(NodeLEQ).Parse("{{.c1}} <= {{.c2}}")),
  60. NodeNEQ + "_2": template.Must(template.New(NodeNEQ).Parse("{{.c1}} != {{.c2}}")),
  61. NodeEQ + "_2": template.Must(template.New(NodeEQ).Parse("{{.c1}} == {{.c2}}")),
  62. NodeGT + "_2": template.Must(template.New(NodeGT).Parse("{{.c1}} > {{.c2}}")),
  63. NodeLT + "_2": template.Must(template.New(NodeLT).Parse("{{.c1}} < {{.c2}}")),
  64. // Constants
  65. NodeTRUE: template.Must(template.New(NodeTRUE).Parse("true")),
  66. NodeFALSE: template.Must(template.New(NodeFALSE).Parse("false")),
  67. NodeNULL: template.Must(template.New(NodeNULL).Parse("null")),
  68. }
  69. bracketPrecedenceMap = map[string]bool{
  70. NodePLUS: true,
  71. NodeMINUS: true,
  72. NodeAND: true,
  73. NodeOR: true,
  74. }
  75. }
  76. /*
  77. PrettyPrint produces pretty printed code from a given AST.
  78. */
  79. func PrettyPrint(ast *ASTNode) (string, error) {
  80. var visit func(ast *ASTNode, level int) (string, error)
  81. visit = func(ast *ASTNode, level int) (string, error) {
  82. var buf bytes.Buffer
  83. var numChildren = len(ast.Children)
  84. tempKey := ast.Name
  85. tempParam := make(map[string]string)
  86. // First pretty print children
  87. if numChildren > 0 {
  88. for i, child := range ast.Children {
  89. res, err := visit(child, level+1)
  90. if err != nil {
  91. return "", err
  92. }
  93. if _, ok := bracketPrecedenceMap[child.Name]; ok && ast.binding > child.binding {
  94. // Put the expression in brackets iff (if and only if) the binding would
  95. // normally order things differently
  96. res = fmt.Sprintf("(%v)", res)
  97. }
  98. tempParam[fmt.Sprint("c", i+1)] = res
  99. }
  100. tempKey += fmt.Sprint("_", len(tempParam))
  101. }
  102. // Handle special cases requiring children
  103. if ast.Name == NodeSTATEMENTS {
  104. // For statements just concat all children
  105. for i := 0; i < numChildren; i++ {
  106. buf.WriteString(stringutil.GenerateRollingString(" ", level*4))
  107. buf.WriteString(tempParam[fmt.Sprint("c", i+1)])
  108. buf.WriteString("\n")
  109. }
  110. return buf.String(), nil
  111. }
  112. if ast.Token != nil {
  113. // Adding node value to template parameters
  114. tempParam["val"] = ast.Token.Val
  115. tempParam["qval"] = strconv.Quote(ast.Token.Val)
  116. }
  117. // Retrieve the template
  118. temp, ok := prettyPrinterMap[tempKey]
  119. if !ok {
  120. return "", fmt.Errorf("Could not find template for %v (tempkey: %v)",
  121. ast.Name, tempKey)
  122. }
  123. // Use the children as parameters for template
  124. errorutil.AssertOk(temp.Execute(&buf, tempParam))
  125. ret := buf.String()
  126. // Add meta data
  127. if len(ast.Meta) > 0 {
  128. for _, meta := range ast.Meta {
  129. if meta.Type() == MetaDataPreComment {
  130. ret = fmt.Sprintf("/*%v*/ %v", meta.Value(), ret)
  131. } else if meta.Type() == MetaDataPostComment {
  132. ret = fmt.Sprintf("%v #%v", ret, meta.Value())
  133. }
  134. }
  135. }
  136. return ret, nil
  137. }
  138. return visit(ast, 0)
  139. }