How to turn a string with a valid Erlang expression into an abstract syntax tree (AST)?

后端 未结 3 1371
醉话见心
醉话见心 2020-12-30 09:38

I would like to convert a string containing a valid Erlang expression to its abstract syntax tree representation, without any success so far.

Below is an example of

3条回答
  •  清酒与你
    2020-12-30 10:28

    In your EDIT example:

    String = "[1,2,3].",
    {ok, Ts, _} = erl_scan:string(String),
    {ok, ListAST} = erl_parse:parse_exprs(Ts),
    

    the ListAST is actually a list of AST:s (because parse_exprs, as the name indicates, parses multiple expressions (each terminated by a period). Since your string contained a single expression, you got a list of one element. All you need to do is match that out:

    {ok, [ListAST]} = erl_parse:parse_exprs(Ts),
    

    so it has nothing to do with erl_syntax (which accepts all erl_parse trees); it's just that you had an extra list wrapper around the ListAST, which caused the compiler to puke.

提交回复
热议问题