Current section
Files
Jump to
Current section
Files
lib/rustq/codegen.ex
defmodule RustQ.Codegen do
@moduledoc """
Generates RustQ's native AST support crate fragments.
"""
alias RustQ.Codegen.DecoderHelpers
alias RustQ.Codegen.Decoders
alias RustQ.Codegen.Dispatch
alias RustQ.Codegen.Helpers
alias RustQ.Codegen.Modules
alias RustQ.Rust.AST.Builder, as: A
alias RustQ.Rust.AST.Render
def generated_ast_support do
[
A.use({[:rustler], [:Atom, :Env, :NifResult, :Term]}),
A.use(
{[:syn],
[
:Arm,
:Expr,
:Field,
:FnArg,
:Item,
:ItemConst,
:ItemEnum,
:ItemFn,
:ItemImpl,
:ItemMod,
:ItemStruct,
:ItemStatic,
:ItemType,
:ItemUse,
:Pat,
:Path,
:Stmt,
:Type,
:Variant
]}
),
Modules.asts(),
Helpers.asts(),
DecoderHelpers.asts(),
Dispatch.asts(),
Decoders.asts()
]
|> List.flatten()
|> Render.render_file()
|> then(&"// This file is generated by RustQ. Do not edit by hand.\n\n#{&1}")
|> format_rust()
end
defp format_rust(source) do
path =
Path.join(System.tmp_dir!(), "rustq_generated_#{System.unique_integer([:positive])}.rs")
File.write!(path, source)
try do
case System.cmd("rustfmt", ["--edition", "2021", path], stderr_to_stdout: true) do
{_output, 0} -> File.read!(path)
{_output, _status} -> source
end
after
File.rm(path)
end
rescue
ErlangError -> source
end
end