Skip to content

Commit

Permalink
Lint: extract the arithmetic for cleaner code
Browse files Browse the repository at this point in the history
  • Loading branch information
bchamagne authored and samuelmanzanera committed Apr 21, 2023
1 parent a2285a5 commit 6f986f0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 66 deletions.
23 changes: 23 additions & 0 deletions lib/archethic/contracts/interpreter/ast_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,27 @@ defmodule Archethic.Contracts.Interpreter.ASTHelper do
"""
def wrap_in_block(ast = {:__block__, _, _}), do: ast
def wrap_in_block(ast), do: {:__block__, [], [ast]}

@doc """
Delegate the arithmetic to the Decimal library
"""
@spec decimal_arithmetic(Macro.t(), number(), number()) :: float()
def decimal_arithmetic(ast, lhs, rhs) do
operation =
case ast do
:* -> &Decimal.mult/2
:/ -> &Decimal.div/2
:+ -> &Decimal.add/2
:- -> &Decimal.sub/2
end

# the `0.0 + x` is used to cast integers to floats
Decimal.to_float(
Decimal.round(
operation.(Decimal.from_float(0.0 + lhs), Decimal.from_float(0.0 + rhs)),
8,
:floor
)
)
end
end
68 changes: 2 additions & 66 deletions lib/archethic/contracts/interpreter/common_interpreter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -361,74 +361,10 @@ defmodule Archethic.Contracts.Interpreter.CommonInterpreter do
end

# BigInt mathematics to avoid floating point issues
# the `0.0 + x` is used to cast integers to floats
def postwalk(_node = {:*, meta, [lhs, rhs]}, acc) do
def postwalk(_node = {ast, meta, [lhs, rhs]}, acc) when ast in [:*, :/, :+, :-] do
new_node =
quote line: Keyword.fetch!(meta, :line) do
Decimal.to_float(
Decimal.round(
Decimal.mult(
Decimal.from_float(0.0 + unquote(lhs)),
Decimal.from_float(0.0 + unquote(rhs))
),
8,
:floor
)
)
end

{new_node, acc}
end

def postwalk(_node = {:/, meta, [lhs, rhs]}, acc) do
new_node =
quote line: Keyword.fetch!(meta, :line) do
Decimal.to_float(
Decimal.round(
Decimal.div(
Decimal.from_float(0.0 + unquote(lhs)),
Decimal.from_float(0.0 + unquote(rhs))
),
8,
:floor
)
)
end

{new_node, acc}
end

def postwalk(_node = {:+, meta, [lhs, rhs]}, acc) do
new_node =
quote line: Keyword.fetch!(meta, :line) do
Decimal.to_float(
Decimal.round(
Decimal.add(
Decimal.from_float(0.0 + unquote(lhs)),
Decimal.from_float(0.0 + unquote(rhs))
),
8,
:floor
)
)
end

{new_node, acc}
end

def postwalk(_node = {:-, meta, [lhs, rhs]}, acc) do
new_node =
quote line: Keyword.fetch!(meta, :line) do
Decimal.to_float(
Decimal.round(
Decimal.sub(
Decimal.from_float(0.0 + unquote(lhs)),
Decimal.from_float(0.0 + unquote(rhs))
),
8,
:floor
)
)
AST.decimal_arithmetic(unquote(ast), unquote(lhs), unquote(rhs))
end

{new_node, acc}
Expand Down

0 comments on commit 6f986f0

Please sign in to comment.