-module(consult).

-export([file/1]).

% A reworking of file:consult/1 that handles funs (and coincidentally
% full expressions) in the source file.  This could be extended to
% export bindings to the source source, for even greater flexibility.

file(FileName) ->
  {ok, IoDevice} = file:open(FileName, [read]),
  {ok, Exprs} = get_exprs(IoDevice, []),
  file:close(IoDevice),
  eval(Exprs, []).

get_exprs(IoDevice, Acc) ->
  case io:parse_erl_exprs(IoDevice, '') of
    {ok, Exprs, _} ->
      get_exprs(IoDevice, [Exprs | Acc]);
    {eof, _} ->
      {ok, Acc};
    Else ->
      Else
  end.

eval([], Acc) ->
  Acc;
eval([Head | Tail], Acc) ->
  {value, Value, _} = erl_eval:exprs(Head, erl_eval:new_bindings()),
  eval(Tail, [Value | Acc]).
