yolo007wizard

yolo007wizard

ChatGPT generated code for eval_string alternative

Was talking with ChatGPT, is the following code a valid/good replacement for Code.eval_string?

def create_function(name, args, code) do
  ast = Macro.escape(code, [:strict])
  code = Macro.to_string(ast)
  {name, Code.string_to_quoted(code)}
end

This code would run in a template engine of sorts to load function schema/definitions from a json file.

defmodule Engine do
  def start(schema_files) do
    functions =
      schema_files
      |> Enum.map(&parse_schema_file/1)
      |> Enum.map(&create_function/1)
      |> Map.new

    # Store the functions in the `functions` map
    Process.put(:functions, functions)
  end
end

ChatGPT explanation:

In this example, the Macro.escape/2 function is used to compile the code string into an AST. The :strict option is passed as the second argument to Macro.escape to ensure that the code is compiled in strict mode, which means that all variables must be declared before they are used. The Macro.to_string/1 function is then used to convert the AST back into a string of Elixir code. Finally, the Code.string_to_quoted/1 function is used to parse the code string and return a tuple containing the function name and the function itself.

This approach has the advantage of being more efficient than Code.eval_string, since the code is only compiled once and then stored as a quoted expression, rather than being compiled every time it is called. It also has the advantage of being safer than Code.eval_string, since it does not allow arbitrary code to be executed. However, it is a bit more complex to use and requires a deeper understanding of Elixir’s macro system.

Most Liked

al2o3cr

al2o3cr

As is pretty common with ChatGPT, some parts of this are outright hallucinations:

  • there is no strict option to Macro.escape
  • Macro.escape does not compile strings into ASTs; if you pass it a string it will return it unchanged
  • Code.string_to_quoted (no !) does not return an AST, it returns either {:ok, ast} or an error tuple
  • the result of Code.string_to_quoted has not been “compiled”, it has been parsed into an AST ready to be compiled

But some parts are mostly correct. There is a relationship between Code.eval_string and Code.string_to_quoted! + Code.eval_quoted because they both make use of the same underlying compiler machinery.

Code.eval_string has three steps:

  • prepare an env with env_for_eval
  • convert the supplied string to forms with :elixir.string_to_quoted!
  • evaluate the forms by calling :elixir.eval_forms

Code.string_to_quoted! does only the middle step:

while Code.eval_quoted does the first and last steps:

A minor detail: :elixir.eval_quoted does a tiny bit of argument reformatting before calling :elixir.eval_forms


As to your original question, the above analysis should make clear that Code.string_to_quoted! at boot + Code.eval_quoted invoked over and over will be faster than Code.eval_string invoked over and over since it does the string_to_quoted! part once instead of over and over (and otherwise does the same thing).

An even faster alternative would be:

  • at boot, parse all the AST once with Code.string_to_quoted!
  • at boot, take all those AST fragments and stitch them together into a module definition
  • call the functions over and over with apply, at normal speed for compiled code

IMO a bigger question is “what happens when one of these functions is configured with a fatal error, like closing a block with ned?”

  • Code.eval_string will crash with an exception when you try to run the function
  • Code.string_to_quoted! called at boot-time will crash with an exception and prevent application startup
  • Code.string_to_quoted (note no !) will return an error tuple explaining the situation

Your application’s specific needs should help you decide which of these is desirable / acceptable.

Where Next?

Popular in Questions Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement