Advertisement
jchero

final 7

Apr 24th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. package rewrite
  2. import "fmt"
  3. import (
  4. "bytes"
  5. "go/ast"
  6. "go/format"
  7. "go/parser"
  8. "go/token"
  9. "strings"
  10. "hw1/expr"
  11. "hw1/simplify"
  12. "strconv" // This package may be helpful...
  13. )
  14.  
  15. // rewriteCalls should modify the passed AST
  16. func rewriteCalls(node ast.Node) {
  17. //TODO Write the rewriteCalls function
  18. fset := token.NewFileSet()
  19. ast.Inspect(node, func (node ast.Node) bool {
  20.  
  21. switch v := node.(type) {
  22.  
  23. case *ast.CallExpr:
  24.  
  25. switch k := v.Fun.(type) {
  26. case *ast.SelectorExpr:
  27.  
  28. if strings.Contains(k.Sel.Name, "ParseAndEval") {
  29. switch m := k.X.(type) {
  30. case *ast.Ident:
  31. m = m
  32.  
  33. switch n := v.Args[0].(type) {
  34. case *ast.BasicLit:
  35. n = n
  36.  
  37. tp, ok := expr.Parse(n.Value[1 : len(n.Value) - 1])
  38.  
  39. ok = ok
  40. tp = tp
  41.  
  42. lol := simplify.Simplify(tp, expr.Env{})
  43. lol = lol
  44.  
  45.  
  46. haha := expr.Format(lol)
  47.  
  48. haha = strconv.Quote(haha)
  49.  
  50. n.Value = haha
  51.  
  52. // n.Value = haha
  53.  
  54. }
  55.  
  56. }
  57. }
  58.  
  59. }
  60.  
  61. }
  62. // If we return true, we keep recursing under this AST node.
  63. // If we return false, we won't visit anything under this AST node.
  64. return true
  65. })
  66. var buf bytes.Buffer
  67. format.Node(&buf, fset, node)
  68. fmt.Println(buf.String())
  69. // fmt.Printf("okkk\n\n")
  70. panic("TODO: implement this!")
  71. }
  72.  
  73. func SimplifyParseAndEval(src string) string {
  74. fset := token.NewFileSet()
  75. f, err := parser.ParseFile(fset, "src.go", src, 0)
  76. if err != nil {
  77. panic(err)
  78. }
  79.  
  80. rewriteCalls(f)
  81.  
  82. var buf bytes.Buffer
  83. format.Node(&buf, fset, f)
  84. return buf.String()
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement