Skip to content

Commit 462cf69

Browse files
committed
fix: do not optimize built-in calls
Sentences like: LET c = USR(x) are optimized if c var is not used. But the built-in call must be executed if it has side-effects. Thse builtins are: IN, RND and USR
1 parent 700cc31 commit 462cf69

3 files changed

Lines changed: 18 additions & 11 deletions

File tree

src/api/optimize.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -321,16 +321,20 @@ def visit_LET(self, node):
321321
lvalue = node.children[0]
322322
if self.O_LEVEL > 1 and not lvalue.accessed:
323323
warning_not_used(lvalue.lineno, lvalue.name, fname=lvalue.filename)
324-
block = symbols.BLOCK(
325-
*[
326-
symbols.CALL(x.entry, x.args, x.lineno, lvalue.filename)
327-
for x in self.filter_inorder(
328-
node.children[1],
329-
lambda x: x.token == "FUNCCALL",
330-
lambda x: x.token != "FUNCTION",
331-
)
332-
]
333-
)
324+
nodes = [
325+
symbols.CALL(x.entry, x.args, x.lineno, lvalue.filename) if x.token == "FUNCCALL" else x
326+
for x in self.filter_inorder(
327+
node.children[1],
328+
lambda x: x.token in ("FUNCCALL", "BUILTIN"),
329+
lambda x: x.token != "FUNCTION",
330+
)
331+
if x.token == "FUNCCALL" or getattr(x, "fname") in {"IN", "RND", "USR"}
332+
]
333+
for node_ in nodes:
334+
if node_.token == "BUILTIN":
335+
node_.discard_result = True
336+
337+
block = symbols.BLOCK(*nodes)
334338
yield block
335339
else:
336340
yield (yield self.generic_visit(node))

src/arch/z80/visitor/translator.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ def visit_BUILTIN(self, node):
152152
att = f"visit_{node.fname}"
153153
if hasattr(bvisitor, att):
154154
yield getattr(bvisitor, att)(node)
155+
if node.discard_result:
156+
self.ic_fparam(node.type_, optemps.new_t())
155157
return
156158

157159
raise InvalidBuiltinFunctionError(node.fname)

src/symbols/builtin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414

1515
class SymbolBUILTIN(Symbol):
16-
"""Defines an BUILTIN function e.g. INKEY$(), RND() or LEN"""
16+
"""Defines a BUILTIN function e.g. INKEY$(), RND() or LEN"""
1717

1818
def __init__(self, lineno, fname, type_=None, *operands):
1919
assert isinstance(lineno, int)
@@ -22,6 +22,7 @@ def __init__(self, lineno, fname, type_=None, *operands):
2222
self.lineno = lineno
2323
self.fname = fname
2424
self.type_ = type_
25+
self.discard_result = False # Whether to discard the return value of the function
2526

2627
@property
2728
def type_(self):

0 commit comments

Comments
 (0)