Erlang trying to evaluate a string
Asked Answered
C

1

1

I'm trying to dynamically evalutate Erlang terms

Start up Erlang

basho-catah% erl
Erlang R16B03 (erts-5.10.4) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V5.10.4  (abort with ^G)

Create a term

1> {a,[b,c,d]}.
{a,[b,c,d]}

Try to scan in the same term

2> {ok, Tokens, _ } = erl_scan:string("{a,[b,c,d]}").
{ok,[{'{',1},
     {atom,1,a},
     {',',1},
     {'[',1},
     {atom,1,b},
     {',',1},
     {atom,1,c},
     {',',1},
     {atom,1,d},
     {']',1},
     {'}',1}],
    1}


3> Tokens.
[{'{',1},
 {atom,1,a},
 {',',1},
 {'[',1},
 {atom,1,b},
 {',',1},
 {atom,1,c},
 {',',1},
 {atom,1,d},
 {']',1},
 {'}',1}]

But it can't parse that tokenized string.

4> Foo = erl_parse:parse(Tokens).
{error,{1,erl_parse,["syntax error before: ","'{'"]}}

Any ideas what I'm doing wrong?

Condolence answered 22/5, 2014 at 15:28 Comment(0)
R
5

You're using the wrong function, and there's also a caveat you haven't encountered.

First, the function you should be using is erl_parse:parse_term/1. I'm not actually able to find documentation for erl_parse:parse/1, so I suspect it's deprecated (and most likely used for parsing abstract-syntax trees, not tokens).

Second, for erl_parse:parse_term/1 to work, you must include the terminating dot character in your term. erl_scan:string/1 will happily convert whatever you give it into tokens, but without the terminator erl_parse:parse_term/1 expects to receive more.

So, try the following in a shell:

{ok, Tokens, _} = erl_scan:string("{a,[b,c,d]}.").
erl_parse:parse_term(Tokens).
Rascal answered 22/5, 2014 at 18:5 Comment(3)
erl_parse:parse/1 is the generic parse function genereated by yecc (used to build the parser) which parses exactly what the grammar dictates. Normally you call some defined wrapper functions like erl_parse:parse_term/1.Layamon
If only Erlang were statically typed ;-)Condolence
Thank your favourite deity it isn't, it would make code loading very difficult and "static". I belong to the Church of Short Variable Names.Layamon

© 2022 - 2024 — McMap. All rights reserved.