Evaluate string based on dictionary values

If you want to define local variables from a dictionary, you can do:

function parse_eval_dict(s::AbstractString, locals::Dict{Symbol})
    ex = Meta.parse(s)
    assignments = [:($sym = $val) for (sym,val) in locals]
    eval(:(let $(assignments...); $ex; end))
end

hence

julia> parse_eval_dict("x + y", Dict(:x => 30, :y => 47))
77

But if I were you I would re-think your whole approach. Rather than defining and parsing a brand new “pseudolanguage”, it would be vastly easier, more flexible, and faster to just let users write Julia code. If you want to provide a compact domain-specific syntax you can do it with macros.

Note that if you are worried about safety/security (i.e. if the user inputs aren’t trusted), you will need to filter the Meta.parse output to allow only a small set of allowed expressions.

3 Likes