项目作者: schlichtanders

项目描述 :
Parse common Expr patterns. Speed up the process of defining stable macros.
高级语言: Julia
项目地址: git://github.com/schlichtanders/ExprParsers.jl.git
创建时间: 2020-04-24T18:28:31Z
项目社区:https://github.com/schlichtanders/ExprParsers.jl

开源协议:MIT License

下载


ExprParsers.jl

Stable
Dev
Build Status
Coverage

ExprParsers is a library made to simplify development of elaborate macros.

What ExprParsers offers is a set of curated parsers for common Expr patterns. For example

  1. parse_expr(ExprParsers.Function(), :(f(a) = 2a))

will give you an ExprParsers.Function_Parsed object where you can inspect and change name, args, kwargs, curlies, wheres, and the function body. It just works and you don’t have to bother any longer that you can also write the same function as function f(a); 2a; end - the parser handles this for you.

In macros you often not only want to inspect the given Expr in efficient and stable manners, but also may want to change parts and return a respectively adapted Expr. For this purpose, all Parsed objects are mutable and can be converted back to Expr by using the to_expr(parsed_value) method.

We guarantee that parse_expr and to_expr are working nicely together, i.e. the following always holds for arbitrary expressions and parsers

  1. julia> using ExprParsers
  2. julia> # comes with a shorthand EP for ExprParsers
  3. julia> parser = EP.Function()
  4. EP.Function(
  5. name = ExprParsers.Isa{Any}()
  6. curlies = ExprParsers.Isa{Any}()
  7. args = ExprParsers.Isa{Any}()
  8. kwargs = ExprParsers.Isa{Any}()
  9. wheres = ExprParsers.Isa{Any}()
  10. body = ExprParsers.Isa{Any}()
  11. )
  12. julia> expr = :(f(a) = 2a)
  13. :(f(a) = begin
  14. #= REPL[8]:1 =#
  15. 2a
  16. end)
  17. julia> parsed = parse_expr(parser, expr)
  18. EP.Function_Parsed(
  19. name = :f
  20. curlies = Any[]
  21. args = Any[:a]
  22. kwargs = Any[]
  23. wheres = Any[]
  24. body = quote
  25. #= REPL[8]:1 =#
  26. 2a
  27. end
  28. )
  29. julia> # applying the parser "twice" returns always the same parsed result
  30. julia> parse_expr(parser, to_expr(parsed)) == parsed
  31. true

Note that ExprParsers exports a constant EP which is an alias for the package ExprParsers itself. This comes in very handy when you use the custom parsers a lot.

Checkout the test/ directory for seeing more examples, especially test/expr_parsers_with_parsed.jl where for each common Expr pattern a parser is put into action.

Installation

install by

  1. using Pkg
  2. pkg"add ExprParsers"