Skip to content
This repository was archived by the owner on May 21, 2025. It is now read-only.

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

Open
wants to merge 2 commits 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
16 changes: 15 additions & 1 deletion registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,21 @@ 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:
if arg.is_constant() and (arg < 0):
# Simplify additions of negative constants:
# Use (a - 1) instead of (a + -1)
result += " - %s" % stc(-arg)
else:
result += " + %s" % 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