expression_manipulation.jl 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """
  2. Returns a new expression where every occurrence of expr_to_replace into expr
  3. has been replaced by new_expr
  4. """
  5. function substitute(expr :: StarpuExpr, expr_to_replace :: StarpuExpr, new_expr :: StarpuExpr)
  6. function func_to_apply(x :: StarpuExpr)
  7. if (x == expr_to_replace)
  8. return new_expr
  9. end
  10. return x
  11. end
  12. return apply(func_to_apply, expr)
  13. end
  14. """
  15. Returns an expression where "€" symbols in expr were replaced
  16. by the following expression list.
  17. Ex : replace_pattern((@parse € = €), (@parse x), (@parse 1 + 1))
  18. --> (StarpuExpr) "x = 1 + 1"
  19. """
  20. function replace_pattern(expr :: StarpuExpr, replace_€ :: StarpuExpr...)
  21. replace_index = 0
  22. function func_to_apply(x :: StarpuExpr)
  23. if x == @parse €
  24. replace_index += 1
  25. return replace_€[replace_index]
  26. end
  27. if isa(x, StarpuExprTypedVar) && x.name == :€
  28. replace_index += 1
  29. if isa(replace_€[replace_index], StarpuExprVar)
  30. return StarpuExprTypedVar(replace_€[replace_index].name, x.typ)
  31. end
  32. return StarpuExprTypedExpr(replace_€[replace_index], x.typ)
  33. end
  34. if isa(x, StarpuExprFunction) && x.func == :€
  35. replace_index += 1
  36. if !(isa(replace_€[replace_index], StarpuExprVar))
  37. error("Can only replace a function name by a variable")
  38. end
  39. return StarpuExprFunction(x.ret_type, replace_€[replace_index].name, x.args, x.body)
  40. end
  41. return x
  42. end
  43. return apply(func_to_apply, expr)
  44. end
  45. import Base.any
  46. """
  47. Returns true if one of the sub-expression x in expr
  48. is such as cond(x) is true, otherwise, it returns false.
  49. """
  50. function any(cond :: Function, expr :: StarpuExpr)
  51. err_to_catch = "Catch me, condition is true somewhere !"
  52. function func_to_apply(x :: StarpuExpr)
  53. if cond(x)
  54. error(err_to_catch) # dirty but osef
  55. end
  56. return x
  57. end
  58. try
  59. apply(func_to_apply, expr)
  60. catch err
  61. if (isa(err, ErrorException) && err.msg == err_to_catch)
  62. return true
  63. end
  64. throw(err)
  65. end
  66. return false
  67. end
  68. import Base.all
  69. """
  70. Returns true if every sub-expression x in expr
  71. is such as cond(x) is true, otherwise, it returns false.
  72. """
  73. function all(cond :: Function, expr :: StarpuExpr)
  74. return !any(!cond, expr)
  75. end