Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

registers.py: Fix subtractions in generated C code #1099

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,22 @@ def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True):
elif isinstance(expression, sympy.Symbol):
return sym_to_c(expression)
elif isinstance(expression, sympy.Add):
return "(" + " + ".join(stc(t) for t in reversed(expression.args)) + ")"
args = list(reversed(expression.args))
result = ""
for i in range(len(args)):
arg = args[i]
is_first = (i == 0)
if is_first:
result += stc(arg)
else:
# Simplify additions of negative constants:
# Use (a - 1) instead of (a + -1)
negative_constant = arg.is_constant() and (arg < 0)
result += " - " if negative_constant else " + "
if negative_constant:
arg = -arg # flip to positive
result += stc(arg)
return "(" + result + ")"
elif isinstance(expression, sympy.Mul):
return "(" + " * ".join(stc(t) for t in expression.args) + ")"
elif isinstance(expression, sympy.Pow):
Expand Down
Loading