Skip to content

Instantly share code, notes, and snippets.

@habibutsu
Last active August 10, 2019 16:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save habibutsu/bc6791d3d81b6ea54e1a to your computer and use it in GitHub Desktop.
Save habibutsu/bc6791d3d81b6ea54e1a to your computer and use it in GitHub Desktop.
Elixir to Erlang
% erl -pa /usr/share/elixir/1.0.5/lib/*/ebin -elixir ansi_enabled true
application:ensure_all_started(elixir),
rr("/usr/share/elixir/1.0.5/lib/elixir/src/elixir.hrl").
% A simplified version of 'Elixir.Code':eval_string/2
% https://github.com/elixir-lang/elixir/blob/v1.2.0/lib/elixir/lib/code.ex#L159
EvalString = fun(String, Binding) ->
% Converts a given string (char list) into quote expression
% https://github.com/elixir-lang/elixir/blob/v1.2.0/lib/elixir/src/elixir.erl#L252
Tree = elixir:'string_to_quoted!'(String, 1, <<"nofile">>, Binding),
io:format("%% Elixir AST: ~n~n~p~n~n", [Tree]),
Env = elixir:env_for_eval([]),
Scope = elixir_env:env_to_scope(Env),
{ParsedBinding, ParsedScope} = elixir_scope:load_binding(Binding, Scope),
ParsedEnv = Env#{vars := [K || {K,_} <- ParsedScope#elixir_scope.vars]},
% Translate Elixir quoted expressions to Erlang Abstract Format.
% https://github.com/elixir-lang/elixir/blob/v1.2.0/lib/elixir/src/elixir.erl#L197
{Erl, _NewEnv, _NewScope} = elixir:quoted_to_erl(Tree, ParsedEnv, ParsedScope),
io:format("%% Erlang Abstract Format: ~n~n~p~n~n", [Erl]),
io:format("%% Erlang: ~n~n~s~n~n", [lists:flatten(erl_pp:expr(Erl))]),
% Running code
% https://github.com/elixir-lang/elixir/blob/v1.2.0/lib/elixir/src/elixir.erl#L215
erl_eval:expr(Erl, ParsedBinding, none, none, none)
end.
% Examples:
EvalString("IO.puts(\"Value of 'my_var' = #{my_var}\")", [{my_var, 100500}]).
EvalString("my_var+1", [{my_var, 100500}]).
EvalString("map.a", [{map, #{a=>1}}]).
EvalString("list |> Enum.reverse |> List.duplicate(2) |> List.flatten", [{list, [1, 2, 3]}]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment